Skip to content

Lint Idea: Call may cause panic #2942

Closed
@jamesmunns

Description

@jamesmunns

It would be nice to have a lint that would inform me if a call I make could panic, and ideally if possible, recommend an alternative that uses Option or Result to handle the error directly. For example, with the following input:

fn main() {
    use std::time::Duration;
    
    let x = Duration::from_secs(2);
    let y = Duration::from_secs(1);
    
    println!("{:?}", y - x);
}

I would like a warning that looks something like this:

src/main.rs
   |
 7 | println!("{:?}", y - x);
   |                    ^ warning: Sub<Duration> for Duration may panic due to this:

src/core/time.rs:428
     | fn sub(self, rhs: Duration) -> Duration {
 428 |     self.checked_sub(rhs).expect("overflow when subtracting durations")
     | }
     |                          ^^^^^^^ call to `expect` could fail

Consider using `Duration::checked_sub()` instead

I imagine this could fall into "Halting problem" territory, but I imagine the process would go something like:

  • find every operator or function call for a given program (you know, no big deal)
  • obtain the full possible branching graph for that call/operator (also nbd)
  • look for unwrap/expect/panic
  • Check if any steps in the call graph to get to the panic have some kind of recommended alternative. Maybe possible to cover the std lib, though supporting external libraries/versions would be difficult to say the least. If no alternative, at least warn

I'm very open to hear things like "this is possible, but difficult", "this is impossible, here is where we discussed previously", etc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions