Skip to content

Error when fn keyword is missing could be more explicit #125446

Closed
@hds

Description

@hds

Code

whoops() {}

fn main() {
    whoops();
}

Current output

error: expected one of `!` or `::`, found `(`
 --> src/main.rs:1:7
  |
1 | whoops() {}
  |       ^ expected one of `!` or `::`

error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

error: function definition is missing `fn` keyword
 --> src/main.rs:1:7
  |
1 | whoops() {}
  | ^ should be `fn whoops()`

Rationale and extra context

The current error appears to be based entirely on the syntax tree. However, adding a ! or :: in this case won't provide compilable code by itself.

It may be possible to determine that the incorrect code "looks like" a function definition which is missing the fn keyword in front of it (the author doesn't have the knowledge to say for sure). Especially in cases where the context doesn't permit calling a function (i.e. not inside another function).

This would provide immediately actionable diagnostics.

Other cases

A missing struct or enum keyword could be differentiated by the contents of the braces, or potentially from the case of the first character of the name (assuming it's correct).

Missing struct:

Whoops {
    value: u64,
}

Missing enum:

Whoops {
    OptionA,
    OptionB,
}

A unit struct is somewhat more ambiguous (if the name is capitalized correctly then there is a hint):

Whoops {}

Rust Version

rustc 1.78.0 (9b00956e5 2024-04-29)
binary: rustc
commit-hash: 9b00956e56009bab2aa15d7bff10916599e3d6d6
commit-date: 2024-04-29
host: x86_64-apple-darwin
release: 1.78.0
LLVM version: 18.1.2

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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