Skip to content

Commit eee8b0c

Browse files
Continue inside a labeled block now lowers to a error when to lowering the ast
1 parent ee0fd6c commit eee8b0c

File tree

13 files changed

+153
-29
lines changed

13 files changed

+153
-29
lines changed

compiler/rustc_ast_lowering/messages.ftl

+5
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ ast_lowering_clobber_abi_not_supported =
5454
5555
ast_lowering_closure_cannot_be_static = closures cannot be static
5656
57+
ast_lowering_continue_labeled_block =
58+
`continue` pointing to a labeled block
59+
.label = labeled blocks cannot be `continue`'d
60+
.block_label = labeled block the `continue` points to
61+
5762
ast_lowering_coroutine_too_many_parameters =
5863
too many parameters for a coroutine (expected 0 or 1 parameters)
5964

compiler/rustc_ast_lowering/src/errors.rs

+10
Original file line numberDiff line numberDiff line change
@@ -451,3 +451,13 @@ pub(crate) struct YieldInClosure {
451451
#[suggestion(code = "#[coroutine] ", applicability = "maybe-incorrect", style = "verbose")]
452452
pub suggestion: Option<Span>,
453453
}
454+
455+
#[derive(Diagnostic)]
456+
#[diag(ast_lowering_continue_labeled_block, code = E0696)]
457+
pub struct ContinueLabeledBlock {
458+
#[primary_span]
459+
#[label]
460+
pub span: Span,
461+
#[label(ast_lowering_block_label)]
462+
pub block_span: Span,
463+
}

compiler/rustc_ast_lowering/src/expr.rs

+14-6
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@ use std::assert_matches::assert_matches;
22

