rust-lang / rust-lang/rust

unreachable_code warnings for code that can't be removed

Open
#158,520 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lints C-bug D-confusing L-unreachable_code T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Let's say we have some trait Foo, and an API that accepts a closure that returns a Foo:

pub trait Foo {
    fn foo();
}

pub fn do_stuff<F, T>(new_foo: F)
where
    F: FnOnce(i32) -> T,
    T: Foo,
{
    todo!()
}

Sometimes it can be necessary to call do_stuff with a closure that panics if it is called. For example, in tests that cover scenarios under which do_stuff shouldn't actually get to the point of calling new_foo. This can be annoying, because we can't do the obvious thing:

do_stuff(|_| panic!("shouldn't be called"));
error[E0277]: the trait bound `!: Foo` is not satisfied

Instead, we have to actually give the closure a return type:

struct UnusedFoo;

impl Foo for UnusedFoo {
    fn foo() {
        panic!("shouldn't be called")
    }
}

do_stuff(|_| {
    panic!("shouldn't be called");
    UnusedFoo
});

This does work. But the bug report here is that the compiler gives me a warning saying the UnusedFoo result is unreachable, implying that I should go back to the version that doesn't work (playground):

warning: unreachable expression
  --> src/lib.rs:24:9
   |
23 |         panic!("shouldn't be called");
   |         ----------------------------- any code following this expression is unreachable
24 |         UnusedFoo
   |         ^^^^^^^^^ unreachable expression

The compiler shouldn't issue an unreachable warning for code which, when removed, causes an error. This warning should only be for issues that are actionable, i.e. the unreachable code can actually be removed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust Playground reproducer in the issue and inspect the compiler path that emits the unreachable expression warning. Verify that removing UnusedFoo still produces the !: Foo trait-bound error, and consider the warning resolved when this required-but-unreachable expression no longer triggers a diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.