Skip to content

Commit f4f0c6f

Browse files
committed
For OutsideLoop we should not suggest add 'block label in if block, or we wiil get another err: block label not supported here.
fixes rust-lang#123261
1 parent 60faa27 commit f4f0c6f

6 files changed

+286
-45
lines changed

compiler/rustc_passes/src/errors.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1103,7 +1103,7 @@ pub struct BreakInsideCoroutine<'a> {
11031103
pub struct OutsideLoop<'a> {
11041104
#[primary_span]
11051105
#[label]
1106-
pub span: Span,
1106+
pub spans: Vec<Span>,
11071107
pub name: &'a str,
11081108
pub is_break: bool,
11091109
#[subdiagnostic]
@@ -1115,7 +1115,7 @@ pub struct OutsideLoopSuggestion {
11151115
#[suggestion_part(code = "'block: ")]
11161116
pub block_span: Span,
11171117
#[suggestion_part(code = " 'block")]
1118-
pub break_span: Span,
1118+
pub break_spans: Vec<Span>,
11191119
}
11201120

11211121
#[derive(Diagnostic)]

compiler/rustc_passes/src/loops.rs

+144-24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::collections::BTreeMap;
2+
use std::fmt;
13
use Context::*;
24

35
use rustc_hir as hir;
@@ -25,22 +27,55 @@ enum Context {
2527
Closure(Span),
2628
Coroutine { coroutine_span: Span, kind: hir::CoroutineDesugaring, source: hir::CoroutineSource },
2729
UnlabeledBlock(Span),
30+
UnlabeledIfBlock(Span),
2831
LabeledBlock,
2932
Constant,
3033
}
3134

32-
#[derive(Copy, Clone)]
35+
#[derive(Clone)]
36+
struct BlockInfo {
37+
name: String,
38+
spans: Vec<Span>,
39+
suggs: Vec<Span>,
40+
}
41+
42+
#[derive(PartialEq)]
43+
enum BreakContextKind {
44+
Break,
45+
Continue,
46+
}
47+
48+
impl fmt::Display for BreakContextKind {
49+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50+
match self {
51+
BreakContextKind::Break => "break",
52+
BreakContextKind::Continue => "continue",
53+
}
54+
.fmt(f)
55+
}
56+
}
57+
58+
#[derive(Clone)]
3359
struct CheckLoopVisitor<'a, 'tcx> {
3460
sess: &'a Session,
3561
tcx: TyCtxt<'tcx>,
36-
cx: Context,
62+
// Keep track of a stack of contexts, so that suggestions
63+
// are not made for contexts where it would be incorrect,
64+
// such as adding a label for an `if`.
65+
// e.g. `if 'foo: {}` would be incorrect.
66+
cx_stack: Vec<Context>,
67+
block_breaks: BTreeMap<Span, BlockInfo>,
3768
}
3869

3970
fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
40-
tcx.hir().visit_item_likes_in_module(
41-
module_def_id,
42-
&mut CheckLoopVisitor { sess: tcx.sess, tcx, cx: Normal },
43-
);
71+
let mut check = CheckLoopVisitor {
72+
sess: tcx.sess,
73+
tcx,
74+
cx_stack: vec![Normal],
75+
block_breaks: Default::default(),
76+
};
77+
tcx.hir().visit_item_likes_in_module(module_def_id, &mut check);
78+
check.report_outside_loop_error();
4479
}
4580

4681
pub(crate) fn provide(providers: &mut Providers) {
@@ -83,6 +118,41 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
83118

84119
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
85120
match e.kind {
121+
hir::ExprKind::If(cond, then, else_opt) => {
122+
self.visit_expr(cond);
123+
if let hir::ExprKind::Block(ref b, None) = then.kind
124+
&& matches!(
125+
self.cx_stack.last(),
126+
Some(&Normal)
127+
| Some(&Constant)
128+
| Some(&UnlabeledBlock(_))
129+
| Some(&UnlabeledIfBlock(_))
130+
)
131+
{
132+
self.with_context(UnlabeledIfBlock(b.span.shrink_to_lo()), |v| {
133+
v.visit_block(b)
134+
});
135+
} else {
136+
self.visit_expr(then);
137+
}
138+
if let Some(else_expr) = else_opt {
139+
if let hir::ExprKind::Block(ref b, None) = else_expr.kind
140+
&& matches!(
141+
self.cx_stack.last(),
142+
Some(&Normal)
143+
| Some(&Constant)
144+
| Some(&UnlabeledBlock(_))
145+
| Some(&UnlabeledIfBlock(_))
146+
)
147+
{
148+
self.with_context(UnlabeledIfBlock(b.span.shrink_to_lo()), |v| {
149+
v.visit_block(b)
150+
});
151+
} else {
152+
self.visit_expr(else_expr);
153+
}
154+
}
155+
}
86156
hir::ExprKind::Loop(ref b, _, source, _) => {
87157
self.with_context(Loop(source), |v| v.visit_block(b));
88158
}
@@ -101,11 +171,14 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
101171
hir::ExprKind::Block(ref b, Some(_label)) => {
102172
self.with_context(LabeledBlock, |v| v.visit_block(b));
103173
}
104-
hir::ExprKind::Block(ref b, None) if matches!(self.cx, Fn) => {
174+
hir::ExprKind::Block(ref b, None) if matches!(self.cx_stack.last(), Some(&Fn)) => {
105175
self.with_context(Normal, |v| v.visit_block(b));
106176
}
107177
hir::ExprKind::Block(ref b, None)
108-
if matches!(self.cx, Normal | Constant | UnlabeledBlock(_)) =>
178+
if matches!(
179+
self.cx_stack.last(),
180+
Some(&Normal) | Some(&Constant) | Some(&UnlabeledBlock(_))
181+
) =>
109182
{
110183
self.with_context(UnlabeledBlock(b.span.shrink_to_lo()), |v| v.visit_block(b));
111184
}
@@ -178,7 +251,12 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
178251
Some(label) => sp_lo.with_hi(label.ident.span.hi()),
179252
None => sp_lo.shrink_to_lo(),
180253
};
181-
self.require_break_cx("break", e.span, label_sp);
254+
self.require_break_cx(
255+
BreakContextKind::Break,
256+
e.span,
257+
label_sp,
258+
self.cx_stack.len() - 1,
259+
);
182260
}
183261
hir::ExprKind::Continue(destination) => {
184262
self.require_label_in_labeled_block(e.span, &destination, "continue");
@@ -200,7 +278,12 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
200278
}
201279
Err(_) => {}
202280
}
203-
self.require_break_cx("continue", e.span, e.span)
281+
self.require_break_cx(
282+
BreakContextKind::Continue,
283+
e.span,
284+
e.span,
285+
self.cx_stack.len() - 1,
286+
)
204287
}
205288
_ => intravisit::walk_expr(self, e),
206289
}
@@ -212,18 +295,26 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
212295
where
213296
F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>),
214297
{
215-
let old_cx = self.cx;
216-
self.cx = cx;
298+
self.cx_stack.push(cx);
217299
f(self);
218-
self.cx = old_cx;
300+
self.cx_stack.pop();
219301
}
220302

221-
fn require_break_cx(&self, name: &str, span: Span, break_span: Span) {
222-
let is_break = name == "break";
223-
match self.cx {
303+
fn require_break_cx(
304+
&mut self,
305+
br_cx_kind: BreakContextKind,
306+
span: Span,
307+
break_span: Span,
308+
cx_pos: usize,
309+
) {
310+
match self.cx_stack[cx_pos] {
224311
LabeledBlock | Loop(_) => {}
225312
Closure(closure_span) => {
226-
self.sess.dcx().emit_err(BreakInsideClosure { span, closure_span, name });
313+
self.sess.dcx().emit_err(BreakInsideClosure {
314+
span,
315+
closure_span,
316+
name: &br_cx_kind.to_string(),
317+
});
227318
}
228319
Coroutine { coroutine_span, kind, source } => {
229320
let kind = match kind {
@@ -239,17 +330,32 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
239330
self.sess.dcx().emit_err(BreakInsideCoroutine {
240331
span,
241332
coroutine_span,
242-
name,
333+
name: &br_cx_kind.to_string(),
243334
kind,
244335
source,
245336
});
246337
}
247-
UnlabeledBlock(block_span) if is_break && block_span.eq_ctxt(break_span) => {
248-
let suggestion = Some(OutsideLoopSuggestion { block_span, break_span });
249-
self.sess.dcx().emit_err(OutsideLoop { span, name, is_break, suggestion });
338+
UnlabeledBlock(block_span)
339+
if br_cx_kind == BreakContextKind::Break && block_span.eq_ctxt(break_span) =>
340+
{
341+
let block = self.block_breaks.entry(block_span).or_insert_with(|| BlockInfo {
342+
name: br_cx_kind.to_string(),
343+
spans: vec![],
344+
suggs: vec![],
345+
});
346+
block.spans.push(span);
347+
block.suggs.push(break_span);
348+
}
349+
UnlabeledIfBlock(_) if br_cx_kind == BreakContextKind::Break => {
350+
self.require_break_cx(br_cx_kind, span, break_span, cx_pos - 1);
250351
}
251-
Normal | Constant | Fn | UnlabeledBlock(_) => {
252-
self.sess.dcx().emit_err(OutsideLoop { span, name, is_break, suggestion: None });
352+
Normal | Constant | Fn | UnlabeledBlock(_) | UnlabeledIfBlock(_) => {
353+
self.sess.dcx().emit_err(OutsideLoop {
354+
spans: vec![span],
355+
name: &br_cx_kind.to_string(),
356+
is_break: br_cx_kind == BreakContextKind::Break,
357+
suggestion: None,
358+
});
253359
}
254360
}
255361
}
@@ -261,12 +367,26 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
261367
cf_type: &str,
262368
) -> bool {
263369
if !span.is_desugaring(DesugaringKind::QuestionMark)
264-
&& self.cx == LabeledBlock
370+
&& self.cx_stack.last() == Some(&LabeledBlock)
265371
&& label.label.is_none()
266372
{
267373
self.sess.dcx().emit_err(UnlabeledInLabeledBlock { span, cf_type });
268374
return true;
269375
}
270376
false
271377
}
378+
379+
fn report_outside_loop_error(&mut self) {
380+
for (s, block) in &self.block_breaks {
381+
self.sess.dcx().emit_err(OutsideLoop {
382+
spans: block.spans.clone(),
383+
name: &block.name,
384+
is_break: true,
385+
suggestion: Some(OutsideLoopSuggestion {
386+
block_span: *s,
387+
break_spans: block.suggs.clone(),
388+
}),
389+
});
390+
}
391+
}
272392
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//@ run-rustfix
2+
3+
#![allow(unused)]
4+
5+
fn main() {
6+
let n = 1;
7+
let m = 2;
8+
let x = 'block: {
9+
if n == 0 {
10+
break 'block 1; //~ ERROR [E0268]
11+
} else {
12+
break 'block 2;
13+
}
14+
};
15+
16+
let y = 'block: {
17+
if n == 0 {
18+
break 'block 1; //~ ERROR [E0268]
19+
}
20+
break 'block 0;
21+
};
22+
23+
let z = 'block: {
24+
if n == 0 {
25+
if m > 1 {
26+
break 'block 3; //~ ERROR [E0268]
27+
}
28+
}
29+
break 'block 1;
30+
};
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//@ run-rustfix
2+
3+
#![allow(unused)]
4+
5+
fn main() {
6+
let n = 1;
7+
let m = 2;
8+
let x = {
9+
if n == 0 {
10+
break 1; //~ ERROR [E0268]
11+
} else {
12+
break 2;
13+
}
14+
};
15+
16+
let y = {
17+
if n == 0 {
18+
break 1; //~ ERROR [E0268]
19+
}
20+
break 0;
21+
};
22+
23+
let z = {
24+
if n == 0 {
25+
if m > 1 {
26+
break 3; //~ ERROR [E0268]
27+
}
28+
}
29+
break 1;
30+
};
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
error[E0268]: `break` outside of a loop or labeled block
2+
--> $DIR/loop-if-else-break-issue-123261.rs:10:13
3+
|
4+
LL | break 1;
5+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
6+
LL | } else {
7+
LL | break 2;
8+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
9+
|
10+
help: consider labeling this block to be able to break within it
11+
|
12+
LL ~ let x = 'block: {
13+
LL | if n == 0 {
14+
LL ~ break 'block 1;
15+
LL | } else {
16+
LL ~ break 'block 2;
17+
|
18+
19+
error[E0268]: `break` outside of a loop or labeled block
20+
--> $DIR/loop-if-else-break-issue-123261.rs:18:13
21+
|
22+
LL | break 1;
23+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
24+
LL | }
25+
LL | break 0;
26+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
27+
|
28+
help: consider labeling this block to be able to break within it
29+
|
30+
LL ~ let y = 'block: {
31+
LL | if n == 0 {
32+
LL ~ break 'block 1;
33+
LL | }
34+
LL ~ break 'block 0;
35+
|
36+
37+
error[E0268]: `break` outside of a loop or labeled block
38+
--> $DIR/loop-if-else-break-issue-123261.rs:26:17
39+
|
40+
LL | break 3;
41+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
42+
...
43+
LL | break 1;
44+
| ^^^^^^^ cannot `break` outside of a loop or labeled block
45+
|
46+
help: consider labeling this block to be able to break within it
47+
|
48+
LL ~ let z = 'block: {
49+
LL | if n == 0 {
50+
LL | if m > 1 {
51+
LL ~ break 'block 3;
52+
LL | }
53+
LL | }
54+
LL ~ break 'block 1;
55+
|
56+
57+
error: aborting due to 3 previous errors
58+
59+
For more information about this error, try `rustc --explain E0268`.

0 commit comments

Comments
 (0)