Auto merge of #14942 - HKalbasi:for-loop-label, r=HKalbasi

fix bug in labeled for loop desugaring

fix https://github.com/rust-lang/rust-analyzer/pull/14892#discussion_r1213091393
This commit is contained in:
bors 2023-06-01 14:54:47 +00:00
commit 4458e7f190
2 changed files with 40 additions and 2 deletions

View File

@ -753,10 +753,13 @@ fn collect_for_loop(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::ForExpr) -
args: Box::new([self.collect_pat_top(e.pat())]),
ellipsis: None,
};
let label = e.label().map(|label| self.collect_label(label));
let some_arm = MatchArm {
pat: self.alloc_pat_desugared(some_pat),
guard: None,
expr: self.collect_expr_opt(e.loop_body().map(|x| x.into())),
expr: self.with_opt_labeled_rib(label, |this| {
this.collect_expr_opt(e.loop_body().map(|x| x.into()))
}),
};
let iter_name = Name::generate_new_name();
let iter_binding = self.alloc_binding(iter_name.clone(), BindingAnnotation::Mutable);
@ -778,7 +781,6 @@ fn collect_for_loop(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::ForExpr) -
Expr::Match { expr: iter_next_expr, arms: Box::new([none_arm, some_arm]) },
syntax_ptr.clone(),
);
let label = e.label().map(|label| self.collect_label(label));
let loop_outer =
self.alloc_expr(Expr::Loop { body: loop_inner, label }, syntax_ptr.clone());
let iter_pat = self.alloc_pat_desugared(Pat::Bind { id: iter_binding, subpat: None });
@ -1449,6 +1451,17 @@ fn with_labeled_rib<T>(&mut self, label: LabelId, f: impl FnOnce(&mut Self) -> T
self.label_ribs.pop();
res
}
fn with_opt_labeled_rib<T>(
&mut self,
label: Option<LabelId>,
f: impl FnOnce(&mut Self) -> T,
) -> T {
match label {
None => f(self),
Some(label) => self.with_labeled_rib(label, f),
}
}
// endregion: labels
}

View File

@ -33,6 +33,31 @@ fn foo() {
);
}
#[test]
fn for_loop() {
check_diagnostics(
r#"
//- minicore: iterator
fn foo() {
'xxx: for _ in unknown {
'yyy: for _ in unknown {
break 'xxx;
continue 'yyy;
break 'zzz;
//^^^^ error: use of undeclared label `'zzz`
}
continue 'xxx;
continue 'yyy;
//^^^^ error: use of undeclared label `'yyy`
break 'xxx;
break 'yyy;
//^^^^ error: use of undeclared label `'yyy`
}
}
"#,
);
}
#[test]
fn try_operator_desugar_works() {
check_diagnostics(