Skip to content

should the orelse operator be right-associative? #15108

@torque

Description

@torque

Consider the following code:

pub fn main() void {
    const a: ?bool = false;
    const b: ?bool = null;
    _ = a orelse b orelse @panic("oh, no");
}

As of zig 0.11.0-dev.2298+5d63d1115, this fails to compile with the following error message:

example.zig:4:20: error: expected optional type, found 'bool'
_ = a orelse b orelse @panic("oh, no");
               ^~~~~~~~~~~~~~~~~~~~~~~

This error message indicates that the line is being parsed in a left-associative fashion, i.e.

_ = (a orelse b) orelse @compileError("should not reach this");

In my opinion, the more intuitive behavior would be for orelse to be right-associative, i.e.

_ = a orelse (b orelse @compileError("should not reach this"));

If this wasn't an explicit design choice, I think it makes sense to change it. Right-associativity would make orelse behave like a short-circuiting boolean operator, which I think is logical behavior given its naming and functionality. For directly applicable prior-art, both C#'s and Swift's null-coalescing operators are right-associative.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions