diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index 21b408064fac5..d0009c36f97a4 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -270,7 +270,13 @@ impl<'hir> Visitor<'hir> for CheckLoopVisitor<'hir> { } } - let sp_lo = e.span.with_lo(e.span.lo() + BytePos("break".len() as u32)); + let sp_lo = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(e.span) + && let Some(break_pos) = snippet.find("break") + { + e.span.with_lo(e.span.lo() + BytePos((break_pos + "break".len()) as u32)) + } else { + e.span.with_lo(e.span.lo() + BytePos("break".len() as u32)) + }; let label_sp = match break_destination.label { Some(label) => sp_lo.with_hi(label.ident.span.hi()), None => sp_lo.shrink_to_lo(), diff --git a/tests/ui/parser/break-in-unlabeled-block-parenthesized.rs b/tests/ui/parser/break-in-unlabeled-block-parenthesized.rs new file mode 100644 index 0000000000000..787aaf0c18450 --- /dev/null +++ b/tests/ui/parser/break-in-unlabeled-block-parenthesized.rs @@ -0,0 +1,9 @@ +#![allow(unused_parens)] +fn main() { + { + (break); //~ ERROR `break` outside of a loop or labeled block + }; + { + ((break)); //~ ERROR `break` outside of a loop or labeled block + }; +} diff --git a/tests/ui/parser/break-in-unlabeled-block-parenthesized.stderr b/tests/ui/parser/break-in-unlabeled-block-parenthesized.stderr new file mode 100644 index 0000000000000..17d3c977ffc90 --- /dev/null +++ b/tests/ui/parser/break-in-unlabeled-block-parenthesized.stderr @@ -0,0 +1,27 @@ +error[E0268]: `break` outside of a loop or labeled block + --> $DIR/break-in-unlabeled-block-parenthesized.rs:4:9 + | +LL | (break); + | ^^^^^^^ cannot `break` outside of a loop or labeled block + | +help: consider labeling this block to be able to break within it + | +LL ~ 'block: { +LL ~ (break 'block); + | + +error[E0268]: `break` outside of a loop or labeled block + --> $DIR/break-in-unlabeled-block-parenthesized.rs:7:9 + | +LL | ((break)); + | ^^^^^^^^^ cannot `break` outside of a loop or labeled block + | +help: consider labeling this block to be able to break within it + | +LL ~ 'block: { +LL ~ ((break 'block)); + | + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0268`.