From 31e0383ea645f38402fe2bce2859490b6a55d965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 13 May 2026 02:29:42 +0000 Subject: [PATCH 1/3] rustfmt matches with comments in or-patterns Using https://github.com/rust-lang/rustfmt/pull/6893, reformat the codebase. The result is that matches that *would have* been formatted under normal circumstances get their expected format. These match expressions were being entirely skipped because they contain or-patterns with comments in between patterns, causing rustfmt to bail out entirely. The or-patterns with comments themselves remain untouched, but now the match arm bodies and other patterns without comments do get formatted under that PR. Because the fix in rustfmt isn't landed yet, I reworked some of the or-patterns with comments so that formatting doesn't regress. Tried doing this only in larger blocks that are more likely to regress in the meantime. --- compiler/rustc_ast/src/ast.rs | 20 +- compiler/rustc_ast/src/token.rs | 47 ++-- compiler/rustc_borrowck/src/def_use.rs | 7 +- compiler/rustc_borrowck/src/lib.rs | 43 ++-- .../src/polonius/legacy/loan_invalidations.rs | 8 +- compiler/rustc_codegen_ssa/src/mir/rvalue.rs | 33 ++- .../src/const_eval/valtrees.rs | 31 +-- compiler/rustc_hir/src/hir.rs | 19 +- .../rustc_hir_typeck/src/method/suggest.rs | 34 +-- compiler/rustc_lint/src/builtin.rs | 3 +- compiler/rustc_lint/src/lifetime_syntax.rs | 17 +- compiler/rustc_lint/src/unused.rs | 38 ++- compiler/rustc_middle/src/ty/sty.rs | 10 +- .../src/move_paths/builder.rs | 7 +- .../src/dataflow_const_prop.rs | 9 +- .../src/known_panics_lint.rs | 4 +- compiler/rustc_mir_transform/src/validate.rs | 23 +- .../rustc_parse/src/parser/diagnostics.rs | 36 +-- compiler/rustc_parse/src/parser/expr.rs | 7 +- .../rustc_parse/src/parser/nonterminal.rs | 14 +- compiler/rustc_resolve/src/late.rs | 12 +- .../rustc_resolve/src/late/diagnostics.rs | 29 ++- compiler/rustc_resolve/src/macros.rs | 3 +- .../traits/fulfillment_errors.rs | 232 ++++++++++-------- .../src/traits/auto_trait.rs | 31 +-- .../src/traits/dyn_compatibility.rs | 37 ++- .../src/traits/fulfill.rs | 2 +- .../src/maybe_transmutable/mod.rs | 2 +- compiler/rustc_ty_utils/src/sig_types.rs | 43 +++- 29 files changed, 456 insertions(+), 345 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 52b54655d1ca1..bc9f142e4a25c 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1557,12 +1557,10 @@ impl Expr { } match &self.kind { - ExprKind::Closure(closure) => { - match closure.fn_decl.output { - FnRetTy::Default(_) => ExprPrecedence::Jump, - FnRetTy::Ty(_) => prefix_attrs_precedence(&self.attrs), - } - } + ExprKind::Closure(closure) => match closure.fn_decl.output { + FnRetTy::Default(_) => ExprPrecedence::Jump, + FnRetTy::Ty(_) => prefix_attrs_precedence(&self.attrs), + }, ExprKind::Break(_ /*label*/, value) | ExprKind::Ret(value) @@ -1584,18 +1582,16 @@ impl Expr { ExprKind::Binary(op, ..) => op.node.precedence(), ExprKind::Cast(..) => ExprPrecedence::Cast, - ExprKind::Assign(..) | - ExprKind::AssignOp(..) => ExprPrecedence::Assign, + ExprKind::Assign(..) | ExprKind::AssignOp(..) => ExprPrecedence::Assign, // Unary, prefix - ExprKind::AddrOf(..) + ExprKind::AddrOf(..) => ExprPrecedence::Prefix, + // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`. // However, this is not exactly right. When `let _ = a` is the LHS of a binop we // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b` // but we need to print `(let _ = a) < b` as-is with parens. - | ExprKind::Let(..) - | ExprKind::Move(..) - | ExprKind::Unary(..) => ExprPrecedence::Prefix, + ExprKind::Let(..) | ExprKind::Move(..) | ExprKind::Unary(..) => ExprPrecedence::Prefix, // Need parens if and only if there are prefix attributes. ExprKind::Array(_) diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index 743e60d2f3bb2..e1746039963f4 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -688,10 +688,10 @@ impl Token { Lifetime(..) | // labeled loop Pound => true, // expression attributes OpenInvisible(InvisibleOrigin::MetaVar( - MetaVarKind::Block | - MetaVarKind::Expr { .. } | - MetaVarKind::Literal | - MetaVarKind::Path + MetaVarKind::Block + | MetaVarKind::Expr { .. } + | MetaVarKind::Literal + | MetaVarKind::Path, )) => true, _ => false, } @@ -717,12 +717,12 @@ impl Token { Shl => true, // path (double UFCS) Or => matches!(pat_kind, PatWithOr), // leading vert `|` or-pattern OpenInvisible(InvisibleOrigin::MetaVar( - MetaVarKind::Expr { .. } | - MetaVarKind::Literal | - MetaVarKind::Meta { .. } | - MetaVarKind::Pat(_) | - MetaVarKind::Path | - MetaVarKind::Ty { .. } + MetaVarKind::Expr { .. } + | MetaVarKind::Literal + | MetaVarKind::Meta { .. } + | MetaVarKind::Pat(_) + | MetaVarKind::Path + | MetaVarKind::Ty { .. }, )) => true, _ => false, } @@ -733,20 +733,19 @@ impl Token { match self.uninterpolate().kind { Ident(name, is_raw) => ident_can_begin_type(name, self.span, is_raw), // type name or keyword - OpenParen | // tuple - OpenBracket | // array - Bang | // never - Star | // raw pointer - And | // reference - AndAnd | // double reference - Question | // maybe bound in trait object - Lifetime(..) | // lifetime bound in trait object - Lt | Shl | // associated path - PathSep => true, // global path - OpenInvisible(InvisibleOrigin::MetaVar( - MetaVarKind::Ty { .. } | - MetaVarKind::Path - )) => true, + OpenParen // tuple + | OpenBracket // array + | Bang // never + | Star // raw pointer + | And // reference + | AndAnd // double reference + | Question // maybe bound in trait object + | Lifetime(..) // lifetime bound in trait object + | Lt | Shl // associated path + | PathSep => true, // global path + OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Ty { .. } | MetaVarKind::Path)) => { + true + } // For anonymous structs or unions, which only appear in specific positions // (type of struct fields or union fields), we don't consider them as regular types _ => false, diff --git a/compiler/rustc_borrowck/src/def_use.rs b/compiler/rustc_borrowck/src/def_use.rs index 502265a83523e..8813ef5249262 100644 --- a/compiler/rustc_borrowck/src/def_use.rs +++ b/compiler/rustc_borrowck/src/def_use.rs @@ -60,8 +60,7 @@ pub(crate) fn categorize(context: PlaceContext) -> Option { PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect) | PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) | PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) | - PlaceContext::MutatingUse(MutatingUseContext::Retag) => - Some(DefUse::Use), + PlaceContext::MutatingUse(MutatingUseContext::Retag) => Some(DefUse::Use), /////////////////////////////////////////////////////////////////////////// // DROP USES @@ -70,9 +69,7 @@ pub(crate) fn categorize(context: PlaceContext) -> Option { // call to `std::mem::drop()`). For the purposes of NLL, // uses in drop are special because `#[may_dangle]` // attributes can affect whether lifetimes must be live. - - PlaceContext::MutatingUse(MutatingUseContext::Drop) => - Some(DefUse::Drop), + PlaceContext::MutatingUse(MutatingUseContext::Drop) => Some(DefUse::Drop), // Debug info is neither def nor use. PlaceContext::NonUse(NonUseContext::VarDebugInfo) => None, diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 8b9f4291603a9..107ca87376015 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -833,19 +833,21 @@ impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!( span, "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics", - ) - } + ), + }, // Only relevant for mir typeck - StatementKind::AscribeUserType(..) + StatementKind::AscribeUserType(..) => {} // Only relevant for liveness and unsafeck - | StatementKind::PlaceMention(..) + StatementKind::PlaceMention(..) => {} // Doesn't have any language semantics - | StatementKind::Coverage(..) + StatementKind::Coverage(..) => {} // These do not actually affect borrowck - | StatementKind::ConstEvalCounter - | StatementKind::StorageLive(..) => {} + StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {} // This does not affect borrowck - StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => { + StatementKind::BackwardIncompatibleDropHint { + place, + reason: BackwardIncompatibleDropReason::Edition2024, + } => { self.check_backward_incompatible_drop(location, **place, state); } StatementKind::StorageDead(local) => { @@ -857,8 +859,7 @@ impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, state, ); } - StatementKind::Nop - | StatementKind::SetDiscriminant { .. } => { + StatementKind::Nop | StatementKind::SetDiscriminant { .. } => { bug!("Statement not allowed in this MIR phase") } } @@ -2243,10 +2244,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { ProjectionElem::ConstantIndex { .. } | // assigning to P[i] requires P to be valid. ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => - // assigning to (P->variant) is okay if assigning to `P` is okay - // - // FIXME: is this true even if P is an adt with a dtor? - { } + // assigning to (P->variant) is okay if assigning to `P` is okay + // + // FIXME: is this true even if P is an adt with a dtor? + {} ProjectionElem::UnwrapUnsafeBinder(_) => { check_parent_of_field(self, location, place_base, span, state); @@ -2255,8 +2256,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { // assigning to (*P) requires P to be initialized ProjectionElem::Deref => { self.check_if_full_path_is_moved( - location, InitializationRequiringAction::Use, - (place_base, span), state); + location, + InitializationRequiringAction::Use, + (place_base, span), + state, + ); // (base initialized; no need to // recur further) break; @@ -2275,8 +2279,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { match base_ty.kind() { ty::Adt(def, _) if def.has_dtor(tcx) => { self.check_if_path_or_subpath_is_moved( - location, InitializationRequiringAction::Assignment, - (place_base, span), state); + location, + InitializationRequiringAction::Assignment, + (place_base, span), + state, + ); // (base initialized; no need to // recur further) diff --git a/compiler/rustc_borrowck/src/polonius/legacy/loan_invalidations.rs b/compiler/rustc_borrowck/src/polonius/legacy/loan_invalidations.rs index 31df87dabf815..5a33b2d5bbe5b 100644 --- a/compiler/rustc_borrowck/src/polonius/legacy/loan_invalidations.rs +++ b/compiler/rustc_borrowck/src/polonius/legacy/loan_invalidations.rs @@ -56,11 +56,9 @@ impl<'a, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'a, 'tcx> { StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => { self.consume_operand(location, op); } - StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping { - src, - dst, - count, - })) => { + StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping( + CopyNonOverlapping { src, dst, count }, + )) => { self.consume_operand(location, src); self.consume_operand(location, dst); self.consume_operand(location, count); diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 0feb22e8d1d70..90ac8c89ba9ad 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -454,13 +454,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { OperandValue::Pair(lldata, llextra) } mir::CastKind::PointerCoercion( - PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _ + PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, + _, ) => { bug!("{kind:?} is for borrowck, and should never appear in codegen"); } - mir::CastKind::PtrToPtr - if bx.cx().is_backend_scalar_pair(operand.layout) => - { + mir::CastKind::PtrToPtr if bx.cx().is_backend_scalar_pair(operand.layout) => { if let OperandValue::Pair(data_ptr, meta) = operand.val { if bx.cx().is_backend_scalar_pair(cast) { OperandValue::Pair(data_ptr, meta) @@ -483,7 +482,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // path as the other integer-to-X casts. | mir::CastKind::PointerWithExposedProvenance => { let imm = operand.immediate(); - let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr else { + let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr + else { bug!("Found non-scalar for operand {operand:?}"); }; let from_backend_ty = bx.cx().immediate_backend_type(operand.layout); @@ -498,11 +498,18 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bug!("Found non-scalar for cast {cast:?}"); }; - self.cast_immediate(bx, imm, from_scalar, from_backend_ty, to_scalar, to_backend_ty) - .map(OperandValue::Immediate) - .unwrap_or_else(|| { - bug!("Unsupported cast of {operand:?} to {cast:?}"); - }) + self.cast_immediate( + bx, + imm, + from_scalar, + from_backend_ty, + to_scalar, + to_backend_ty, + ) + .map(OperandValue::Immediate) + .unwrap_or_else(|| { + bug!("Unsupported cast of {operand:?} to {cast:?}"); + }) } mir::CastKind::Transmute | mir::CastKind::Subtype => { self.codegen_transmute_operand(bx, operand, cast) @@ -553,6 +560,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { move_annotation: None, } } + mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => { let lhs = self.codegen_operand(bx, lhs); let rhs = self.codegen_operand(bx, rhs); @@ -666,7 +674,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { }; OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None } } + mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand), + mir::Rvalue::Repeat(ref elem, len_const) => { // All arrays have `BackendRepr::Memory`, so only the ZST cases // end up here. Anything else forces the destination local to be @@ -682,6 +692,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { move_annotation: None, } } + mir::Rvalue::Aggregate(ref kind, ref fields) => { let (variant_index, active_field_index) = match **kind { mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => { @@ -719,12 +730,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } } + mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => { let operand = self.codegen_operand(bx, operand); let binder_ty = self.monomorphize(binder_ty); let layout = bx.cx().layout_of(binder_ty); OperandRef { val: operand.val, layout, move_annotation: None } } + mir::Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in codegen"), } } diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 0169dc7ed99df..9fe3bff071f15 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -109,8 +109,7 @@ fn const_to_valtree_inner<'tcx>( // switch to the base type. place.layout = ecx.layout_of(*base).unwrap(); ensure_sufficient_stack(|| const_to_valtree_inner(ecx, &place, num_nodes)) - }, - + } ty::RawPtr(_, _) => { // Not all raw pointers are allowed, as we cannot properly test them for @@ -137,23 +136,19 @@ fn const_to_valtree_inner<'tcx>( // agree with runtime equality tests. ty::FnPtr(..) => Err(ValTreeCreationError::NonSupportedType(ty)), - ty::Ref(_, _, _) => { + ty::Ref(_, _, _) => { let derefd_place = ecx.deref_pointer(place).report_err()?; const_to_valtree_inner(ecx, &derefd_place, num_nodes) } - ty::Str | ty::Slice(_) | ty::Array(_, _) => { - slice_branches(ecx, place, num_nodes) - } + ty::Str | ty::Slice(_) | ty::Array(_, _) => slice_branches(ecx, place, num_nodes), // Trait objects are not allowed in type level constants, as we have no concept for // resolving their backing type, even if we can do that at const eval time. We may // hypothetically be able to allow `dyn StructuralPartialEq` trait objects in the future, // but it is unclear if this is useful. ty::Dynamic(..) => Err(ValTreeCreationError::NonSupportedType(ty)), - ty::Tuple(elem_tys) => { - branches(ecx, place, elem_tys.len(), None, num_nodes) - } + ty::Tuple(elem_tys) => branches(ecx, place, elem_tys.len(), None, num_nodes), ty::Adt(def, _) => { if def.is_union() { @@ -163,22 +158,30 @@ fn const_to_valtree_inner<'tcx>( } let variant = ecx.read_discriminant(place).report_err()?; - branches(ecx, place, def.variant(variant).fields.len(), def.is_enum().then_some(variant), num_nodes) + branches( + ecx, + place, + def.variant(variant).fields.len(), + def.is_enum().then_some(variant), + num_nodes, + ) } + // FIXME(oli-obk): we could look behind opaque types + ty::Alias(..) => Err(ValTreeCreationError::NonSupportedType(ty)), + + // FIXME(oli-obk): we can probably encode closures just like structs + ty::Closure(..) => Err(ValTreeCreationError::NonSupportedType(ty)), + ty::Never | ty::Error(_) | ty::Foreign(..) | ty::Infer(ty::FreshIntTy(_)) | ty::Infer(ty::FreshFloatTy(_)) - // FIXME(oli-obk): we could look behind opaque types - | ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(_) - // FIXME(oli-obk): we can probably encode closures just like structs - | ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..) | ty::CoroutineWitness(..) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 501ecadd392fc..55153001d7ccf 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2471,12 +2471,10 @@ impl Expr<'_> { }; match &self.kind { - ExprKind::Closure(closure) => { - match closure.fn_decl.output { - FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump, - FnRetTy::Return(_) => prefix_attrs_precedence(), - } - } + ExprKind::Closure(closure) => match closure.fn_decl.output { + FnRetTy::DefaultReturn(_) => ExprPrecedence::Jump, + FnRetTy::Return(_) => prefix_attrs_precedence(), + }, ExprKind::Break(..) | ExprKind::Ret(..) @@ -2487,17 +2485,16 @@ impl Expr<'_> { ExprKind::Binary(op, ..) => op.node.precedence(), ExprKind::Cast(..) => ExprPrecedence::Cast, - ExprKind::Assign(..) | - ExprKind::AssignOp(..) => ExprPrecedence::Assign, + ExprKind::Assign(..) | ExprKind::AssignOp(..) => ExprPrecedence::Assign, // Unary, prefix - ExprKind::AddrOf(..) + ExprKind::AddrOf(..) => ExprPrecedence::Prefix, + // Here `let pats = expr` has `let pats =` as a "unary" prefix of `expr`. // However, this is not exactly right. When `let _ = a` is the LHS of a binop we // need parens sometimes. E.g. we can print `(let _ = a) && b` as `let _ = a && b` // but we need to print `(let _ = a) < b` as-is with parens. - | ExprKind::Let(..) - | ExprKind::Unary(..) => ExprPrecedence::Prefix, + ExprKind::Let(..) | ExprKind::Unary(..) => ExprPrecedence::Prefix, // Need parens if and only if there are prefix attributes. ExprKind::Array(_) diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index d773420512590..0bdd6ce4b05cc 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1903,10 +1903,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (FxIndexSet::default(), FxIndexSet::default(), Vec::new()) }); entry.0.insert(cause_span); - entry.1.insert(( - cause_span, - cause_msg, - )); + entry.1.insert((cause_span, cause_msg)); entry.2.push(p); skip_list.insert(p); manually_impl = true; @@ -1918,16 +1915,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: item_span, .. })) => { - let sized_pred = - unsatisfied_predicates.iter().any(|(pred, _, _)| { - match pred.kind().skip_binder() { - ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => { - self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) - && pred.polarity == ty::PredicatePolarity::Positive - } - _ => false, + let sized_pred = unsatisfied_predicates.iter().any(|(pred, _, _)| { + match pred.kind().skip_binder() { + ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => { + self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) + && pred.polarity == ty::PredicatePolarity::Positive } - }); + _ => false, + } + }); for param in generics.params { if param.span == cause_span && sized_pred { let (sp, sugg) = match param.colon_span { @@ -1954,7 +1950,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { entry.2.push(p); if cause_span != *item_span { entry.0.insert(cause_span); - entry.1.insert((cause_span, "unsatisfied trait bound introduced here".to_string())); + entry.1.insert(( + cause_span, + "unsatisfied trait bound introduced here".to_string(), + )); } else { if let Some(of_trait) = of_trait { entry.0.insert(of_trait.trait_ref.path.span); @@ -1967,7 +1966,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { entry.1.insert((self_ty.span, String::new())); } Some(Node::Item(hir::Item { - kind: hir::ItemKind::Trait { is_auto: rustc_ast::ast::IsAuto::Yes, .. }, + kind: hir::ItemKind::Trait { is_auto: rustc_ast::ast::IsAuto::Yes, .. }, span: item_span, .. })) => { @@ -1994,7 +1993,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }); entry.0.insert(cause_span); entry.1.insert((ident.span, String::new())); - entry.1.insert((cause_span, "unsatisfied trait bound introduced here".to_string())); + entry.1.insert(( + cause_span, + "unsatisfied trait bound introduced here".to_string(), + )); entry.2.push(p); } _ => { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index ea0791783a642..0e4ee0a557030 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1510,8 +1510,7 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { for &(predicate, span) in predicates.predicates { let predicate_kind_name = match predicate.kind().skip_binder() { ClauseKind::Trait(..) => "trait", - ClauseKind::TypeOutlives(..) | - ClauseKind::RegionOutlives(..) => "lifetime", + ClauseKind::TypeOutlives(..) | ClauseKind::RegionOutlives(..) => "lifetime", ClauseKind::UnstableFeature(_) // `ConstArgHasType` is never global as `ct` is always a param diff --git a/compiler/rustc_lint/src/lifetime_syntax.rs b/compiler/rustc_lint/src/lifetime_syntax.rs index 6c65673acd0d8..1f3ecb03ebfc6 100644 --- a/compiler/rustc_lint/src/lifetime_syntax.rs +++ b/compiler/rustc_lint/src/lifetime_syntax.rs @@ -169,28 +169,19 @@ impl LifetimeSyntaxCategory { // E.g. `ContainsLifetime<'_>`. (ExplicitAnonymous, Path { .. }) | // E.g. `+ '_`, `+ use<'_>`. - (ExplicitAnonymous, OutlivesBound | PreciseCapturing) => { - Some(Self::Elided) - } + (ExplicitAnonymous, OutlivesBound | PreciseCapturing) => Some(Self::Elided), // E.g. `ContainsLifetime`. - (Implicit, Path { .. }) => { - Some(Self::Hidden) - } + (Implicit, Path { .. }) => Some(Self::Hidden), // E.g. `&'a T`. (ExplicitBound, Reference) | // E.g. `ContainsLifetime<'a>`. (ExplicitBound, Path { .. }) | // E.g. `+ 'a`, `+ use<'a>`. - (ExplicitBound, OutlivesBound | PreciseCapturing) => { - Some(Self::Named) - } + (ExplicitBound, OutlivesBound | PreciseCapturing) => Some(Self::Named), - (Implicit, OutlivesBound | PreciseCapturing) | - (_, Other) => { - None - } + (Implicit, OutlivesBound | PreciseCapturing) | (_, Other) => None, } } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 0cb7b4cce8462..ed7afa1c711de 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -761,23 +761,39 @@ impl EarlyLintPass for UnusedParens { let keep_space = (false, false); match &p.kind { // Do not lint on `(..)` as that will result in the other arms being useless. - Paren(_) + Paren(_) => {} // The other cases do not contain sub-patterns. - | Missing | Wild | Never | Rest | Expr(..) | MacCall(..) | Range(..) | Ident(.., None) - | Path(..) | Err(_) => {}, + Missing + | Wild + | Never + | Rest + | Expr(..) + | MacCall(..) + | Range(..) + | Ident(.., None) + | Path(..) + | Err(_) => {} // These are list-like patterns; parens can always be removed. - TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps { - self.check_unused_parens_pat(cx, p, false, false, keep_space); - }, - Struct(_, _, fps, _) => for f in fps { - self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space); - }, + TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => { + for p in ps { + self.check_unused_parens_pat(cx, p, false, false, keep_space); + } + } + Struct(_, _, fps, _) => { + for f in fps { + self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space); + } + } // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106. - Ident(.., Some(p)) | Box(p) | Deref(p) | Guard(p, _) => self.check_unused_parens_pat(cx, p, true, false, keep_space), + Ident(.., Some(p)) | Box(p) | Deref(p) | Guard(p, _) => { + self.check_unused_parens_pat(cx, p, true, false, keep_space) + } // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342. // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106. // FIXME(pin_ergonomics): check pinned patterns - Ref(p, _, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space), + Ref(p, _, m) => { + self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space) + } } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 112ad65e19bff..f208182c997f0 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1751,15 +1751,15 @@ impl<'tcx> Ty<'tcx> { | ty::Closure(..) | ty::CoroutineClosure(..) | ty::Never - | ty::Error(_) + | ty::Error(_) => Ok(tcx.types.unit), // Extern types have metadata = (). - | ty::Foreign(..) + ty::Foreign(..) => Ok(tcx.types.unit), // If returned by `struct_tail_raw` this is a unit struct // without any fields, or not a struct, and therefore is Sized. - | ty::Adt(..) + ty::Adt(..) => Ok(tcx.types.unit), // If returned by `struct_tail_raw` this is the empty tuple, // a.k.a. unit type, which is Sized - | ty::Tuple(..) => Ok(tcx.types.unit), + ty::Tuple(..) => Ok(tcx.types.unit), ty::Str | ty::Slice(_) => Ok(tcx.types.usize), @@ -1772,7 +1772,7 @@ impl<'tcx> Ty<'tcx> { // metadata of `tail`. ty::Param(_) | ty::Alias(..) => Err(tail), - | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"), + ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"), ty::Infer(ty::TyVar(_)) | ty::Pat(..) diff --git a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs index 905f36a3edb06..5982475361ca8 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs @@ -450,12 +450,12 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> { match term.kind { TerminatorKind::Goto { target: _ } | TerminatorKind::FalseEdge { .. } - | TerminatorKind::FalseUnwind { .. } + | TerminatorKind::FalseUnwind { .. } => {} // In some sense returning moves the return place into the current // call's destination, however, since there are no statements after // this that could possibly access the return place, this doesn't // need recording. - | TerminatorKind::Return + TerminatorKind::Return | TerminatorKind::UnwindResume | TerminatorKind::UnwindTerminate(_) | TerminatorKind::CoroutineDrop @@ -510,8 +510,7 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> { } => { for op in operands { match *op { - InlineAsmOperand::In { reg: _, ref value } - => { + InlineAsmOperand::In { reg: _, ref value } => { self.gather_operand(value); } InlineAsmOperand::Out { reg: _, late: _, place, .. } => { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 1c465977ec6ca..c83cfba34f790 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -871,8 +871,9 @@ fn try_write_constant<'tcx>( ty::FnDef(..) => {} // Those are scalars, must be handled above. - ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => - throw_machine_stop_str!("primitive type with provenance"), + ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => { + throw_machine_stop_str!("primitive type with provenance") + } ty::Tuple(elem_tys) => { for (i, elem) in elem_tys.iter().enumerate() { @@ -898,7 +899,9 @@ fn try_write_constant<'tcx>( throw_machine_stop_str!("discriminant with provenance") }; let discr_bits = discr.to_bits(discr.size()); - let Some((variant, _)) = def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val) else { + let Some((variant, _)) = + def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val) + else { throw_machine_stop_str!("illegal discriminant for enum") }; let Some(variant_place) = map.apply(place, TrackElem::Variant(variant)) else { diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index 6c2ca9166b101..9f187c5c75959 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -955,7 +955,9 @@ impl<'tcx> Visitor<'tcx> for CanConstProp { self.can_const_prop[local] = ConstPropMode::NoPropagation; } MutatingUse(MutatingUseContext::Projection) - | NonMutatingUse(NonMutatingUseContext::Projection) => bug!("visit_place should not pass {context:?} for {local:?}"), + | NonMutatingUse(NonMutatingUseContext::Projection) => { + bug!("visit_place should not pass {context:?} for {local:?}") + } } } } diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 746662e6a302f..df789618ad908 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -145,26 +145,21 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> { let src = self.body.basic_blocks.get(location.block).unwrap(); match (src.is_cleanup, bb.is_cleanup, edge_kind) { // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges - (false, false, EdgeKind::Normal) + (false, false, EdgeKind::Normal) => {} // Cleanup blocks can jump to cleanup blocks along non-unwind edges - | (true, true, EdgeKind::Normal) => {} + (true, true, EdgeKind::Normal) => {} // Non-cleanup blocks can jump to cleanup blocks along unwind edges (false, true, EdgeKind::Unwind) => { self.unwind_edge_count += 1; } // All other jumps are invalid - _ => { - self.fail( - location, - format!( - "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})", - edge_kind, - bb, - src.is_cleanup, - bb.is_cleanup, - ) - ) - } + _ => self.fail( + location, + format!( + "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})", + edge_kind, bb, src.is_cleanup, bb.is_cleanup, + ), + ), } } else { self.fail(location, format!("encountered jump to invalid basic block {bb:?}")) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 47ac91feefd4b..f935f43d336c8 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1349,19 +1349,19 @@ impl<'a> Parser<'a> { (BinOpKind::Gt, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) | (BinOpKind::Ge, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) => { let expr_to_str = |e: &Expr| { - self.span_to_snippet(e.span) - .unwrap_or_else(|_| pprust::expr_to_string(e)) + self.span_to_snippet(e.span).unwrap_or_else(|_| pprust::expr_to_string(e)) }; - err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison { - span: inner_op.span.shrink_to_hi(), - middle_term: expr_to_str(r1), - }); + err.chaining_sugg = + Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison { + span: inner_op.span.shrink_to_hi(), + middle_term: expr_to_str(r1), + }); false // Keep the current parse behavior, where the AST is `(x < y) < z`. } // `x == y < z` ( BinOpKind::Eq, - AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge) + AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge), ) => { // Consume `z`/outer-op-rhs. let snapshot = self.create_snapshot_for_diagnostic(); @@ -1369,10 +1369,11 @@ impl<'a> Parser<'a> { Ok(r2) => { // We are sure that outer-op-rhs could be consumed, the suggestion is // likely correct. - err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize { - left: r1.span.shrink_to_lo(), - right: r2.span.shrink_to_hi(), - }); + err.chaining_sugg = + Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize { + left: r1.span.shrink_to_lo(), + right: r2.span.shrink_to_hi(), + }); true } Err(expr_err) => { @@ -1385,17 +1386,18 @@ impl<'a> Parser<'a> { // `x > y == z` ( BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, - AssocOp::Binary(BinOpKind::Eq) + AssocOp::Binary(BinOpKind::Eq), ) => { let snapshot = self.create_snapshot_for_diagnostic(); // At this point it is always valid to enclose the lhs in parentheses, no // further checks are necessary. match self.parse_expr() { Ok(_) => { - err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize { - left: l1.span.shrink_to_lo(), - right: r1.span.shrink_to_hi(), - }); + err.chaining_sugg = + Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize { + left: l1.span.shrink_to_lo(), + right: r1.span.shrink_to_hi(), + }); true } Err(expr_err) => { @@ -1405,7 +1407,7 @@ impl<'a> Parser<'a> { } } } - _ => false + _ => false, }; } false diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index e5de0d972df6a..957ed9ab55e0a 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1107,9 +1107,7 @@ impl<'a> Parser<'a> { match &*components { // 1e2 - [IdentLike(i)] => { - DestructuredFloat::Single(Symbol::intern(i), span) - } + [IdentLike(i)] => DestructuredFloat::Single(Symbol::intern(i), span), // 1. [IdentLike(left), Punct('.')] => { let (left_span, dot_span) = if can_take_span_apart() { @@ -1126,7 +1124,8 @@ impl<'a> Parser<'a> { [IdentLike(left), Punct('.'), IdentLike(right)] => { let (left_span, dot_span, right_span) = if can_take_span_apart() { let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len())); - let dot_span = span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1)); + let dot_span = + span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1)); let right_span = span.with_lo(dot_span.hi()); (left_span, dot_span, right_span) } else { diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 6ca7f89c76776..1b1d7ddb24b1b 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -26,18 +26,16 @@ impl<'a> Parser<'a> { | MetaVarKind::Pat(_) | MetaVarKind::Expr { .. } | MetaVarKind::Ty { .. } - | MetaVarKind::Literal // `true`, `false` | MetaVarKind::Meta { .. } | MetaVarKind::Path => true, + // `true`, `false` + MetaVarKind::Literal => true, - MetaVarKind::Item - | MetaVarKind::Block - | MetaVarKind::Vis - | MetaVarKind::Guard => false, + MetaVarKind::Item | MetaVarKind::Block | MetaVarKind::Vis | MetaVarKind::Guard => { + false + } - MetaVarKind::Ident - | MetaVarKind::Lifetime - | MetaVarKind::TT => unreachable!(), + MetaVarKind::Ident | MetaVarKind::Lifetime | MetaVarKind::TT => unreachable!(), } } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index e8bd3abdc621e..a1d496337dbb6 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -4397,7 +4397,13 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } Some(res) } - Res::Def(DefKind::Ctor(..) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::Static { .. }, _) => { + Res::Def( + DefKind::Ctor(..) + | DefKind::Const { .. } + | DefKind::AssocConst { .. } + | DefKind::Static { .. }, + _, + ) => { // This is unambiguously a fresh binding, either syntactically // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves // to something unusable as a pattern (e.g., constructor function), @@ -4429,7 +4435,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { article: res.article(), shadowed_binding: res, shadowed_binding_span: self.r.def_span(def_id), - } + }, ); None } @@ -4442,7 +4448,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { // so delay a bug instead of ICEing. self.r.dcx().span_delayed_bug( ident.span, - "unexpected `SelfCtor` in pattern, expected identifier" + "unexpected `SelfCtor` in pattern, expected identifier", ); None } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 10c864226d220..0f3d256f5158d 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -3468,7 +3468,11 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char { return (None, None); } - match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) { + match ( + self.diag_metadata.current_item, + single_uppercase_char, + self.diag_metadata.currently_processing_generic_args, + ) { (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => { // Ignore `fn main()` as we don't want to suggest `fn main()` } @@ -3481,7 +3485,8 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { | kind @ ItemKind::Union(..), .. }), - true, _ + true, + _, ) // Without the 2nd `true`, we'd suggest `impl ` for `impl T` when a type `T` isn't found | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true) @@ -3501,7 +3506,9 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let (msg, sugg) = match source { PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => { - if let Some(err) = self.detect_and_suggest_const_parameter_error(path, source) { + if let Some(err) = + self.detect_and_suggest_const_parameter_error(path, source) + { return (None, Some(err)); } ("you might be missing a type parameter", ident) @@ -3516,8 +3523,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let span = if let [.., bound] = ¶m.bounds[..] { bound.span() } else if let GenericParam { - kind: GenericParamKind::Const { ty, span: _, default }, .. - } = param { + kind: GenericParamKind::Const { ty, span: _, default }, + .. + } = param + { default.as_ref().map(|def| def.value.span).unwrap_or(ty.span) } else { param.ident.span @@ -3528,12 +3537,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { }; // Do not suggest if this is coming from macro expansion. if span.can_be_used_for_suggestions() { - return (Some(( - span.shrink_to_hi(), - msg, - sugg, - Applicability::MaybeIncorrect, - )), None); + return ( + Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)), + None, + ); } } } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 206e32f61b485..f4166fb29f77f 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1273,8 +1273,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { PathResult::NonModule(..) | // HACK(Urgau): This shouldn't be necessary PathResult::Failed { is_error_from_last_segment: false, .. } => { - self.dcx() - .emit_err(errors::CfgAccessibleUnsure { span }); + self.dcx().emit_err(errors::CfgAccessibleUnsure { span }); // If we get a partially resolved NonModule in one namespace, we should get the // same result in any other namespaces, so we can return early. diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 4b67cada078a4..0ade2391e13dd 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -73,10 +73,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { root_obligation.cause.code().peel_derives() && !obligation.predicate.has_non_region_infer() { - if let Some(cause) = self - .tcx - .diagnostic_hir_wf_check((tcx.erase_and_anonymize_regions(obligation.predicate), *wf_loc)) - { + if let Some(cause) = self.tcx.diagnostic_hir_wf_check(( + tcx.erase_and_anonymize_regions(obligation.predicate), + *wf_loc, + )) { obligation.cause = cause.clone(); span = obligation.cause.span; } @@ -89,13 +89,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } = *obligation.cause.code() { debug!("ObligationCauseCode::CompareImplItemObligation"); - return self.report_extra_impl_obligation( - span, - impl_item_def_id, - trait_item_def_id, - &format!("`{}`", obligation.predicate), - ) - .emit() + return self + .report_extra_impl_obligation( + span, + impl_item_def_id, + trait_item_def_id, + &format!("`{}`", obligation.predicate), + ) + .emit(); } // Report a const-param specific error @@ -116,7 +117,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // // We rely on a few heuristics to identify cases where this root // obligation is more important than the leaf obligation: - let (main_trait_predicate, main_obligation) = if let ty::PredicateKind::Clause( + let (main_trait_predicate, main_obligation) = + if let ty::PredicateKind::Clause( ty::ClauseKind::Trait(root_pred) ) = root_obligation.predicate.kind().skip_binder() && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars() @@ -146,26 +148,24 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // The root trait is not `Unsize`, as to avoid talking about it in // `tests/ui/coercion/coerce-issue-49593-box-never.rs`. && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize) - { - ( - self.resolve_vars_if_possible( - root_obligation.predicate.kind().rebind(root_pred), - ), - root_obligation, - ) - } else { - (leaf_trait_predicate, &obligation) - }; + { + ( + self.resolve_vars_if_possible( + root_obligation.predicate.kind().rebind(root_pred), + ), + root_obligation, + ) + } else { + (leaf_trait_predicate, &obligation) + }; - if let Some(guar) = self.emit_specialized_closure_kind_error( - &obligation, - leaf_trait_predicate, - ) { + if let Some(guar) = self + .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate) + { return guar; } - if let Err(guar) = leaf_trait_predicate.error_reported() - { + if let Err(guar) = leaf_trait_predicate.error_reported() { return guar; } // Silence redundant errors on binding access that are already @@ -185,29 +185,32 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) .unwrap_or_default(); - let CustomDiagnostic { - message, - label, - notes, - parent_label, - } = self.on_unimplemented_note(main_trait_predicate, main_obligation, &mut long_ty_file); + let CustomDiagnostic { message, label, notes, parent_label } = self + .on_unimplemented_note( + main_trait_predicate, + main_obligation, + &mut long_ty_file, + ); let have_alt_message = message.is_some() || label.is_some(); - let message = message.unwrap_or_else(|| self.get_standard_error_message( - main_trait_predicate, - None, - post_message, - &mut long_ty_file, - )); - let is_try_conversion = self.is_try_conversion(span, main_trait_predicate.def_id()); + let message = message.unwrap_or_else(|| { + self.get_standard_error_message( + main_trait_predicate, + None, + post_message, + &mut long_ty_file, + ) + }); + let is_try_conversion = + self.is_try_conversion(span, main_trait_predicate.def_id()); let is_question_mark = matches!( root_obligation.cause.code().peel_derives(), ObligationCauseCode::QuestionMark, - ) && !( - self.tcx.is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id()) - || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try) - ); + ) && !(self + .tcx + .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id()) + || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try)); let is_unsize = self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize); let question_mark_message = "the question mark operation (`?`) implicitly \ @@ -240,13 +243,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { (message, notes) }; - let (err_msg, safe_transmute_explanation) = if self.tcx.is_lang_item( - main_trait_predicate.def_id(), - LangItem::TransmuteTrait, - ) { + let (err_msg, safe_transmute_explanation) = if self + .tcx + .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait) + { // Recompute the safe transmute reason and use that for the error reporting - let (report_obligation, report_pred) = - self.select_transmute_obligation_for_reporting( + let (report_obligation, report_pred) = self + .select_transmute_obligation_for_reporting( &obligation, main_trait_predicate, root_obligation, @@ -258,13 +261,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { span, ) { GetSafeTransmuteErrorAndReason::Silent => { - return self.dcx().span_delayed_bug( - span, "silent safe transmute error" - ); - } - GetSafeTransmuteErrorAndReason::Default => { - (message, None) + return self + .dcx() + .span_delayed_bug(span, "silent safe transmute error"); } + GetSafeTransmuteErrorAndReason::Default => (message, None), GetSafeTransmuteErrorAndReason::Error { err_msg, safe_transmute_explanation, @@ -285,15 +286,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { { let trait_ref = leaf_trait_predicate.skip_binder().trait_ref; - if let Some(found_ty) = trait_ref.args.get(1).and_then(|arg| arg.as_type()) + if let Some(found_ty) = + trait_ref.args.get(1).and_then(|arg| arg.as_type()) { let ty = main_trait_predicate.skip_binder().self_ty(); - if let Some(cast_ty) = self.find_explicit_cast_type( - obligation.param_env, - found_ty, - ty, - ) { + if let Some(cast_ty) = + self.find_explicit_cast_type(obligation.param_env, found_ty, ty) + { let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file); let cast_ty_str = @@ -306,13 +306,16 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } - *err.long_ty_path() = long_ty_file; let mut suggested = false; let mut noted_missing_impl = false; if is_try_conversion || is_question_mark { - (suggested, noted_missing_impl) = self.try_conversion_context(&obligation, main_trait_predicate, &mut err); + (suggested, noted_missing_impl) = self.try_conversion_context( + &obligation, + main_trait_predicate, + &mut err, + ); } suggested |= self.detect_negative_literal( @@ -378,8 +381,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() { - ty::Adt(def, _) if def.did().is_local() - && !self.can_suggest_derive(&obligation, leaf_trait_predicate) => self.tcx.def_span(def.did()), + ty::Adt(def, _) + if def.did().is_local() + && !self + .can_suggest_derive(&obligation, leaf_trait_predicate) => + { + self.tcx.def_span(def.did()) + } _ => DUMMY_SP, }; if let Some(s) = label { @@ -391,8 +399,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // `std::marker::Sized` is not implemented for `T`" as we will point // at the type param with a label to suggest constraining it. && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id()) - // Don't say "the trait `FromResidual>` is - // not implemented for `Result`". + // Don't say "the trait `FromResidual>` is + // not implemented for `Result`". { // We do this just so that the JSON output's `help` position is the // right one and not `file.rs:1:1`. The render is the same. @@ -404,7 +412,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } else if let Some(custom_explanation) = safe_transmute_explanation { err.span_label(span, custom_explanation); - } else if (explanation.len() > self.tcx.sess.diagnostic_width() || ty_span != DUMMY_SP) && !noted_missing_impl { + } else if (explanation.len() > self.tcx.sess.diagnostic_width() + || ty_span != DUMMY_SP) + && !noted_missing_impl + { // Really long types don't look good as span labels, instead move it // to a `help`. err.span_label(span, "unsatisfied trait bound"); @@ -423,7 +434,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if let ObligationCauseCode::Coercion { source, target } = *obligation.cause.code().peel_derives() { - if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized) { + if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized) + { self.suggest_borrowing_for_object_cast( &mut err, root_obligation, @@ -445,10 +457,20 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.span_label(tcx.def_span(body), s); } - self.suggest_floating_point_literal(&obligation, &mut err, leaf_trait_predicate); - self.suggest_dereferencing_index(&obligation, &mut err, leaf_trait_predicate); - suggested |= self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate); - suggested |= self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate); + self.suggest_floating_point_literal( + &obligation, + &mut err, + leaf_trait_predicate, + ); + self.suggest_dereferencing_index( + &obligation, + &mut err, + leaf_trait_predicate, + ); + suggested |= + self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate); + suggested |= + self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate); suggested |= self.suggest_cast_to_fn_pointer( &obligation, &mut err, @@ -456,15 +478,22 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { main_trait_predicate, span, ); - suggested |= - self.suggest_remove_reference(&obligation, &mut err, leaf_trait_predicate); + suggested |= self.suggest_remove_reference( + &obligation, + &mut err, + leaf_trait_predicate, + ); suggested |= self.suggest_semicolon_removal( &obligation, &mut err, span, leaf_trait_predicate, ); - self.note_different_trait_with_same_name(&mut err, &obligation, leaf_trait_predicate); + self.note_different_trait_with_same_name( + &mut err, + &obligation, + leaf_trait_predicate, + ); self.note_adt_version_mismatch(&mut err, leaf_trait_predicate); self.suggest_remove_await(&obligation, &mut err); self.suggest_derive(&obligation, &mut err, leaf_trait_predicate); @@ -478,7 +507,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ); } - if self.suggest_add_clone_to_arg(&obligation, &mut err, leaf_trait_predicate) { + if self.suggest_add_clone_to_arg( + &obligation, + &mut err, + leaf_trait_predicate, + ) { return err.emit(); } @@ -553,11 +586,18 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { \ for more information)", ); - err.help("you might have intended to use the type `()` here instead"); + err.help( + "you might have intended to use the type `()` here instead", + ); } } - self.explain_hrtb_projection(&mut err, leaf_trait_predicate, obligation.param_env, &obligation.cause); + self.explain_hrtb_projection( + &mut err, + leaf_trait_predicate, + obligation.param_env, + &obligation.cause, + ); self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate); // Return early if the trait is Debug or Display and the invocation @@ -586,9 +626,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err } - ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => { - self.report_host_effect_error(bound_predicate.rebind(predicate), &obligation, span) - } + ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => self + .report_host_effect_error( + bound_predicate.rebind(predicate), + &obligation, + span, + ), ty::PredicateKind::Subtype(predicate) => { // Errors for Subtype predicates show up as @@ -668,17 +711,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } - // Errors for `ConstEvaluatable` predicates show up as - // `SelectionError::ConstEvalFailure`, - // not `Unimplemented`. + // Errors for `ConstEvaluatable`, `ConstEquate` predicates show up as + // `SelectionError::ConstEvalFailure`, not `Unimplemented`. + // Ambiguous predicates should never error. + // We never return `Err` when proving `UnstableFeature`` goal. ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) - // Errors for `ConstEquate` predicates show up as - // `SelectionError::ConstEvalFailure`, - // not `Unimplemented`. | ty::PredicateKind::ConstEquate { .. } - // Ambiguous predicates should never error | ty::PredicateKind::Ambiguous - // We never return Err when proving UnstableFeature goal. | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. }) | ty::PredicateKind::NormalizesTo { .. } | ty::PredicateKind::AliasRelate { .. } @@ -736,12 +775,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } // Already reported in the query. - SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar)) | - // Already reported. - SelectionError::Overflow(OverflowError::Error(guar)) => { + SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar)) + | SelectionError::Overflow(OverflowError::Error(guar)) => { self.set_tainted_by_errors(guar); - return guar - }, + return guar; + } SelectionError::Overflow(_) => { bug!("overflow should be handled before the `report_selection_error` path"); diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 646945990a1d5..af104a56202b0 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -740,7 +740,11 @@ impl<'tcx> AutoTraitFinder<'tcx> { ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(binder)) => { let binder = bound_predicate.rebind(binder); selcx.infcx.enter_forall(binder, |pred| { - selcx.infcx.register_region_outlives_constraint(pred, ty::VisibleForLeakCheck::Yes,&dummy_cause); + selcx.infcx.register_region_outlives_constraint( + pred, + ty::VisibleForLeakCheck::Yes, + &dummy_cause, + ); }); } ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(binder)) => { @@ -757,11 +761,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { ); } (Some(ty::OutlivesPredicate(t_a, r_b)), _) => { - selcx.infcx.register_type_outlives_constraint( - t_a, - r_b, - &dummy_cause, - ); + selcx.infcx.register_type_outlives_constraint(t_a, r_b, &dummy_cause); } _ => {} }; @@ -769,11 +769,8 @@ impl<'tcx> AutoTraitFinder<'tcx> { ty::PredicateKind::ConstEquate(c1, c2) => { let evaluate = |c: ty::Const<'tcx>| { if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() { - let ct = super::try_evaluate_const( - selcx.infcx, - c, - obligation.param_env, - ); + let ct = + super::try_evaluate_const(selcx.infcx, c, obligation.param_env); if let Err(EvaluateConstErr::InvalidConstParamTy(_)) = ct { self.tcx.dcx().emit_err(UnableToConstructConstantValue { @@ -790,8 +787,11 @@ impl<'tcx> AutoTraitFinder<'tcx> { match (evaluate(c1), evaluate(c2)) { (Ok(c1), Ok(c2)) => { - match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(DefineOpaqueTypes::Yes,c1, c2) - { + match selcx.infcx.at(&obligation.cause, obligation.param_env).eq( + DefineOpaqueTypes::Yes, + c1, + c2, + ) { Ok(_) => (), Err(_) => return false, } @@ -810,12 +810,13 @@ impl<'tcx> AutoTraitFinder<'tcx> { | ty::PredicateKind::AliasRelate(..) | ty::PredicateKind::DynCompatible(..) | ty::PredicateKind::Subtype(..) - // FIXME(generic_const_exprs): you can absolutely add this as a where clauses - | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) | ty::PredicateKind::Coerce(..) | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => {} ty::PredicateKind::Ambiguous => return false, + + // FIXME(generic_const_exprs): you can absolutely add this as a where clauses + ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) => return false, }; } true diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index d1522ec89a016..c48e56c06d6ba 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -223,7 +223,17 @@ fn predicate_references_self<'tcx>( match predicate.kind().skip_binder() { ty::ClauseKind::Trait(ref data) => { // In the case of a trait predicate, we can skip the "self" type. - data.trait_ref.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp) + data.trait_ref.args[1..] + .iter() + .any(|&arg| { + contains_illegal_self_type_reference( + tcx, + trait_def_id, + arg, + allow_self_projections, + ) + }) + .then_some(sp) } ty::ClauseKind::Projection(ref data) => { // And similarly for projections. This should be redundant with @@ -241,18 +251,31 @@ fn predicate_references_self<'tcx>( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - data.projection_term.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp) + data.projection_term.args[1..] + .iter() + .any(|&arg| { + contains_illegal_self_type_reference( + tcx, + trait_def_id, + arg, + allow_self_projections, + ) + }) + .then_some(sp) + } + ty::ClauseKind::ConstArgHasType(_ct, ty) => { + contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections) + .then_some(sp) } - ty::ClauseKind::ConstArgHasType(_ct, ty) => contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections).then_some(sp), ty::ClauseKind::WellFormed(..) | ty::ClauseKind::TypeOutlives(..) | ty::ClauseKind::RegionOutlives(..) - // FIXME(generic_const_exprs): this can mention `Self` - | ty::ClauseKind::ConstEvaluatable(..) | ty::ClauseKind::HostEffect(..) - | ty::ClauseKind::UnstableFeature(_) - => None, + | ty::ClauseKind::UnstableFeature(_) => None, + + // FIXME(generic_const_exprs): this can mention `Self` + ty::ClauseKind::ConstEvaluatable(..) => None, } } diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index ce8f05637f9a6..914e103afded3 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -464,7 +464,7 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { bug!("AliasRelate is only used by the new solver") } ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) => { - unreachable!("unexpected higher ranked `UnstableFeature` goal") + unreachable!("unexpected higher ranked `UnstableFeature` goal") } }, Some(pred) => match pred { diff --git a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs index 062de4b5d08a7..b748611be383f 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs @@ -330,7 +330,7 @@ impl Answer { // If either is an error, return it | (Answer::No(reason), _) | (_, Answer::No(reason)) => Answer::No(reason), // If only one side has a condition, pass it along - | (Answer::Yes, other) | (other, Answer::Yes) => other, + (Answer::Yes, other) | (other, Answer::Yes) => other, // If both sides have IfAll conditions, merge them (Answer::If(Condition::IfAll(mut lhs)), Answer::If(Condition::IfAll(ref mut rhs))) => { lhs.append(rhs); diff --git a/compiler/rustc_ty_utils/src/sig_types.rs b/compiler/rustc_ty_utils/src/sig_types.rs index ab4bfd998cf34..ebec1888e6a95 100644 --- a/compiler/rustc_ty_utils/src/sig_types.rs +++ b/compiler/rustc_ty_utils/src/sig_types.rs @@ -41,10 +41,13 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( try_visit!(visitor.visit(span, pred.skip_norm_wip())); } } - // Walk over the type behind the alias - DefKind::TyAlias { .. } | DefKind::AssocTy | - // Walk over the type of the item - DefKind::Static { .. } | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::AnonConst => { + // Walk over the type behind the alias or the type of the item + DefKind::TyAlias { .. } + | DefKind::AssocTy + | DefKind::Static { .. } + | DefKind::Const { .. } + | DefKind::AssocConst { .. } + | DefKind::AnonConst => { if let Some(ty) = tcx.hir_node_by_def_id(item).ty() { // If the type of the item uses `_`, we're gonna error out anyway, but // typeck (which type_of invokes below), will call back into opaque_types_defined_by @@ -53,14 +56,21 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( return V::Result::output(); } // Associated types in traits don't necessarily have a type that we can visit - try_visit!(visitor.visit(ty.span, tcx.type_of(item).instantiate_identity().skip_norm_wip())); + try_visit!( + visitor + .visit(ty.span, tcx.type_of(item).instantiate_identity().skip_norm_wip()) + ); } for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred.skip_norm_wip())); } } DefKind::OpaqueTy => { - for (pred, span) in tcx.explicit_item_bounds(item).iter_identity_copied().map(Unnormalized::skip_norm_wip) { + for (pred, span) in tcx + .explicit_item_bounds(item) + .iter_identity_copied() + .map(Unnormalized::skip_norm_wip) + { try_visit!(visitor.visit(span, pred)); } } @@ -87,15 +97,26 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( DefKind::InlineConst | DefKind::Closure | DefKind::SyntheticCoroutineBody => {} DefKind::Impl { of_trait } => { if of_trait { - let span = tcx.hir_node_by_def_id(item).expect_item().expect_impl().of_trait.unwrap().trait_ref.path.span; - let args = &tcx.impl_trait_ref(item).instantiate_identity().skip_norm_wip().args[1..]; + let span = tcx + .hir_node_by_def_id(item) + .expect_item() + .expect_impl() + .of_trait + .unwrap() + .trait_ref + .path + .span; + let args = + &tcx.impl_trait_ref(item).instantiate_identity().skip_norm_wip().args[1..]; try_visit!(visitor.visit(span, args)); } let span = match tcx.hir_node_by_def_id(item).ty() { Some(ty) => ty.span, _ => tcx.def_span(item), }; - try_visit!(visitor.visit(span, tcx.type_of(item).instantiate_identity().skip_norm_wip())); + try_visit!( + visitor.visit(span, tcx.type_of(item).instantiate_identity().skip_norm_wip()) + ); for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred.skip_norm_wip())); } @@ -105,7 +126,7 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( try_visit!(visitor.visit(span, pred.skip_norm_wip())); } } - | DefKind::Variant + DefKind::Variant | DefKind::TyParam | DefKind::ConstParam | DefKind::Ctor(_, _) @@ -117,7 +138,7 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( ) } // These don't have any types, but are visited during privacy checking. - | DefKind::ExternCrate + DefKind::ExternCrate | DefKind::ForeignMod | DefKind::ForeignTy | DefKind::Macro(_) From 701e4942ed6b1c3e487b66b4a1bd4ea8d25015b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 13 May 2026 02:40:58 +0000 Subject: [PATCH 2/3] Remove a bunch of stray backticks Thanks VSCode! --- .../src/error_reporting/traits/fulfillment_errors.rs | 2 +- .../clippy_lints/src/default_numeric_fallback.rs | 2 +- src/tools/miri/src/shims/os_str.rs | 2 +- src/tools/run-make-support/src/external_deps/rustc.rs | 4 ++-- src/tools/rust-analyzer/crates/hir-ty/src/traits.rs | 10 +++++----- src/tools/rust-analyzer/crates/mbe/src/parser.rs | 2 +- .../crates/project-model/src/workspace.rs | 2 +- .../dont-ice-when-body-tainted-by-errors.rs | 2 +- tests/ui/parser/const-block-items/pub.rs | 2 +- tests/ui/parser/raw/raw-idents.rs | 2 +- .../normalize/indirectly-constrained-term.rs | 2 +- 11 files changed, 16 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 0ade2391e13dd..bf881feb60158 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -714,7 +714,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Errors for `ConstEvaluatable`, `ConstEquate` predicates show up as // `SelectionError::ConstEvalFailure`, not `Unimplemented`. // Ambiguous predicates should never error. - // We never return `Err` when proving `UnstableFeature`` goal. + // We never return `Err` when proving `UnstableFeature` goal. ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) | ty::PredicateKind::ConstEquate { .. } | ty::PredicateKind::Ambiguous diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index f93f682bc9298..8ec095cc24dde 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -133,7 +133,7 @@ impl<'tcx> Visitor<'tcx> for NumericFallbackVisitor<'_, 'tcx> { if let Some(fn_sig) = self.cx.tcx.parent_hir_node(expr.hir_id).fn_sig() && let FnRetTy::Return(_ty) = fn_sig.decl.output { - // We cannot check the exact type since it's a `hir::Ty`` which does not implement `is_numeric` + // We cannot check the exact type since it's a `hir::Ty` which does not implement `is_numeric` self.ty_bounds.push(ExplicitTyBound(true)); for stmt in *stmts { self.visit_stmt(stmt); diff --git a/src/tools/miri/src/shims/os_str.rs b/src/tools/miri/src/shims/os_str.rs index db9cb3a7a32bd..78e7f2d418c30 100644 --- a/src/tools/miri/src/shims/os_str.rs +++ b/src/tools/miri/src/shims/os_str.rs @@ -282,7 +282,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { *c = sep; } } - // If this starts with `//?/`, it was probably produced by `unix_to_windows`` and we + // If this starts with `//?/`, it was probably produced by `unix_to_windows` and we // remove the `//?` that got added to get the Unix path back out. if path.get(0..4) == Some(&[sep, sep, b'?'.into(), sep]) { // Remove first 3 characters. It still starts with `/` so it is absolute on Unix. diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index e8645e00e1852..b5d9593ae9a6a 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -190,14 +190,14 @@ impl Rustc { self } - /// Specify path to the output file. Equivalent to `-o`` in rustc. + /// Specify path to the output file. Equivalent to `-o` in rustc. pub fn output>(&mut self, path: P) -> &mut Self { self.cmd.arg("-o"); self.cmd.arg(path.as_ref()); self } - /// Specify path to the output directory. Equivalent to `--out-dir`` in rustc. + /// Specify path to the output directory. Equivalent to `--out-dir` in rustc. pub fn out_dir>(&mut self, path: P) -> &mut Self { self.cmd.arg("--out-dir"); self.cmd.arg(path.as_ref()); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs b/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs index ad1c3fb709c9d..9582f2ceba831 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs @@ -232,11 +232,11 @@ pub fn is_inherent_impl_coherent(db: &dyn HirDatabase, def_map: &DefMap, impl_id /// Checks whether the impl satisfies the orphan rules. /// -/// Given `impl Trait for T0`, an `impl`` is valid only if at least one of the following is true: +/// Given `impl Trait for T0`, an `impl` is valid only if at least one of the following is true: /// - Trait is a local trait /// - All of -/// - At least one of the types `T0..=Tn`` must be a local type. Let `Ti`` be the first such type. -/// - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti`` (excluding `Ti`) +/// - At least one of the types `T0..=Tn` must be a local type. Let `Ti` be the first such type. +/// - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`) pub fn check_orphan_rules<'db>(db: &'db dyn HirDatabase, impl_: ImplId) -> bool { let Some(impl_trait) = db.impl_trait(impl_) else { // not a trait impl @@ -277,10 +277,10 @@ pub fn check_orphan_rules<'db>(db: &'db dyn HirDatabase, impl_: ImplId) -> bool } } }; - // - At least one of the types `T0..=Tn`` must be a local type. Let `Ti`` be the first such type. + // - At least one of the types `T0..=Tn` must be a local type. Let `Ti` be the first such type. // FIXME: param coverage - // - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti`` (excluding `Ti`) + // - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`) let is_not_orphan = trait_ref.args.types().any(|ty| match unwrap_fundamental(ty).kind() { TyKind::Adt(adt_def, _) => is_local(adt_def.def_id().module(db).krate(db)), TyKind::Error(_) => true, diff --git a/src/tools/rust-analyzer/crates/mbe/src/parser.rs b/src/tools/rust-analyzer/crates/mbe/src/parser.rs index 796ee62d48e3a..9fbd06cf88626 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/parser.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/parser.rs @@ -109,7 +109,7 @@ pub(crate) enum Op { }, Count { name: Symbol, - // FIXME: `usize`` once we drop support for 1.76 + // FIXME: `usize` once we drop support for 1.76 depth: Option, }, Concat { diff --git a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs index 29a19bc32e453..675533645d0db 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs @@ -748,7 +748,7 @@ impl ProjectWorkspace { .packages() .filter_map(|pkg| { if ws[pkg].is_local { - // the local ones are included in the main `PackageRoot`` below + // the local ones are included in the main `PackageRoot` below return None; } let pkg_root = ws[pkg].manifest.parent().to_path_buf(); diff --git a/tests/ui/async-await/async-closures/dont-ice-when-body-tainted-by-errors.rs b/tests/ui/async-await/async-closures/dont-ice-when-body-tainted-by-errors.rs index f90d10ebe854b..1bbff34292c39 100644 --- a/tests/ui/async-await/async-closures/dont-ice-when-body-tainted-by-errors.rs +++ b/tests/ui/async-await/async-closures/dont-ice-when-body-tainted-by-errors.rs @@ -11,7 +11,7 @@ pub fn main() { // Type error here taints the environment. This causes us to fallback all // variables to `Error`. This means that when we compute the upvars for the // *outer* coroutine-closure, we don't actually see any upvars since `MemCategorization` - // and `ExprUseVisitor`` will bail early when it sees error. This means + // and `ExprUseVisitor` will bail early when it sees error. This means // that our underlying assumption that the parent and child captures are // compatible ends up being broken, previously leading to an ICE. trait_error::<()>(); diff --git a/tests/ui/parser/const-block-items/pub.rs b/tests/ui/parser/const-block-items/pub.rs index b76d30d9bda18..4bff11a5a5ad6 100644 --- a/tests/ui/parser/const-block-items/pub.rs +++ b/tests/ui/parser/const-block-items/pub.rs @@ -2,7 +2,7 @@ //@ check-pass -// FIXME(const_block_items): `pub`` is useless here +// FIXME(const_block_items): `pub` is useless here pub const { assert!(true); } diff --git a/tests/ui/parser/raw/raw-idents.rs b/tests/ui/parser/raw/raw-idents.rs index 4e1e6b124c311..fd0a4c7522a09 100644 --- a/tests/ui/parser/raw/raw-idents.rs +++ b/tests/ui/parser/raw/raw-idents.rs @@ -6,7 +6,7 @@ //@[e2024] edition:2024 // Ensure that all (usable as identifier) keywords work as raw identifiers in all positions. -// This was motivated by issue #137128, where `r#move`/`r#static`` did not work as `const` names +// This was motivated by issue #137128, where `r#move`/`r#static` did not work as `const` names // due to a parser check not acounting for raw identifiers. #![crate_type = "lib"] diff --git a/tests/ui/traits/next-solver/normalize/indirectly-constrained-term.rs b/tests/ui/traits/next-solver/normalize/indirectly-constrained-term.rs index 380477c2c3c67..55fb751d26973 100644 --- a/tests/ui/traits/next-solver/normalize/indirectly-constrained-term.rs +++ b/tests/ui/traits/next-solver/normalize/indirectly-constrained-term.rs @@ -17,7 +17,7 @@ // We prove `Projection( as Unconstrained>::Assoc, ())`. This normalizes // ` as Unconstrained>::Assoc` to `?1` and eagerly computes the nested // goals `[Projection(::Assoc, ?1), Trait(?1: NoImpl)]`. -// These goals are both ambiguous. `NormalizesTo`` then returns `?1` as the +// These goals are both ambiguous. `NormalizesTo` then returns `?1` as the // normalized-to type. It discards the nested goals, forcing the certainty of // the normalization to `Maybe`. Unifying `?1` with `()` succeeds¹. However, // this is never propagated to the `?1: NoImpl` goal, as it only exists inside From 5cd51c0edd2118b8799f6c8656e3753afd411e2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sat, 16 May 2026 00:33:43 +0000 Subject: [PATCH 3/3] Place comment in the right place --- compiler/rustc_borrowck/src/lib.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 107ca87376015..e80969cd0cbb2 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -2239,14 +2239,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { // None case => assigning to `x` does not require `x` be initialized. for (place_base, elem) in place.iter_projections().rev() { match elem { - ProjectionElem::Index(_/*operand*/) | - ProjectionElem::OpaqueCast(_) | - ProjectionElem::ConstantIndex { .. } | + ProjectionElem::Index(_/*operand*/) + | ProjectionElem::OpaqueCast(_) // assigning to P[i] requires P to be valid. - ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => - // assigning to (P->variant) is okay if assigning to `P` is okay - // - // FIXME: is this true even if P is an adt with a dtor? + | ProjectionElem::ConstantIndex { .. } + // assigning to (P->variant) is okay if assigning to `P` is okay + // + // FIXME: is this true even if P is an adt with a dtor? + | ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => {} ProjectionElem::UnwrapUnsafeBinder(_) => {