Skip to content

Fix control flow check for breaking with diverging values #77317

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

Merged
merged 3 commits into from
Oct 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion compiler/rustc_typeck/src/check/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
}

ctxt.may_break = true;
// If we encountered a `break`, then (no surprise) it may be possible to break from the
// loop... unless the value being returned from the loop diverges itself, e.g.
// `break return 5` or `break loop {}`.
ctxt.may_break |= !self.diverges.get().is_always();

// the type of a `break` is always `!`, since it diverges
tcx.types.never
Expand Down
37 changes: 37 additions & 0 deletions src/test/ui/break-diverging-value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#![feature(never_type)]

fn loop_break_return() -> i32 {
let loop_value = loop { break return 0 }; // ok
}

fn loop_break_loop() -> i32 {
let loop_value = loop { break loop {} }; // ok
}

fn loop_break_break() -> i32 { //~ ERROR mismatched types
let loop_value = loop { break break };
}

fn loop_break_return_2() -> i32 {
let loop_value = loop { break { return 0; () } }; // ok
}

enum Void {}

fn get_void() -> Void {
panic!()
}

fn loop_break_void() -> i32 { //~ ERROR mismatched types
let loop_value = loop { break get_void() };
}

fn get_never() -> ! {
panic!()
}

fn loop_break_never() -> i32 {
let loop_value = loop { break get_never() }; // ok
}

fn main() {}
19 changes: 19 additions & 0 deletions src/test/ui/break-diverging-value.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
error[E0308]: mismatched types
--> $DIR/break-diverging-value.rs:11:26
|
LL | fn loop_break_break() -> i32 {
| ---------------- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression

error[E0308]: mismatched types
--> $DIR/break-diverging-value.rs:25:25
|
LL | fn loop_break_void() -> i32 {
| --------------- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0308`.