Skip to content

Diagnostics: improve error message for incorrect inner attribute #89566

Closed

Description

I was assisting someone new to Rust and they were confused by an error message. This is the complete file of code they had written:

#![derive(Debug)]
struct Test {
    s: String,
}

fn main() {
}

Using rustc 1.55.0 (c8dfcfe04 2021-09-06) and rustc 1.57.0-nightly (f03eb6b 2021-10-02), the compiler outputs the following error (playground link):

error: cannot determine resolution for the attribute macro `derive`
 --> src/main.rs:1:4
  |
1 | #![derive(Debug)]
  |    ^^^^^^
  |
  = note: import resolution is stuck, try simplifying macro imports

The fix is to use #[derive], an outer attribute, rather than #![derive], an inner attribute, but the compiler's error does not make that clear. And its suggestion to simplify macro imports doesn't help, as from the user's perspective, nothing is being imported in this source file!

I think a more specific error message that checks whether the inner attribute's name would fit as an outer attribute would be helpful here. A suggestion to remove the ! would be even better. Annoyingly, having #! at the start of the file looked correct as it resembles a shebang.

Note that there is a good error for using #![] instead of #[] in the general case. It even mentions the difference between inner and outer attributes in its message. It was just bad luck that this particular struct happened to be at the very start of the source file, so that error was not displayed.

I also spotted that in issue #67107, which has a very similar piece of example code, the compiler used to provide a suggestion to "try an outer attribute". But, running that example on the latest stable and nightly, it looks like that suggestion is not being produced anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)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