Skip to content

Better error message for .. in struct patterns not in last position #49257

Closed
@Badel2

Description

@Badel2

Since the let P(.., y) = p; syntax is allowed in unnamed patterns, people will try the same in named patterns, let P { .., y } = p;,and it won't work. Right now the error is

error: expected `}`, found `,`
   |
13 |     let Point { .., y } = a;
   |                   ^ expected `}`

followed by other errors about "pattern does not mention field x". Test code playground link

struct Point { x: u8, y: u8 }
struct P(u8, u8);

fn main() {
    // Unnamed patterns allow `.., y`
    let p = P(0, 0);
    let P(x, ..) = p;
    let P(.., y) = p;
    
    // But named patterns don't
    let a = Point { x: 0, y: 0 };
    let Point { x, .. } = a; // works
    let Point { .., y } = a; // lots of errors
}

Adding a clear error message should be pretty easy, just check if there is a comma after DotDot and display a better error message ".. must always be the last field, and it cannot have a trailing comma". Actually, I think this is the code that checks if .. is followed by a }, so adding the , check should be pretty straight-forward:

if self.token != token::CloseDelim(token::Brace) {
let token_str = self.this_token_to_string();
let mut err = self.fatal(&format!("expected `{}`, found `{}`", "}", token_str));
err.span_label(self.span, "expected `}`");
return Err(err);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions