Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parser: provide better suggestions and errors on closures with braces missing #108388

Merged

Commits on Feb 23, 2023

  1. parser: provide better errors on closures with braces missing

    We currently provide wrong suggestions and unhelpful errors on closure
    bodies with braces missing. For example, given the following code:
    
    ```
    fn main() {
        let _x = Box::new(|x|x+1;);
    }
    ```
    
    the current output is like this:
    
    ```
    error: expected expression, found `)`
     --> ./main.rs:2:30
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                              ^ expected expression
    
    error: closure bodies that contain statements must be surrounded by braces
     --> ./main.rs:2:25
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                         ^
    3 | }
      | ^
      |
    
    ...
    
    help: try adding braces
      |
    2 ~     let _x = Box::new(|x| {x+1;);
    3 ~ }}
    
    ...
    
    error: expected `;`, found `}`
     --> ./main.rs:2:32
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                                ^ help: add `;` here
    3 | }
      | - unexpected token
    
    error: aborting due to 3 previous errors
    ```
    
    This commit allows outputting correct suggestions and errors. The above
    code would output like this:
    
    ```
    error: closure bodies that contain statements must be surrounded by braces
     --> ./main.rs:2:25
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                         ^    ^
      |
    note: statement found outside of a block
     --> ./main.rs:2:29
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                          ---^ this `;` turns the preceding closure into a statement
      |                          |
      |                          this expression is a statement because of the trailing semicolon
    note: the closure body may be incorrectly delimited
     --> ./main.rs:2:23
      |
    2 |     let _x = Box::new(|x|x+1;);
      |                       ^^^^^^ - ...but likely you meant the closure to end here
      |                       |
      |                       this is the parsed closure...
    help: try adding braces
      |
    2 |     let _x = Box::new(|x| {x+1;});
      |                           +    +
    
    error: aborting due to previous error
    ```
    ohno418 committed Feb 23, 2023
    Configuration menu
    Copy the full SHA
    0e42298 View commit details
    Browse the repository at this point in the history