Skip to content

Misleading error for missing comma/semicolon in array literal #96791

Closed
@LyricLy

Description

@LyricLy

Given the following code: Playground

fn main() {
    let v = [1
    2];
}

The current output is:

error: expected `;`, found `2`
 --> test.rs:2:15
  |
2 |     let v = [1
  |               ^ help: add `;` here
3 |     2];
  |     - unexpected token

error: expected one of `.`, `;`, `?`, `}`, or an operator, found `]`
 --> test.rs:3:6
  |
3 |     2];
  |      ^ expected one of `.`, `;`, `?`, `}`, or an operator

error: aborting due to 2 previous errors

Ideally the output should look like:

error: expected one of `,`, `.`, `;`, `?`, `]`, or an operator, found `2`
 --> test.rs:3:5
  |
2 |     let v = [1
  |               -
  |               |
  |               expected one of `,`, `.`, `;`, `?`, `]`, or an operator
3 |     2];
  |     ^ unexpected token

The error implies that ; is the only valid token at the end of the second line, and that the third line is being considered a separate statement from the second line, probably due to a consequence of the fault-tolerant parsing machinery.

Reasonable output is given when the newline is removed or there is more than 2 elements:

error: expected one of `,`, `.`, `;`, `?`, `]`, or an operator, found `2`
 --> test.rs:2:16
  |
2 |     let v = [1 2
  |                ^ expected one of `,`, `.`, `;`, `?`, `]`, or an operator

error: aborting due to previous error
error: expected one of `,`, `.`, `?`, `]`, or an operator, found `3`
 --> test.rs:3:5
  |
2 |     let v = [1, 2
  |                  -
  |                  |
  |                  expected one of `,`, `.`, `?`, `]`, or an operator
  |                  help: missing `,`
3 |     3];
  |     ^ unexpected token

error: aborting due to previous error

This should be fixed because it is confusing in less clear situations such as the following, especially where someone might expect the comma to be implicit due to the behaviour of match.

let v = [
    {
        1
    }
    {
        2
    }
];

This happens in every edition and on both stable and nightly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions