Skip to content

Provide a better error when code is put outside of a function #92615

@meithecatte

Description

@meithecatte

Examples in the documentation often provide excerpts instead of full programs. A beginner might try compiling that code directly, and be confused that it doesn't work. Currently, the error messages for that case don't provide any hints as to what might be wrong:

error: expected item, found keyword `let`
 --> src/lib.rs:1:1
  |
1 | let data = [4, 8, 15, 16, 23, 42];
  | ^^^ expected item
error: expected one of `!` or `::`, found `(`
 --> src/lib.rs:2:10
  |
2 | fs::write("foo.txt", "Hello!").unwrap();
  |          ^ expected one of `!` or `::`
error: macro expansion ignores token `{` and any following
   |
  ::: src/lib.rs:1:1
   |
1  |   println!("Hello, world!");
   |   ------------------------- caused by the macro expansion here
   |
   = note: the usage of `println!` is likely invalid in item context

Ideally the output should look like:

error: `let` is invalid outside of a function
 --> src/lib.rs:1:1
  |
1 | let data = [4, 8, 15, 16, 23, 42];
  | ^^^ not valid outside of a function
help: put your code in a `main` function:
  | fn main() {
  |     let data = [4, 8, 15, 16, 23, 42];
  |     for n in data {
  |         dbg!(n);
  |     }
  | }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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