Skip to content

Provide a better error message for function pointers with generic parameters #103487

Closed
@fmease

Description

@fmease

Newcomers might attempt to write a “generic” function pointer like fn<T>(T) -> bool. In such case, the compiler should provide a better error message. Inspired by a recent Reddit thread I sadly cannot find anymore.

fn<'a>

Given the following code:

fn main() {
    let _: fn<'a>(&'a str) -> bool;
}

The compiler should mention that function pointers may not be generic or […] may not have generic parameters, suggest to move the lifetime(s) to a for<> parameter list (this should be machine-applicable in my judgement) and be able to recover:

- fn<'a>(&'a str) -> bool
+ for<'a> fn(&'a str) -> bool

For later reference, the current output is:

error: expected `(`, found `<`
 --> src/main.rs:2:14
  |
2 |     let _: fn<'a>(&'a str) -> bool;
  |         -    ^ expected `(`
  |         |
  |         while parsing the type for `_`

fn<T> / fn<const C: T>

Given the following code:

fn main() {
    let _: fn<T>(T) -> bool;
    let _: fn<const N: usize>([u8; N]);
}

The compiler should mention that function pointers may not be generic or […] may not have generic parameters and be able to recover emitting two diagnostics, one for each line.

The compiler could also suggest moving the generic parameter list further up to the owning function, struct, etc. if available. Note that this might not be what the user intended (since there is a semantic difference between hypothetical higher-ranked generics and normal ones) and therefore shouldn't be machine-applicable.

For later reference, the current output is:

error: expected `(`, found `<`
 --> src/main.rs:2:14
  |
2 |     let _: fn<T>(T) -> bool;
  |         -    ^ expected `(`
  |         |
  |         while parsing the type for `_`

@rustbot label A-parser A-suggestion-diagnostics D-newcomer-roadblock

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`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