33
use super::errors::{
44
AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, BaseExpressionDoubleDot,
5-
ClosureCannotBeStatic, CoroutineTooManyParameters,
5+
ClosureCannotBeStatic, ContinueLabeledBlock, CoroutineTooManyParameters,
66
FunctionalRecordUpdateDestructuringAssignment, InclusiveRangeWithNoEnd, MatchArmWithNoBody,
7-
NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign,
7+
NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign, YieldInClosure,
88
};
99
use super::ResolverAstLoweringExt;
1010
use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
11-
use crate::errors::YieldInClosure;
1211
use crate::{FnDeclKind, ImplTraitPosition};
1312
use rustc_ast::ptr::P as AstP;
1413
use rustc_ast::*;
@@ -290,7 +289,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
290289
hir::ExprKind::Break(self.lower_jump_destination(e.id, *opt_label), opt_expr)
291290
}
292291
ExprKind::Continue(opt_label) => {
293-
hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label))
292+
if opt_label.is_some()
293+
&& let Some((_, is_loop, block_span)) = self.resolver.get_label_res(e.id)
294+
&& !is_loop
295+
{
296+
hir::ExprKind::Err(
297+
self.dcx().emit_err(ContinueLabeledBlock { span: e.span, block_span }),
298+
)
299+
} else {
300+
hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label))
301+
}
294302
}
295303
ExprKind::Ret(e) => {
296304
let e = e.as_ref().map(|x| self.lower_expr(x));
@@ -1469,8 +1477,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
14691477
fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
14701478
let target_id = match destination {
14711479
Some((id, _)) => {
1472-
if let Some(loop_id) = self.resolver.get_label_res(id) {
1473-
Ok(self.lower_node_id(loop_id))
1480+
if let Some((id, _is_loop, _)) = self.resolver.get_label_res(id) {
1481+
Ok(self.lower_node_id(id))
14741482
} else {
14751483
Err(hir::LoopIdError::UnresolvedLabel)
14761484
}

compiler/rustc_ast_lowering/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ impl ResolverAstLowering {
250250
}
251251

252252
/// Obtains resolution for a label with the given `NodeId`.
253-
fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
253+
fn get_label_res(&self, id: NodeId) -> Option<(NodeId, bool, Span)> {
254254
self.label_res_map.get(&id).copied()
255255
}
256256

compiler/rustc_middle/src/ty/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,8 @@ pub struct ResolverAstLowering {
207207
/// Resolutions for import nodes, which have multiple resolutions in different namespaces.
208208
pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
209209
/// Resolutions for labels (node IDs of their corresponding blocks or loops).
210-
pub label_res_map: NodeMap<ast::NodeId>,
210+
/// The boolean stores if the node is loop. The span is the span of the node.
211+
pub label_res_map: NodeMap<(ast::NodeId, bool, Span)>,
211212
/// Resolutions for lifetimes.
212213
pub lifetimes_res_map: NodeMap<LifetimeRes>,
213214
/// Lifetime parameters that lowering will have to introduce.

compiler/rustc_resolve/src/late.rs

+31-13
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,7 @@ struct LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
669669
last_block_rib: Option<Rib<'a>>,
670670

671671
/// The current set of local scopes, for labels.
672-
label_ribs: Vec<Rib<'a, NodeId>>,
672+
label_ribs: Vec<Rib<'a, (NodeId, bool, Span)>>,
673673

674674
/// The current set of local scopes for lifetimes.
675675
lifetime_ribs: Vec<LifetimeRib>,
@@ -2313,7 +2313,10 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
23132313

23142314
/// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
23152315
/// label and reports an error if the label is not found or is unreachable.
2316-
fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
2316+
fn resolve_label(
2317+
&mut self,
2318+
mut label: Ident,
2319+
) -> Result<((NodeId, bool, Span), Span), ResolutionError<'a>> {
23172320
let mut suggestion = None;
23182321

23192322
for i in (0..self.label_ribs.len()).rev() {
@@ -4330,7 +4333,14 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
43304333
Ok(Some(result))
43314334
}
43324335

4333-
fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4336+
fn with_resolved_label(
4337+
&mut self,
4338+
label: Option<Label>,
4339+
id: NodeId,
4340+
is_loop: bool,
4341+
span: Span,
4342+
f: impl FnOnce(&mut Self),
4343+
) {
43344344
if let Some(label) = label {
43354345
if label.ident.as_str().as_bytes()[1] != b'_' {
43364346
self.diag_metadata.unused_labels.insert(id, label.ident.span);
@@ -4342,16 +4352,22 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
43424352

43434353
self.with_label_rib(RibKind::Normal, |this| {
43444354
let ident = label.ident.normalize_to_macro_rules();
4345-
this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4355+
this.label_ribs.last_mut().unwrap().bindings.insert(ident, (id, is_loop, span));
43464356
f(this);
43474357
});
43484358
} else {
43494359
f(self);
43504360
}
43514361
}
43524362

4353-
fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4354-
self.with_resolved_label(label, id, |this| this.visit_block(block));
4363+
fn resolve_labeled_block(
4364+
&mut self,
4365+
label: Option<Label>,
4366+
id: NodeId,
4367+
block: &'ast Block,
4368+
is_loop: bool,
4369+
) {
4370+
self.with_resolved_label(label, id, is_loop, block.span, |this| this.visit_block(block));
43554371
}
43564372

43574373
fn resolve_block(&mut self, block: &'ast Block) {
@@ -4494,10 +4510,10 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
44944510

44954511
ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
44964512
match self.resolve_label(label.ident) {
4497-
Ok((node_id, _)) => {
4513+
Ok((node, _)) => {
44984514
// Since this res is a label, it is never read.
4499-
self.r.label_res_map.insert(expr.id, node_id);
4500-
self.diag_metadata.unused_labels.remove(&node_id);
4515+
self.r.label_res_map.insert(expr.id, node);
4516+
self.diag_metadata.unused_labels.remove(&node.0);
45014517
}
45024518
Err(error) => {
45034519
self.report_error(label.ident.span, error);
@@ -4532,11 +4548,11 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
45324548
}
45334549

45344550
ExprKind::Loop(ref block, label, _) => {
4535-
self.resolve_labeled_block(label, expr.id, block)
4551+
self.resolve_labeled_block(label, expr.id, block, true)
45364552
}
45374553

45384554
ExprKind::While(ref cond, ref block, label) => {
4539-
self.with_resolved_label(label, expr.id, |this| {
4555+
self.with_resolved_label(label, expr.id, true, block.span, |this| {
45404556
this.with_rib(ValueNS, RibKind::Normal, |this| {
45414557
let old = this.diag_metadata.in_if_condition.replace(cond);
45424558
this.visit_expr(cond);
@@ -4550,11 +4566,13 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
45504566
self.visit_expr(iter);
45514567
self.with_rib(ValueNS, RibKind::Normal, |this| {
45524568
this.resolve_pattern_top(pat, PatternSource::For);
4553-
this.resolve_labeled_block(label, expr.id, body);
4569+
this.resolve_labeled_block(label, expr.id, body, true);
45544570
});
45554571
}
45564572

4557-
ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4573+
ExprKind::Block(ref block, label) => {
4574+
self.resolve_labeled_block(label, block.id, block, false)
4575+
}
45584576

45594577
// Equivalent to `visit::walk_expr` + passing some context to children.
45604578
ExprKind::Field(ref subexpression, _) => {

compiler/rustc_resolve/src/late/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
936936
if let Some(err_code) = err.code {
937937
if err_code == E0425 {
938938
for label_rib in &self.label_ribs {
939-
for (label_ident, node_id) in &label_rib.bindings {
939+
for (label_ident, (node_id, _, _)) in &label_rib.bindings {
940940
let ident = path.last().unwrap().ident;
941941
if format!("'{ident}") == label_ident.to_string() {
942942
err.span_label(label_ident.span, "a label with a similar name exists");

compiler/rustc_resolve/src/lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1013,7 +1013,8 @@ pub struct Resolver<'a, 'tcx> {
10131013
/// Resolutions for import nodes, which have multiple resolutions in different namespaces.
10141014
import_res_map: NodeMap<PerNS<Option<Res>>>,
10151015
/// Resolutions for labels (node IDs of their corresponding blocks or loops).
1016-
label_res_map: NodeMap<NodeId>,
1016+
/// The boolean stores if the node is loop. The span is the span of the node.
1017+
label_res_map: NodeMap<(NodeId, bool, Span)>,
10171018
/// Resolutions for lifetimes.
10181019
lifetimes_res_map: NodeMap<LifetimeRes>,
10191020
/// Lifetime parameters that lowering will have to introduce.

tests/ui/label/label_break_value_continue.stderr

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
1-
error[E0695]: unlabeled `continue` inside of a labeled block
2-
--> $DIR/label_break_value_continue.rs:6:9
3-
|
4-
LL | continue;
5-
| ^^^^^^^^ `continue` statements that would diverge to or through a labeled block need to bear a label
6-
71
error[E0696]: `continue` pointing to a labeled block
82
--> $DIR/label_break_value_continue.rs:13:9
93
|
@@ -13,6 +7,12 @@ LL | | continue 'b;
137
LL | | }
148
| |_____- labeled block the `continue` points to
159

10+
error[E0695]: unlabeled `continue` inside of a labeled block
11+
--> $DIR/label_break_value_continue.rs:6:9
12+
|
13+
LL | continue;
14+
| ^^^^^^^^ `continue` statements that would diverge to or through a labeled block need to bear a label
15+
1616
error[E0695]: unlabeled `continue` inside of a labeled block
1717
--> $DIR/label_break_value_continue.rs:21:13
1818
|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![allow(incomplete_features)]
2+
#![feature(adt_const_params)]
3+
4+
trait Trait<const S: &'static str> {}
5+
6+
struct Bug<T>
7+
where
8+
T: Trait<
9+
{
10+
'b: { //~ ERROR [E0308]
11+
continue 'b; //~ ERROR [E0696]
12+
}
13+
},
14+
>,
15+
{
16+
t: T,
17+
}
18+
19+
fn f() -> impl Sized {
20+
'b: {
21+
continue 'b;
22+
//~^ ERROR [E0696]
23+
}
24+
}
25+
26+
fn main() {
27+
f();
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
error[E0696]: `continue` pointing to a labeled block
2+
--> $DIR/cont-in-fn-issue-113379.rs:11:17
3+
|
4+
LL | / 'b: {
5+
LL | | continue 'b;
6+
| | ^^^^^^^^^^^ labeled blocks cannot be `continue`'d
7+
LL | | }
8+
| |_____________- labeled block the `continue` points to
9+
10+
error[E0696]: `continue` pointing to a labeled block
11+
--> $DIR/cont-in-fn-issue-113379.rs:21:9
12+
|
13+
LL | / 'b: {
14+
LL | | continue 'b;
15+
| | ^^^^^^^^^^^ labeled blocks cannot be `continue`'d
16+
LL | |
17+
LL | | }
18+
| |_____- labeled block the `continue` points to
19+
20+
error[E0308]: mismatched types
21+
--> $DIR/cont-in-fn-issue-113379.rs:10:13
22+
|
23+
LL | / 'b: {
24+
LL | | continue 'b;
25+
LL | | }
26+
| |_____________^ expected `&str`, found `()`
27+
28+
error: aborting due to 3 previous errors
29+
30+
Some errors have detailed explanations: E0308, E0696.
31+
For more information about an error, try `rustc --explain E0308`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
match () {
3+
_ => 'b: {
4+
continue 'b;
5+
//~^ ERROR [E0696]
6+
}
7+
}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error[E0696]: `continue` pointing to a labeled block
2+
--> $DIR/cont-in-match-arm-issue-121623.rs:4:13
3+
|
4+
LL | _ => 'b: {
5+
| ______________-
6+
LL | | continue 'b;
7+
| | ^^^^^^^^^^^ labeled blocks cannot be `continue`'d
8+
LL | |
9+
LL | | }
10+
| |_________- labeled block the `continue` points to
11+
12+
error: aborting due to 1 previous error
13+
14+
For more information about this error, try `rustc --explain E0696`.

0 commit comments

Comments
 (0)