From 249eb1c589bd12b2a26d9603460d62d514b59b90 Mon Sep 17 00:00:00 2001 From: Veeupup <931418134@qq.com> Date: Wed, 29 Dec 2021 18:01:17 +0800 Subject: [PATCH 1/8] fix typo in btree/vec doc: Self -> self --- library/alloc/src/collections/btree/map.rs | 2 +- library/alloc/src/collections/btree/set.rs | 2 +- library/alloc/src/vec/mod.rs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 199c05dc5df..1497d1a84ef 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -979,7 +979,7 @@ pub fn retain(&mut self, mut f: F) self.drain_filter(|k, v| !f(k, v)); } - /// Moves all elements from `other` into `Self`, leaving `other` empty. + /// Moves all elements from `other` into `self`, leaving `other` empty. /// /// # Examples /// diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index 394c21bf51c..f6aca05f25f 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -892,7 +892,7 @@ pub fn retain(&mut self, mut f: F) self.drain_filter(|v| !f(v)); } - /// Moves all elements from `other` into `Self`, leaving `other` empty. + /// Moves all elements from `other` into `self`, leaving `other` empty. /// /// # Examples /// diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 2863da05932..2689c6fd1ac 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1755,7 +1755,7 @@ pub fn pop(&mut self) -> Option { } } - /// Moves all the elements of `other` into `Self`, leaving `other` empty. + /// Moves all the elements of `other` into `self`, leaving `other` empty. /// /// # Panics /// @@ -1780,7 +1780,7 @@ pub fn append(&mut self, other: &mut Self) { } } - /// Appends elements to `Self` from other buffer. + /// Appends elements to `self` from other buffer. #[cfg(not(no_global_oom_handling))] #[inline] unsafe fn append_elements(&mut self, other: *const [T]) { From bfa7d44823717c30bc21abc1ca3675d0b78c80a2 Mon Sep 17 00:00:00 2001 From: DrMeepster <19316085+DrMeepster@users.noreply.github.com> Date: Sun, 27 Feb 2022 00:48:17 -0800 Subject: [PATCH 2/8] fix box icing when it has aggregate abi --- compiler/rustc_codegen_ssa/src/mir/place.rs | 13 +++++++++++- src/test/ui/box/issue-81270-ice.rs | 22 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/box/issue-81270-ice.rs diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index 6976999c0e4..aee385ab050 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -453,7 +453,18 @@ pub fn codegen_place( }; for elem in place_ref.projection[base..].iter() { cg_base = match elem.clone() { - mir::ProjectionElem::Deref => bx.load_operand(cg_base).deref(bx.cx()), + mir::ProjectionElem::Deref => { + // custom allocators can change box's abi, making it unable to be derefed directly + if cg_base.layout.ty.is_box() + && matches!(cg_base.layout.abi, Abi::Aggregate { .. }) + { + let ptr = cg_base.project_field(bx, 0).project_field(bx, 0); + + bx.load_operand(ptr).deref(bx.cx()) + } else { + bx.load_operand(cg_base).deref(bx.cx()) + } + } mir::ProjectionElem::Field(ref field, _) => { cg_base.project_field(bx, field.index()) } diff --git a/src/test/ui/box/issue-81270-ice.rs b/src/test/ui/box/issue-81270-ice.rs new file mode 100644 index 00000000000..fb42aed7aae --- /dev/null +++ b/src/test/ui/box/issue-81270-ice.rs @@ -0,0 +1,22 @@ +// check-pass +#![feature(allocator_api)] + +use std::alloc::Allocator; + +struct BigAllocator([usize; 2]); + +unsafe impl Allocator for BigAllocator { + fn allocate( + &self, + _: std::alloc::Layout, + ) -> Result, std::alloc::AllocError> { + todo!() + } + unsafe fn deallocate(&self, _: std::ptr::NonNull, _: std::alloc::Layout) { + todo!() + } +} + +fn main() { + Box::new_in((), BigAllocator([0; 2])); +} From 025b7c433c109dad2c84f1cbeae422a3ffbd01b6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 21 Feb 2022 19:49:15 -0800 Subject: [PATCH 3/8] fix ICE when passing empty block to while-loop condition --- compiler/rustc_typeck/src/check/expr.rs | 35 +++-- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 132 ++++++++++-------- src/test/ui/typeck/while-loop-block-cond.rs | 4 + .../ui/typeck/while-loop-block-cond.stderr | 9 ++ 4 files changed, 110 insertions(+), 70 deletions(-) create mode 100644 src/test/ui/typeck/while-loop-block-cond.rs create mode 100644 src/test/ui/typeck/while-loop-block-cond.stderr diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 8d4ffefda73..15284dc008f 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -842,7 +842,27 @@ pub(crate) fn check_lhs_assignable( ); err.span_label(lhs.span, "cannot assign to this expression"); - let mut parent = self.tcx.hir().get_parent_node(lhs.hir_id); + self.comes_from_while_condition(lhs.hir_id, |expr| { + err.span_suggestion_verbose( + expr.span.shrink_to_lo(), + "you might have meant to use pattern destructuring", + "let ".to_string(), + Applicability::MachineApplicable, + ); + }); + + err.emit(); + } + + // Check if an expression `original_expr_id` comes from the condition of a while loop, + // as opposed from the body of a while loop, which we can naively check by iterating + // parents until we find a loop... + pub(super) fn comes_from_while_condition( + &self, + original_expr_id: HirId, + then: impl FnOnce(&hir::Expr<'_>), + ) { + let mut parent = self.tcx.hir().get_parent_node(original_expr_id); while let Some(node) = self.tcx.hir().find(parent) { match node { hir::Node::Expr(hir::Expr { @@ -863,8 +883,8 @@ pub(crate) fn check_lhs_assignable( ), .. }) => { - // Check if our lhs is a child of the condition of a while loop - let expr_is_ancestor = std::iter::successors(Some(lhs.hir_id), |id| { + // Check if our original expression is a child of the condition of a while loop + let expr_is_ancestor = std::iter::successors(Some(original_expr_id), |id| { self.tcx.hir().find_parent_node(*id) }) .take_while(|id| *id != parent) @@ -872,12 +892,7 @@ pub(crate) fn check_lhs_assignable( // if it is, then we have a situation like `while Some(0) = value.get(0) {`, // where `while let` was more likely intended. if expr_is_ancestor { - err.span_suggestion_verbose( - expr.span.shrink_to_lo(), - "you might have meant to use pattern destructuring", - "let ".to_string(), - Applicability::MachineApplicable, - ); + then(expr); } break; } @@ -890,8 +905,6 @@ pub(crate) fn check_lhs_assignable( } } } - - err.emit(); } // A generic function for checking the 'then' and 'else' clauses in an 'if' diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 4b6460b62b7..769b0f19101 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -770,55 +770,57 @@ pub(in super::super) fn check_block_with_expected( let prev_diverges = self.diverges.get(); let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false }; - let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || { - for (pos, s) in blk.stmts.iter().enumerate() { - self.check_stmt(s, blk.stmts.len() - 1 == pos); - } + let (ctxt, ()) = + self.with_breakable_ctxt(blk.hir_id, ctxt, || { + for (pos, s) in blk.stmts.iter().enumerate() { + self.check_stmt(s, blk.stmts.len() - 1 == pos); + } - // check the tail expression **without** holding the - // `enclosing_breakables` lock below. - let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected)); + // check the tail expression **without** holding the + // `enclosing_breakables` lock below. + let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected)); - let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); - let ctxt = enclosing_breakables.find_breakable(blk.hir_id); - let coerce = ctxt.coerce.as_mut().unwrap(); - if let Some(tail_expr_ty) = tail_expr_ty { - let tail_expr = tail_expr.unwrap(); - let span = self.get_expr_coercion_span(tail_expr); - let cause = self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id)); - coerce.coerce(self, &cause, tail_expr, tail_expr_ty); - } else { - // Subtle: if there is no explicit tail expression, - // that is typically equivalent to a tail expression - // of `()` -- except if the block diverges. In that - // case, there is no value supplied from the tail - // expression (assuming there are no other breaks, - // this implies that the type of the block will be - // `!`). - // - // #41425 -- label the implicit `()` as being the - // "found type" here, rather than the "expected type". - if !self.diverges.get().is_always() { - // #50009 -- Do not point at the entire fn block span, point at the return type - // span, as it is the cause of the requirement, and - // `consider_hint_about_removing_semicolon` will point at the last expression - // if it were a relevant part of the error. This improves usability in editors - // that highlight errors inline. - let mut sp = blk.span; - let mut fn_span = None; - if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) { - let ret_sp = decl.output.span(); - if let Some(block_sp) = self.parent_item_span(blk.hir_id) { - // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the - // output would otherwise be incorrect and even misleading. Make sure - // the span we're aiming at correspond to a `fn` body. - if block_sp == blk.span { - sp = ret_sp; - fn_span = Some(ident.span); + let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); + let ctxt = enclosing_breakables.find_breakable(blk.hir_id); + let coerce = ctxt.coerce.as_mut().unwrap(); + if let Some(tail_expr_ty) = tail_expr_ty { + let tail_expr = tail_expr.unwrap(); + let span = self.get_expr_coercion_span(tail_expr); + let cause = + self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id)); + coerce.coerce(self, &cause, tail_expr, tail_expr_ty); + } else { + // Subtle: if there is no explicit tail expression, + // that is typically equivalent to a tail expression + // of `()` -- except if the block diverges. In that + // case, there is no value supplied from the tail + // expression (assuming there are no other breaks, + // this implies that the type of the block will be + // `!`). + // + // #41425 -- label the implicit `()` as being the + // "found type" here, rather than the "expected type". + if !self.diverges.get().is_always() { + // #50009 -- Do not point at the entire fn block span, point at the return type + // span, as it is the cause of the requirement, and + // `consider_hint_about_removing_semicolon` will point at the last expression + // if it were a relevant part of the error. This improves usability in editors + // that highlight errors inline. + let mut sp = blk.span; + let mut fn_span = None; + if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) { + let ret_sp = decl.output.span(); + if let Some(block_sp) = self.parent_item_span(blk.hir_id) { + // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the + // output would otherwise be incorrect and even misleading. Make sure + // the span we're aiming at correspond to a `fn` body. + if block_sp == blk.span { + sp = ret_sp; + fn_span = Some(ident.span); + } } } - } - coerce.coerce_forced_unit( + coerce.coerce_forced_unit( self, &self.misc(sp), &mut |err| { @@ -827,19 +829,31 @@ pub(in super::super) fn check_block_with_expected( if expected_ty == self.tcx.types.bool { // If this is caused by a missing `let` in a `while let`, // silence this redundant error, as we already emit E0070. - let parent = self.tcx.hir().get_parent_node(blk.hir_id); - let parent = self.tcx.hir().get_parent_node(parent); - let parent = self.tcx.hir().get_parent_node(parent); - let parent = self.tcx.hir().get_parent_node(parent); - let parent = self.tcx.hir().get_parent_node(parent); - match self.tcx.hir().find(parent) { - Some(hir::Node::Expr(hir::Expr { - kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _), - .. - })) => { + + // Our block must be a `assign desugar local; assignment` + if let Some(hir::Node::Block(hir::Block { + stmts: + [hir::Stmt { + kind: + hir::StmtKind::Local(hir::Local { + source: hir::LocalSource::AssignDesugar(_), + .. + }), + .. + }, hir::Stmt { + kind: + hir::StmtKind::Expr(hir::Expr { + kind: hir::ExprKind::Assign(..), + .. + }), + .. + }], + .. + })) = self.tcx.hir().find(blk.hir_id) + { + self.comes_from_while_condition(blk.hir_id, |_| { err.downgrade_to_delayed_bug(); - } - _ => {} + }) } } } @@ -853,9 +867,9 @@ pub(in super::super) fn check_block_with_expected( }, false, ); + } } - } - }); + }); if ctxt.may_break { // If we can break from the block, then the block's exit is always reachable diff --git a/src/test/ui/typeck/while-loop-block-cond.rs b/src/test/ui/typeck/while-loop-block-cond.rs new file mode 100644 index 00000000000..929759766f2 --- /dev/null +++ b/src/test/ui/typeck/while-loop-block-cond.rs @@ -0,0 +1,4 @@ +fn main() { + while {} {} + //~^ ERROR mismatched types [E0308] +} diff --git a/src/test/ui/typeck/while-loop-block-cond.stderr b/src/test/ui/typeck/while-loop-block-cond.stderr new file mode 100644 index 00000000000..598273af9cf --- /dev/null +++ b/src/test/ui/typeck/while-loop-block-cond.stderr @@ -0,0 +1,9 @@ +error[E0308]: mismatched types + --> $DIR/while-loop-block-cond.rs:2:11 + | +LL | while {} {} + | ^^ expected `bool`, found `()` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. From d316aba04c4644093ba07d1ec8d334b599b8eb01 Mon Sep 17 00:00:00 2001 From: DrMeepster <19316085+DrMeepster@users.noreply.github.com> Date: Sun, 27 Feb 2022 20:25:16 -0800 Subject: [PATCH 4/8] expadn abi check + condese & fix tests --- compiler/rustc_codegen_ssa/src/mir/place.rs | 2 +- src/test/ui/box/issue-78459-ice.rs | 6 ------ .../ui/box/{issue-81270-ice.rs => large-allocator-ice.rs} | 3 ++- 3 files changed, 3 insertions(+), 8 deletions(-) delete mode 100644 src/test/ui/box/issue-78459-ice.rs rename src/test/ui/box/{issue-81270-ice.rs => large-allocator-ice.rs} (88%) diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index aee385ab050..809d6447908 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -456,7 +456,7 @@ pub fn codegen_place( mir::ProjectionElem::Deref => { // custom allocators can change box's abi, making it unable to be derefed directly if cg_base.layout.ty.is_box() - && matches!(cg_base.layout.abi, Abi::Aggregate { .. }) + && matches!(cg_base.layout.abi, Abi::Aggregate { .. } | Abi::Uninhabited) { let ptr = cg_base.project_field(bx, 0).project_field(bx, 0); diff --git a/src/test/ui/box/issue-78459-ice.rs b/src/test/ui/box/issue-78459-ice.rs deleted file mode 100644 index 89f75fea15b..00000000000 --- a/src/test/ui/box/issue-78459-ice.rs +++ /dev/null @@ -1,6 +0,0 @@ -// check-pass -#![feature(allocator_api)] - -fn main() { - Box::new_in((), &std::alloc::Global); -} diff --git a/src/test/ui/box/issue-81270-ice.rs b/src/test/ui/box/large-allocator-ice.rs similarity index 88% rename from src/test/ui/box/issue-81270-ice.rs rename to src/test/ui/box/large-allocator-ice.rs index fb42aed7aae..3ef1171ff50 100644 --- a/src/test/ui/box/issue-81270-ice.rs +++ b/src/test/ui/box/large-allocator-ice.rs @@ -1,4 +1,4 @@ -// check-pass +// build-pass #![feature(allocator_api)] use std::alloc::Allocator; @@ -18,5 +18,6 @@ unsafe fn deallocate(&self, _: std::ptr::NonNull, _: std::alloc::Layout) { } fn main() { + Box::new_in((), &std::alloc::Global); Box::new_in((), BigAllocator([0; 2])); } From e3e902bb06143c8dcf72be392e95c3e6dc517f1a Mon Sep 17 00:00:00 2001 From: Caio Date: Mon, 28 Feb 2022 07:49:56 -0300 Subject: [PATCH 5/8] 4 - Make more use of `let_chains` Continuation of #94376. cc #53667 --- compiler/rustc_parse/src/lexer/tokentrees.rs | 15 ++-- compiler/rustc_parse/src/lib.rs | 3 +- .../rustc_parse/src/parser/diagnostics.rs | 78 +++++++++---------- compiler/rustc_parse/src/parser/item.rs | 12 ++- compiler/rustc_parse/src/parser/mod.rs | 10 +-- compiler/rustc_parse/src/parser/path.rs | 14 ++-- compiler/rustc_parse/src/parser/stmt.rs | 16 ++-- 7 files changed, 72 insertions(+), 76 deletions(-) diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index 6233549dc85..8318aec8726 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -282,14 +282,13 @@ struct TokenStreamBuilder { impl TokenStreamBuilder { fn push(&mut self, (tree, joint): TreeAndSpacing) { - if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { - if let TokenTree::Token(token) = &tree { - if let Some(glued) = prev_token.glue(token) { - self.buf.pop(); - self.buf.push((TokenTree::Token(glued), joint)); - return; - } - } + if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() + && let TokenTree::Token(token) = &tree + && let Some(glued) = prev_token.glue(token) + { + self.buf.pop(); + self.buf.push((TokenTree::Token(glued), joint)); + return; } self.buf.push((tree, joint)) } diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index eb0d1a12c77..5c95a9e7bb6 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -1,9 +1,10 @@ //! The main parser interface. #![feature(array_windows)] +#![feature(box_patterns)] #![feature(crate_visibility_modifier)] #![feature(if_let_guard)] -#![feature(box_patterns)] +#![feature(let_chains)] #![feature(let_else)] #![recursion_limit = "256"] diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 50310b28f9a..42c9753d6bd 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -732,43 +732,42 @@ pub(super) fn check_mistyped_turbofish_with_multiple_type_params( mut e: DiagnosticBuilder<'a, ErrorReported>, expr: &mut P, ) -> PResult<'a, ()> { - if let ExprKind::Binary(binop, _, _) = &expr.kind { - if let ast::BinOpKind::Lt = binop.node { - if self.eat(&token::Comma) { - let x = self.parse_seq_to_before_end( - &token::Gt, - SeqSep::trailing_allowed(token::Comma), - |p| p.parse_generic_arg(None), - ); - match x { - Ok((_, _, false)) => { - if self.eat(&token::Gt) { - e.span_suggestion_verbose( - binop.span.shrink_to_lo(), - TURBOFISH_SUGGESTION_STR, - "::".to_string(), - Applicability::MaybeIncorrect, - ) - .emit(); - match self.parse_expr() { - Ok(_) => { - *expr = - self.mk_expr_err(expr.span.to(self.prev_token.span)); - return Ok(()); - } - Err(err) => { - *expr = self.mk_expr_err(expr.span); - err.cancel(); - } - } + if let ExprKind::Binary(binop, _, _) = &expr.kind + && let ast::BinOpKind::Lt = binop.node + && self.eat(&token::Comma) + { + let x = self.parse_seq_to_before_end( + &token::Gt, + SeqSep::trailing_allowed(token::Comma), + |p| p.parse_generic_arg(None), + ); + match x { + Ok((_, _, false)) => { + if self.eat(&token::Gt) { + e.span_suggestion_verbose( + binop.span.shrink_to_lo(), + TURBOFISH_SUGGESTION_STR, + "::".to_string(), + Applicability::MaybeIncorrect, + ) + .emit(); + match self.parse_expr() { + Ok(_) => { + *expr = + self.mk_expr_err(expr.span.to(self.prev_token.span)); + return Ok(()); + } + Err(err) => { + *expr = self.mk_expr_err(expr.span); + err.cancel(); } } - Err(err) => { - err.cancel(); - } - _ => {} } } + Err(err) => { + err.cancel(); + } + _ => {} } } Err(e) @@ -784,12 +783,13 @@ fn attempt_chained_comparison_suggestion( outer_op: &Spanned, ) -> bool /* advanced the cursor */ { if let ExprKind::Binary(op, ref l1, ref r1) = inner_op.kind { - if let ExprKind::Field(_, ident) = l1.kind { - if ident.as_str().parse::().is_err() && !matches!(r1.kind, ExprKind::Lit(_)) { - // The parser has encountered `foo.bar().is_err() + && !matches!(r1.kind, ExprKind::Lit(_)) + { + // The parser has encountered `foo.bar PResult<'a, Option> { // Don't use `maybe_whole` so that we have precise control // over when we bump the parser - if let token::Interpolated(nt) = &self.token.kind { - if let token::NtItem(item) = &**nt { - let mut item = item.clone(); - self.bump(); + if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt { + let mut item = item.clone(); + self.bump(); - attrs.prepend_to_nt_inner(&mut item.attrs); - return Ok(Some(item.into_inner())); - } + attrs.prepend_to_nt_inner(&mut item.attrs); + return Ok(Some(item.into_inner())); }; let mut unclosed_delims = vec![]; diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index d8e6d5037bb..4d31de123b4 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -97,15 +97,15 @@ macro_rules! maybe_whole { #[macro_export] macro_rules! maybe_recover_from_interpolated_ty_qpath { ($self: expr, $allow_qpath_recovery: expr) => { - if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) { - if let token::Interpolated(nt) = &$self.token.kind { - if let token::NtTy(ty) = &**nt { + if $allow_qpath_recovery + && $self.look_ahead(1, |t| t == &token::ModSep) + && let token::Interpolated(nt) = &$self.token.kind + && let token::NtTy(ty) = &**nt + { let ty = ty.clone(); $self.bump(); return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); } - } - } }; } diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 0ffc9d09355..5e537d7b95c 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -658,13 +658,13 @@ fn get_ident_from_generic_arg( &self, gen_arg: GenericArg, ) -> Result<(Ident, Option), GenericArg> { - if let GenericArg::Type(ty) = &gen_arg { - if let ast::TyKind::Path(qself, path) = &ty.kind { - if qself.is_none() && path.segments.len() == 1 { - let seg = &path.segments[0]; - return Ok((seg.ident, seg.args.as_deref().cloned())); - } - } + if let GenericArg::Type(ty) = &gen_arg + && let ast::TyKind::Path(qself, path) = &ty.kind + && qself.is_none() + && path.segments.len() == 1 + { + let seg = &path.segments[0]; + return Ok((seg.ident, seg.args.as_deref().cloned())); } Err(gen_arg) } diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 6b195285243..2154c09f12a 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -48,15 +48,13 @@ pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option< // Don't use `maybe_whole` so that we have precise control // over when we bump the parser - if let token::Interpolated(nt) = &self.token.kind { - if let token::NtStmt(stmt) = &**nt { - let mut stmt = stmt.clone(); - self.bump(); - stmt.visit_attrs(|stmt_attrs| { - attrs.prepend_to_nt_inner(stmt_attrs); - }); - return Ok(Some(stmt)); - } + if let token::Interpolated(nt) = &self.token.kind && let token::NtStmt(stmt) = &**nt { + let mut stmt = stmt.clone(); + self.bump(); + stmt.visit_attrs(|stmt_attrs| { + attrs.prepend_to_nt_inner(stmt_attrs); + }); + return Ok(Some(stmt)); } Ok(Some(if self.token.is_keyword(kw::Let) { From 911de7b98c828ddf18fc6a1db227593faee7aad3 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 28 Feb 2022 14:23:11 +0100 Subject: [PATCH 6/8] Add explanation for E0726 --- compiler/rustc_error_codes/src/error_codes.rs | 2 +- .../src/error_codes/E0726.md | 46 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 compiler/rustc_error_codes/src/error_codes/E0726.md diff --git a/compiler/rustc_error_codes/src/error_codes.rs b/compiler/rustc_error_codes/src/error_codes.rs index a72681dbf4e..a185902123d 100644 --- a/compiler/rustc_error_codes/src/error_codes.rs +++ b/compiler/rustc_error_codes/src/error_codes.rs @@ -429,6 +429,7 @@ E0722: include_str!("./error_codes/E0722.md"), E0724: include_str!("./error_codes/E0724.md"), E0725: include_str!("./error_codes/E0725.md"), +E0726: include_str!("./error_codes/E0726.md"), E0727: include_str!("./error_codes/E0727.md"), E0728: include_str!("./error_codes/E0728.md"), E0729: include_str!("./error_codes/E0729.md"), @@ -641,6 +642,5 @@ E0717, // rustc_promotable without stability attribute // E0721, // `await` keyword // E0723, // unstable feature in `const` context - E0726, // non-explicit (not `'_`) elided lifetime in unsupported position // E0738, // Removed; errored on `#[track_caller] fn`s in `extern "Rust" { ... }`. } diff --git a/compiler/rustc_error_codes/src/error_codes/E0726.md b/compiler/rustc_error_codes/src/error_codes/E0726.md new file mode 100644 index 00000000000..e3794327f2d --- /dev/null +++ b/compiler/rustc_error_codes/src/error_codes/E0726.md @@ -0,0 +1,46 @@ +An argument lifetime was elided in an async function. + +Erroneous code example: + +When a struct or a type is bound/declared with a lifetime it is important for +the Rust compiler to know, on usage, the lifespan of the type. When the +lifetime is not explicitly mentioned and the Rust Compiler cannot determine +the lifetime of your type, the following error occurs. + +```compile_fail,E0726 +use futures::executor::block_on; +struct Content<'a> { + title: &'a str, + body: &'a str, +} +async fn create(content: Content) { // error: implicit elided + // lifetime not allowed here + println!("title: {}", content.title); + println!("body: {}", content.body); +} +let content = Content { title: "Rust", body: "is great!" }; +let future = create(content); +block_on(future); +``` + +Specify desired lifetime of parameter `content` or indicate the anonymous +lifetime like `content: Content<'_>`. The anonymous lifetime tells the Rust +compiler that `content` is only needed until create function is done with +it's execution. + +The `implicit elision` meaning the omission of suggested lifetime that is +`pub async fn create<'a>(content: Content<'a>) {}` is not allowed here as +lifetime of the `content` can differ from current context: + +```ignore (needs futures dependency) +async fn create(content: Content<'_>) { // ok! + println!("title: {}", content.title); + println!("body: {}", content.body); +} +``` + +Know more about lifetime elision in this [chapter][lifetime-elision] and a +chapter on lifetimes can be found [here][lifetimes]. + +[lifetime-elision]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision +[lifetimes]: https://doc.rust-lang.org/rust-by-example/scope/lifetime.html From 8f36d4a536fd194a3f412e957e176cf2944d9c0a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 28 Feb 2022 14:37:27 +0100 Subject: [PATCH 7/8] Update ui test with the add of E0726 explanation --- src/test/ui/async-await/async-fn-path-elision.stderr | 1 + src/test/ui/impl-header-lifetime-elision/path-elided.stderr | 1 + src/test/ui/impl-header-lifetime-elision/trait-elided.stderr | 1 + src/test/ui/issues/issue-10412.stderr | 3 ++- src/test/ui/wf/wf-in-foreign-fn-decls-issue-80468.stderr | 1 + 5 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/test/ui/async-await/async-fn-path-elision.stderr b/src/test/ui/async-await/async-fn-path-elision.stderr index 36fb73a8dde..3d18d9c4125 100644 --- a/src/test/ui/async-await/async-fn-path-elision.stderr +++ b/src/test/ui/async-await/async-fn-path-elision.stderr @@ -8,3 +8,4 @@ LL | async fn error(lt: HasLifetime) { error: aborting due to previous error +For more information about this error, try `rustc --explain E0726`. diff --git a/src/test/ui/impl-header-lifetime-elision/path-elided.stderr b/src/test/ui/impl-header-lifetime-elision/path-elided.stderr index 1c81c696201..90522a885ab 100644 --- a/src/test/ui/impl-header-lifetime-elision/path-elided.stderr +++ b/src/test/ui/impl-header-lifetime-elision/path-elided.stderr @@ -8,3 +8,4 @@ LL | impl MyTrait for Foo { error: aborting due to previous error +For more information about this error, try `rustc --explain E0726`. diff --git a/src/test/ui/impl-header-lifetime-elision/trait-elided.stderr b/src/test/ui/impl-header-lifetime-elision/trait-elided.stderr index 735f01379f0..15bc3f106b9 100644 --- a/src/test/ui/impl-header-lifetime-elision/trait-elided.stderr +++ b/src/test/ui/impl-header-lifetime-elision/trait-elided.stderr @@ -8,3 +8,4 @@ LL | impl MyTrait for u32 { error: aborting due to previous error +For more information about this error, try `rustc --explain E0726`. diff --git a/src/test/ui/issues/issue-10412.stderr b/src/test/ui/issues/issue-10412.stderr index 053a93e6cd8..a91b3c90ebb 100644 --- a/src/test/ui/issues/issue-10412.stderr +++ b/src/test/ui/issues/issue-10412.stderr @@ -67,4 +67,5 @@ LL | trait Serializable<'self, T: ?Sized> { error: aborting due to 9 previous errors -For more information about this error, try `rustc --explain E0277`. +Some errors have detailed explanations: E0277, E0726. +For more information about an error, try `rustc --explain E0277`. diff --git a/src/test/ui/wf/wf-in-foreign-fn-decls-issue-80468.stderr b/src/test/ui/wf/wf-in-foreign-fn-decls-issue-80468.stderr index d3593d8c1eb..ba624507c21 100644 --- a/src/test/ui/wf/wf-in-foreign-fn-decls-issue-80468.stderr +++ b/src/test/ui/wf/wf-in-foreign-fn-decls-issue-80468.stderr @@ -30,3 +30,4 @@ LL | impl Trait for Ref {} error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0726`. From f42b4f595e68b224d72e143b2785160876ab0ff1 Mon Sep 17 00:00:00 2001 From: Esteban Kuber Date: Wed, 12 Jan 2022 20:43:24 +0000 Subject: [PATCH 8/8] Tweak diagnostics * Recover from invalid `'label: ` before block. * Make suggestion to enclose statements in a block multipart. * Point at `match`, `while`, `loop` and `unsafe` keywords when failing to parse their expression. * Do not suggest `{ ; }`. * Do not suggest `|` when very unlikely to be what was wanted (in `let` statements). --- compiler/rustc_expand/src/expand.rs | 3 +- .../rustc_parse/src/parser/diagnostics.rs | 53 +++++++++++++----- compiler/rustc_parse/src/parser/expr.rs | 56 +++++++++++++++---- compiler/rustc_parse/src/parser/mod.rs | 2 +- .../rustc_parse/src/parser/nonterminal.rs | 4 +- compiler/rustc_parse/src/parser/pat.rs | 51 ++++++++++++++--- compiler/rustc_parse/src/parser/stmt.rs | 38 +++++++------ .../incorrect-syntax-suggestions.stderr | 2 +- ...-identifier-not-instead-of-negation.stderr | 5 +- ...92-tuple-destructure-missing-parens.stderr | 46 +++++---------- src/test/ui/issues/issue-39848.stderr | 10 ++-- .../label_break_value_illegal_uses.fixed | 30 ++++++++++ .../label/label_break_value_illegal_uses.rs | 19 +++++-- .../label_break_value_illegal_uses.stderr | 38 +++++-------- src/test/ui/let-else/let-else-if.stderr | 8 +-- src/test/ui/missing/missing-block-hint.stderr | 10 ++-- .../ui/parser/block-no-opening-brace.stderr | 36 ++++++++---- .../ui/parser/closure-return-syntax.stderr | 10 ++-- src/test/ui/parser/issues/issue-62554.stderr | 5 +- src/test/ui/parser/issues/issue-62973.stderr | 2 +- .../ui/parser/match-refactor-to-expr.fixed | 2 +- src/test/ui/parser/match-refactor-to-expr.rs | 2 +- .../ui/parser/match-refactor-to-expr.stderr | 2 +- .../ui/parser/while-if-let-without-body.rs | 13 +++++ .../parser/while-if-let-without-body.stderr | 18 ++++++ .../unsafe/unsafe-block-without-braces.stderr | 12 ++-- 26 files changed, 316 insertions(+), 161 deletions(-) create mode 100644 src/test/ui/label/label_break_value_illegal_uses.fixed create mode 100644 src/test/ui/parser/while-if-let-without-body.rs create mode 100644 src/test/ui/parser/while-if-let-without-body.stderr diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index bdc9c064a6f..ab3951d7683 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -20,7 +20,7 @@ use rustc_errors::{Applicability, PResult}; use rustc_feature::Features; use rustc_parse::parser::{ - AttemptLocalParseRecovery, ForceCollect, Parser, RecoverColon, RecoverComma, + AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, }; use rustc_parse::validate_attr; use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; @@ -911,6 +911,7 @@ pub fn parse_ast_fragment<'a>( None, RecoverComma::No, RecoverColon::Yes, + CommaRecoveryMode::LikelyTuple, )?), AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?), AstFragmentKind::Arms diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 50310b28f9a..5aa8ccf497b 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1,8 +1,8 @@ use super::pat::Expected; use super::ty::{AllowPlus, IsAsCast}; use super::{ - BlockMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions, SemiColonMode, SeqSep, - TokenExpectType, TokenType, + BlockMode, CommaRecoveryMode, Parser, PathStyle, RecoverColon, RecoverComma, Restrictions, + SemiColonMode, SeqSep, TokenExpectType, TokenType, }; use rustc_ast as ast; @@ -2245,12 +2245,32 @@ pub(super) fn incorrect_move_async_order_found( first_pat } + crate fn maybe_recover_unexpected_block_label(&mut self) -> bool { + let Some(label) = self.eat_label().filter(|_| { + self.eat(&token::Colon) && self.token.kind == token::OpenDelim(token::Brace) + }) else { + return false; + }; + let span = label.ident.span.to(self.prev_token.span); + let mut err = self.struct_span_err(span, "block label not supported here"); + err.span_label(span, "not supported here"); + err.tool_only_span_suggestion( + label.ident.span.until(self.token.span), + "remove this block label", + String::new(), + Applicability::MachineApplicable, + ); + err.emit(); + true + } + /// Some special error handling for the "top-level" patterns in a match arm, /// `for` loop, `let`, &c. (in contrast to subpatterns within such). crate fn maybe_recover_unexpected_comma( &mut self, lo: Span, rc: RecoverComma, + rt: CommaRecoveryMode, ) -> PResult<'a, ()> { if rc == RecoverComma::No || self.token != token::Comma { return Ok(()); @@ -2270,20 +2290,25 @@ pub(super) fn incorrect_move_async_order_found( let seq_span = lo.to(self.prev_token.span); let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern"); if let Ok(seq_snippet) = self.span_to_snippet(seq_span) { - const MSG: &str = "try adding parentheses to match on a tuple..."; - - err.span_suggestion( - seq_span, - MSG, - format!("({})", seq_snippet), - Applicability::MachineApplicable, - ); - err.span_suggestion( - seq_span, - "...or a vertical bar to match on multiple alternatives", - seq_snippet.replace(',', " |"), + err.multipart_suggestion( + &format!( + "try adding parentheses to match on a tuple{}", + if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." }, + ), + vec![ + (seq_span.shrink_to_lo(), "(".to_string()), + (seq_span.shrink_to_hi(), ")".to_string()), + ], Applicability::MachineApplicable, ); + if let CommaRecoveryMode::EitherTupleOrPipe = rt { + err.span_suggestion( + seq_span, + "...or a vertical bar to match on multiple alternatives", + seq_snippet.replace(',', " |"), + Applicability::MachineApplicable, + ); + } } Err(err) } diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index a11cb3f5677..a54ab4a92e1 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1,4 +1,4 @@ -use super::pat::{RecoverColon, RecoverComma, PARAM_EXPECTED}; +use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED}; use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; use super::{ AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, TokenType, @@ -1286,18 +1286,27 @@ fn parse_bottom_expr(&mut self) -> PResult<'a, P> { } else if let Some(label) = self.eat_label() { self.parse_labeled_expr(label, attrs, true) } else if self.eat_keyword(kw::Loop) { - self.parse_loop_expr(None, self.prev_token.span, attrs) + let sp = self.prev_token.span; + self.parse_loop_expr(None, self.prev_token.span, attrs).map_err(|mut err| { + err.span_label(sp, "while parsing this `loop` expression"); + err + }) } else if self.eat_keyword(kw::Continue) { let kind = ExprKind::Continue(self.eat_label()); Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs)) } else if self.eat_keyword(kw::Match) { let match_sp = self.prev_token.span; self.parse_match_expr(attrs).map_err(|mut err| { - err.span_label(match_sp, "while parsing this match expression"); + err.span_label(match_sp, "while parsing this `match` expression"); err }) } else if self.eat_keyword(kw::Unsafe) { + let sp = self.prev_token.span; self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs) + .map_err(|mut err| { + err.span_label(sp, "while parsing this `unsafe` expression"); + err + }) } else if self.check_inline_const(0) { self.parse_const_block(lo.to(self.token.span), false) } else if self.is_do_catch_block() { @@ -2160,7 +2169,12 @@ fn parse_cond_expr(&mut self) -> PResult<'a, P> { /// The `let` token has already been eaten. fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { let lo = self.prev_token.span; - let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?; + let pat = self.parse_pat_allow_top_alt( + None, + RecoverComma::Yes, + RecoverColon::Yes, + CommaRecoveryMode::LikelyTuple, + )?; self.expect(&token::Eq)?; let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| { this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into()) @@ -2223,7 +2237,12 @@ fn parse_for_expr( _ => None, }; - let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?; + let pat = self.parse_pat_allow_top_alt( + None, + RecoverComma::Yes, + RecoverColon::Yes, + CommaRecoveryMode::LikelyTuple, + )?; if !self.eat_keyword(kw::In) { self.error_missing_in_for_loop(); } @@ -2266,8 +2285,15 @@ fn parse_while_expr( lo: Span, mut attrs: AttrVec, ) -> PResult<'a, P> { - let cond = self.parse_cond_expr()?; - let (iattrs, body) = self.parse_inner_attrs_and_block()?; + let cond = self.parse_cond_expr().map_err(|mut err| { + err.span_label(lo, "while parsing the condition of this `while` expression"); + err + })?; + let (iattrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| { + err.span_label(lo, "while parsing the body of this `while` expression"); + err.span_label(cond.span, "this `while` condition successfully parsed"); + err + })?; attrs.extend(iattrs); Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs)) } @@ -2284,7 +2310,7 @@ fn parse_loop_expr( Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs)) } - fn eat_label(&mut self) -> Option