3 use rustc_errors::{struct_span_err, Applicability};
5 use rustc_hir::def_id::LocalDefId;
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_hir::{Destination, Movability, Node};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::ty::query::Providers;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::Session;
12 use rustc_span::hygiene::DesugaringKind;
15 #[derive(Clone, Copy, Debug, PartialEq)]
18 Loop(hir::LoopSource),
25 #[derive(Copy, Clone)]
26 struct CheckLoopVisitor<'a, 'hir> {
32 fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
33 tcx.hir().visit_item_likes_in_module(
35 &mut CheckLoopVisitor { sess: &tcx.sess, hir_map: tcx.hir(), cx: Normal }.as_deep_visitor(),
39 pub(crate) fn provide(providers: &mut Providers) {
40 *providers = Providers { check_mod_loops, ..*providers };
43 impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
46 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
47 NestedVisitorMap::OnlyBodies(self.hir_map)
50 fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {
51 self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
54 fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
56 hir::ExprKind::Loop(ref b, _, source) => {
57 self.with_context(Loop(source), |v| v.visit_block(&b));
59 hir::ExprKind::Closure(_, ref function_decl, b, span, movability) => {
60 let cx = if let Some(Movability::Static) = movability {
65 self.visit_fn_decl(&function_decl);
66 self.with_context(cx, |v| v.visit_nested_body(b));
68 hir::ExprKind::Block(ref b, Some(_label)) => {
69 self.with_context(LabeledBlock, |v| v.visit_block(&b));
71 hir::ExprKind::Break(label, ref opt_expr) => {
72 if let Some(e) = opt_expr {
76 if self.require_label_in_labeled_block(e.span, &label, "break") {
77 // If we emitted an error about an unlabeled break in a labeled
78 // block, we don't need any further checking for this break any more
82 let loop_id = match label.target_id {
83 Ok(loop_id) => Some(loop_id),
84 Err(hir::LoopIdError::OutsideLoopScope) => None,
85 Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
86 self.emit_unlabled_cf_in_while_condition(e.span, "break");
89 Err(hir::LoopIdError::UnresolvedLabel) => None,
92 if let Some(loop_id) = loop_id {
93 if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() {
98 if opt_expr.is_some() {
99 let loop_kind = if let Some(loop_id) = loop_id {
100 Some(match self.hir_map.expect_expr(loop_id).kind {
101 hir::ExprKind::Loop(_, _, source) => source,
103 span_bug!(e.span, "break label resolved to a non-loop: {:?}", r)
110 None | Some(hir::LoopSource::Loop) => (),
116 "`break` with value from a `{}` loop",
121 "can only break with a value inside \
122 `loop` or breakable block",
127 "instead, use `break` on its own \
128 without a value inside this `{}` loop",
132 Applicability::MaybeIncorrect,
139 self.require_break_cx("break", e.span);
141 hir::ExprKind::Continue(destination) => {
142 self.require_label_in_labeled_block(e.span, &destination, "continue");
144 match destination.target_id {
146 if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
151 "`continue` pointing to a labeled block"
153 .span_label(e.span, "labeled blocks cannot be `continue`'d")
154 .span_label(block.span, "labeled block the `continue` points to")
158 Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
159 self.emit_unlabled_cf_in_while_condition(e.span, "continue");
163 self.require_break_cx("continue", e.span)
165 _ => intravisit::walk_expr(self, e),
170 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
171 fn with_context<F>(&mut self, cx: Context, f: F)
173 F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>),
175 let old_cx = self.cx;
181 fn require_break_cx(&self, name: &str, span: Span) {
182 let err_inside_of = |article, ty, closure_span| {
183 struct_span_err!(self.sess, span, E0267, "`{}` inside of {} {}", name, article, ty)
184 .span_label(span, format!("cannot `{}` inside of {} {}", name, article, ty))
185 .span_label(closure_span, &format!("enclosing {}", ty))
190 LabeledBlock | Loop(_) => {}
191 Closure(closure_span) => err_inside_of("a", "closure", closure_span),
192 AsyncClosure(closure_span) => err_inside_of("an", "`async` block", closure_span),
193 Normal | AnonConst => {
194 struct_span_err!(self.sess, span, E0268, "`{}` outside of a loop", name)
195 .span_label(span, format!("cannot `{}` outside of a loop", name))
201 fn require_label_in_labeled_block(
207 if !span.is_desugaring(DesugaringKind::QuestionMark) && self.cx == LabeledBlock {
208 if label.label.is_none() {
213 "unlabeled `{}` inside of a labeled block",
219 "`{}` statements that would diverge to or through \
220 a labeled block need to bear a label",
230 fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
235 "`break` or `continue` with no label in the condition of a `while` loop"
237 .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type))