Skip to content

Parser shows error at wrong place if closing parenthesis is missing in if optional #7186

@frmdstryr

Description

@frmdstryr

I've hit this too many times by accident now... so another minor nitpick/potential error message improvement... or possibly a parser issue.

If you forget to add a closing paren ) in an optional if the error always points to the end of the if block however it should know right at the first | that a paren is missing.

const std = @import("std");

fn getOptional(key: []const u8, default: []const u8) ?[]const u8 {
    if (std.mem.eql(u8, key, "special")) return key;
    return default;  
}

pub fn main() !void {
    if (getOptional("foo") |value| {
        std.log.warn("{}", .{value});
    } else {
        std.log.warn("missing", .{});
    }
}

https://zig.godbolt.org/z/Eb71E5

<source>:11:7: error: expected token ')', found 'else'
    } else {
      ^
ASM generation compiler returned: 1
<source>:11:7: error: expected token ')', found 'else'
    } else {
      ^
Execution build compiler returned: 1

After scanning through the stage2 parser a little it seems like the error is at the end because the Expr seems to be capturing the Payload so any valid expression before the closing paren puts the error at the bottom while.

Edit this might be a parser bug... as https://zig.godbolt.org/z/fh99P1 gives the same error

const std = @import("std");

fn getOptional(key: []const u8, default: []const u8) ?[]const u8 {
    if (std.mem.eql(u8, key, "special")) return key;
    return default;  
}

pub fn main() !void {
    if (getOptional("test", "bar") |t| t |foo| foo |bar| bar |bas| bas |value| {
        std.log.warn("{}", .{value});
    } else {
        std.log.warn("missing", .{});
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    error messageThis issue points out an error message that is unhelpful and should be improved.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions