Skip to content

Commit 5a440f1

Browse files
committed
Fix control flow check for breaking with diverging values
1 parent 1d27267 commit 5a440f1

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

compiler/rustc_typeck/src/check/expr.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
627627
assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
628628
}
629629

630-
ctxt.may_break = true;
630+
// If we encountered a `break`, then (no surprise) it may be possible to break from the
631+
// loop... unless the value being returned from the loop diverges itself, e.g.
632+
// `break return 5` or `break loop {}`.
633+
ctxt.may_break |= !e_ty.is_never();
631634

632635
// the type of a `break` is always `!`, since it diverges
633636
tcx.types.never

src/test/ui/break-diverging-value.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fn loop_break_return() -> i32 {
2+
let loop_value = loop { break return 0 }; // ok
3+
}
4+
5+
fn loop_break_loop() -> i32 {
6+
let loop_value = loop { break loop {} }; // ok
7+
}
8+
9+
fn loop_break_break() -> i32 { //~ ERROR mismatched types
10+
let loop_value = loop { break break };
11+
}
12+
13+
fn main() {}
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/break-diverging-value.rs:9:26
3+
|
4+
LL | fn loop_break_break() -> i32 {
5+
| ---------------- ^^^ expected `i32`, found `()`
6+
| |
7+
| implicitly returns `()` as its body has no tail or `return` expression
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)