Skip to content

Permit -> _ return types for improved diagnostics #56132

Closed
@varkor

Description

@varkor

Consider (the invalid Rust code containing) a function that returns a value, but has no return type:

fn foo() {
    0u8
}

fn main() {
    let _: u8 = foo();
}

Currently, the compiler produces these errors:

error[E0308]: mismatched types
 --> src/main.rs:2:5
  |
1 | fn foo() {
  |          - help: try adding a return type: `-> u8`
2 |     0u8
  |     ^^^ expected (), found u8
  |
  = note: expected type `()`
             found type `u8`

error[E0308]: mismatched types
 --> src/main.rs:6:17
  |
6 |     let _: u8 = foo();
  |                 ^^^^^ expected u8, found ()
  |
  = note: expected type `u8`
             found type `()`

error: aborting due to 2 previous errors

In theory, the only problem is the missing return type, which, if provided, would cause the code to compile successfully.

The compiler knows what the return type should be here, and could potentially interpret the rest of the program as if the correct return type were given.

This issue proposes giving special treatment in the compiler for diagnostics only (note that this is not a language change) to the syntax -> _ for return types. This would report a normal error for a missing return type (no extra code would compile after this change), but would otherwise treat the function as having the missing return type. A machine-applicable suggestion would be provided to replace _ with the correct return type.

For example:

fn foo() -> _ {
    0u8
}

fn main() {
    let _: u8 = foo();
}
error[E0121]: the type placeholder `_` is not allowed within types on item signatures
 --> src/main.rs:1:13
  |
1 | fn foo() -> _ {
  |             ^ not allowed in type signatures
  |             - help: replace `_` with the correct return type: `u8`

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.P-highHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions