Skip to content

Consider desugaring the pattern in match to a let to improve error messages #14390

Closed
@huonw

Description

@huonw

Proposal: desugar the Some branch a for loop to Some(value) => { let <pattern> = value; ..., rather than Some(<pattern>) => { ... as we do now.

#[cfg(normal)]
fn main() {
    for &1 in [1].iter() {}
}

// expanded forms:

#[cfg(now)]
fn main() {
    match &mut [1].iter() {
        it => {
            loop {
                match it.next() {
                    None => break,
                    Some(&1) => {}
                }
            }
        }
    }
}

#[cfg(future)]
fn main() {
    match &mut [1].iter() {
        it => {
            loop {
                match it.next() {
                    None => break,
                    Some(value) => {
                        let &1 = value;
                    }
                }
            }
        }
    }
}
$ rustc patterns.rs --cfg normal
patterns.rs:3:5: 4:2 error: non-exhaustive patterns
patterns.rs:3     for &1 in [1].iter() {}
patterns.rs:4 }
error: aborting due to previous error

$ rustc patterns.rs --cfg now
patterns.rs:11:17: 14:18 error: non-exhaustive patterns
patterns.rs:11                 match it.next() {
patterns.rs:12                     None => break,
patterns.rs:13                     Some(&1) => {}
patterns.rs:14                 }
error: aborting due to previous error

$ rustc patterns.rs --cfg future
patterns.rs:28:29: 28:31 error: refutable pattern in local binding
patterns.rs:28                         let &1 = value;
                                           ^~
error: aborting due to previous error

Using the let version would give two advantages:

  • mentions that the pattern is refutable
  • allows the span of the error to point exactly at the pattern, rather than the whole for loop (annoying for beginners if the for has a large body).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions