Skip to content

Commit 7a5536b

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 #123261
1 parent 60faa27 commit 7a5536b

6 files changed

+284
-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

+142-24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::collections::BTreeMap;
12
use Context::*;
23

34
use rustc_hir as hir;
@@ -25,22 +26,54 @@ enum Context {
2526
Closure(Span),
2627
Coroutine { coroutine_span: Span, kind: hir::CoroutineDesugaring, source: hir::CoroutineSource },
2728
UnlabeledBlock(Span),
29+
UnlabeledIfBlock(Span),
2830
LabeledBlock,
2931
Constant,
3032
}
3133

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

3968
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-
);
69+
let mut check = CheckLoopVisitor {
70+
sess: tcx.sess,
71+
tcx,
72+
cx_stack: vec![Normal],
73+
block_breaks: Default::default(),
74+
};
75+
tcx.hir().visit_item_likes_in_module(module_def_id, &mut check);
76+
check.report_outside_loop_error();
4477
}
4578

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

84117
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
85118
match e.kind {
119+
hir::ExprKind::If(cond, then, else_opt) => {
120+
self.visit_expr(cond);
121+
if let hir::ExprKind::Block(ref b, None) = then.kind
122+
&& matches!(
123+
self.cx_stack.last(),
124+
Some(&Normal)
125+
| Some(&Constant)
126+
| Some(&UnlabeledBlock(_))
127+
| Some(&UnlabeledIfBlock(_))
128+
)
129+
{
130+
self.with_context(UnlabeledIfBlock(b.span.shrink_to_lo()), |v| {
131+
v.visit_block(b)
132+
});
133+
} else {
134+
self.visit_expr(then);
135+
}
136+
if let Some(else_expr) = else_opt {
137+
if let hir::ExprKind::Block(ref b, None) = else_expr.kind
138+
&& matches!(
139+
self.cx_stack.last(),
140+
Some(&Normal)
141+
| Some(&Constant)
142+
| Some(&UnlabeledBlock(_))
143+
| Some(&UnlabeledIfBlock(_))
144+
)
145+
{
146+
self.with_context(UnlabeledIfBlock(b.span.shrink_to_lo()), |v| {
147+
v.visit_block(b)
148+
});
149+
} else {
150+
self.visit_expr(else_expr);
151+
}
152+
}
153+
}
86154
hir::ExprKind::Loop(ref b, _, source, _) => {
87155
self.with_context(Loop(source), |v| v.visit_block(b));
88156
}
@@ -101,11 +169,14 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
101169
hir::ExprKind::Block(ref b, Some(_label)) => {
102170
self.with_context(LabeledBlock, |v| v.visit_block(b));
103171
}
104-
hir::ExprKind::Block(ref b, None) if matches!(self.cx, Fn) => {
172+
hir::ExprKind::Block(ref b, None) if matches!(self.cx_stack.last(), Some(&Fn)) => {
105173
self.with_context(Normal, |v| v.visit_block(b));
106174
}
107175
hir::ExprKind::Block(ref b, None)
108-
if matches!(self.cx, Normal | Constant | UnlabeledBlock(_)) =>
176+
if matches!(
177+
self.cx_stack.last(),
178+
Some(&Normal) | Some(&Constant) | Some(&UnlabeledBlock(_))
179+
) =>
109180
{
110181
self.with_context(UnlabeledBlock(b.span.shrink_to_lo()), |v| v.visit_block(b));
111182
}
@@ -178,7 +249,12 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
178249
Some(label) => sp_lo.with_hi(label.ident.span.hi()),
179250
None => sp_lo.shrink_to_lo(),
180251
};
181-
self.require_break_cx("break", e.span, label_sp);
252+
self.require_break_cx(
253+
BreakContextKind::Break,
254+
e.span,
255+
label_sp,
256+
self.cx_stack.len() - 1,
257+
);
182258
}
183259
hir::ExprKind::Continue(destination) => {
184260
self.require_label_in_labeled_block(e.span, &destination, "continue");
@@ -200,7 +276,12 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
200276
}
201277
Err(_) => {}
202278
}
203-
self.require_break_cx("continue", e.span, e.span)
279+
self.require_break_cx(
280+
BreakContextKind::Continue,
281+
e.span,
282+
e.span,
283+
self.cx_stack.len() - 1,
284+
)
204285
}
205286
_ => intravisit::walk_expr(self, e),
206287
}
@@ -212,18 +293,26 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
212293
where
213294
F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>),
214295
{
215-
let old_cx = self.cx;
216-
self.cx = cx;
296+
self.cx_stack.push(cx);
217297
f(self);
218-
self.cx = old_cx;
298+
self.cx_stack.pop();
219299
}
220300

221-
fn require_break_cx(&self, name: &str, span: Span, break_span: Span) {
222-
let is_break = name == "break";
223-
match self.cx {
301+
fn require_break_cx(
302+
&mut self,
303+
kind: BreakContextKind,
304+
span: Span,
305+
break_span: Span,
306+
cx_pos: usize,
307+
) {
308+
match self.cx_stack[cx_pos] {
224309
LabeledBlock | Loop(_) => {}
225310
Closure(closure_span) => {
226-
self.sess.dcx().emit_err(BreakInsideClosure { span, closure_span, name });
311+
self.sess.dcx().emit_err(BreakInsideClosure {
312+
span,
313+
closure_span,
314+
name: &kind.to_string(),
315+
});
227316
}
228317
Coroutine { coroutine_span, kind, source } => {
229318
let kind = match kind {
@@ -239,17 +328,32 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
239328
self.sess.dcx().emit_err(BreakInsideCoroutine {
240329
span,
241330
coroutine_span,
242-
name,
331+
name: &kind.to_string(),
243332
kind,
244333
source,
245334
});
246335
}
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 });
336+
UnlabeledBlock(block_span)
337+
if kind == BreakContextKind::Break && block_span.eq_ctxt(break_span) =>
338+
{
339+
let block = self.block_breaks.entry(block_span).or_insert_with(|| BlockInfo {
340+
name: kind.to_string(),
341+
spans: vec![],
342+
suggs: vec![],
343+
});
344+
block.spans.push(span);
345+
block.suggs.push(break_span);
346+
}
347+
UnlabeledIfBlock(_) if kind == BreakContextKind::Break => {
348+
self.require_break_cx(kind, span, break_span, cx_pos - 1);
250349
}
251-
Normal | Constant | Fn | UnlabeledBlock(_) => {
252-
self.sess.dcx().emit_err(OutsideLoop { span, name, is_break, suggestion: None });
350+
Normal | Constant | Fn | UnlabeledBlock(_) | UnlabeledIfBlock(_) => {
351+
self.sess.dcx().emit_err(OutsideLoop {
352+
spans: vec![span],
353+
name: &kind.to_string(),
354+
is_break: kind == BreakContextKind::Break,
355+
suggestion: None,
356+
});
253357
}
254358
}
255359
}
@@ -261,12 +365,26 @@ impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
261365
cf_type: &str,
262366
) -> bool {
263367
if !span.is_desugaring(DesugaringKind::QuestionMark)
264-
&& self.cx == LabeledBlock
368+
&& self.cx_stack.last() == Some(&LabeledBlock)
265369
&& label.label.is_none()
266370
{
267371
self.sess.dcx().emit_err(UnlabeledInLabeledBlock { span, cf_type });
268372
return true;
269373
}
270374
false
271375
}
376+
377+
fn report_outside_loop_error(&mut self) {
378+
for (s, block) in &self.block_breaks {
379+
self.sess.dcx().emit_err(OutsideLoop {
380+
spans: block.spans.clone(),
381+
name: &block.name,
382+
is_break: true,
383+
suggestion: Some(OutsideLoopSuggestion {
384+
block_span: *s,
385+
break_spans: block.suggs.clone(),
386+
}),
387+
});
388+
}
389+
}
272390
}
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)