From 6215bb9c6ec2d7454d0f378fd0ca0b7ef8efbbb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 12 Dec 2025 22:07:23 +0000 Subject: [PATCH] Replace some `matches!` with `if let` or `==` --- compiler/rustc_ast/src/ast.rs | 2 +- .../rustc_ast/src/expand/autodiff_attrs.rs | 2 +- compiler/rustc_attr_parsing/src/parser.rs | 2 +- compiler/rustc_attr_parsing/src/safety.rs | 2 +- .../rustc_borrowck/src/borrowck_errors.rs | 2 +- .../src/diagnostics/conflict_errors.rs | 36 +++++++++---------- .../src/diagnostics/region_errors.rs | 2 +- .../rustc_borrowck/src/handle_placeholders.rs | 2 +- compiler/rustc_borrowck/src/lib.rs | 2 +- compiler/rustc_borrowck/src/path_utils.rs | 2 +- compiler/rustc_borrowck/src/renumber.rs | 2 +- .../src/type_check/free_region_relations.rs | 2 +- .../src/check_consts/check.rs | 7 ++-- .../src/check_consts/qualifs.rs | 2 +- .../rustc_const_eval/src/interpret/call.rs | 2 +- .../src/interpret/intrinsics.rs | 2 +- .../rustc_const_eval/src/interpret/memory.rs | 8 ++--- .../rustc_const_eval/src/interpret/operand.rs | 4 +-- .../src/interpret/validity.rs | 10 +++--- compiler/rustc_errors/src/emitter.rs | 4 +-- compiler/rustc_errors/src/json.rs | 2 +- compiler/rustc_errors/src/lib.rs | 2 +- .../rustc_hir_analysis/src/check/check.rs | 6 ++-- .../rustc_hir_analysis/src/check/wfcheck.rs | 4 +-- .../src/coherence/orphan.rs | 2 +- .../src/collect/generics_of.rs | 2 +- .../src/collect/predicates_of.rs | 2 +- .../rustc_hir_analysis/src/variance/mod.rs | 2 +- compiler/rustc_hir_typeck/src/coercion.rs | 6 ++-- compiler/rustc_hir_typeck/src/demand.rs | 19 ++++------ .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 2 +- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 2 +- compiler/rustc_hir_typeck/src/loops.rs | 8 ++--- .../src/method/prelude_edition_lints.rs | 4 +-- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- .../rustc_hir_typeck/src/method/suggest.rs | 6 ++-- compiler/rustc_hir_typeck/src/pat.rs | 4 +-- compiler/rustc_hir_typeck/src/place_op.rs | 2 +- .../src/infer/outlives/test_type_match.rs | 2 +- .../src/early/diagnostics/check_cfg.rs | 4 ++- compiler/rustc_lint/src/lifetime_syntax.rs | 2 +- compiler/rustc_middle/src/hir/map.rs | 2 +- compiler/rustc_middle/src/lint.rs | 2 +- compiler/rustc_middle/src/middle/stability.rs | 2 +- compiler/rustc_middle/src/mir/pretty.rs | 7 ++-- compiler/rustc_middle/src/mir/statement.rs | 2 +- compiler/rustc_middle/src/thir.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 16 ++++----- compiler/rustc_middle/src/ty/diagnostics.rs | 2 +- .../ty/inhabitedness/inhabited_predicate.rs | 4 +-- .../rustc_middle/src/ty/inhabitedness/mod.rs | 2 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/trait_def.rs | 2 +- .../src/known_panics_lint.rs | 4 +-- compiler/rustc_monomorphize/src/collector.rs | 4 +-- .../src/solve/trait_goals.rs | 4 +-- compiler/rustc_parse/src/parser/asm.rs | 7 ++-- .../rustc_parse/src/parser/attr_wrapper.rs | 4 +-- .../rustc_parse/src/parser/diagnostics.rs | 6 ++-- compiler/rustc_parse/src/parser/expr.rs | 13 ++++--- compiler/rustc_parse/src/parser/item.rs | 6 ++-- compiler/rustc_parse/src/parser/mod.rs | 13 +++---- compiler/rustc_parse/src/parser/pat.rs | 4 +-- compiler/rustc_parse/src/parser/path.rs | 4 +-- compiler/rustc_parse/src/parser/stmt.rs | 4 ++- compiler/rustc_parse/src/parser/ty.rs | 4 +-- compiler/rustc_passes/src/check_attr.rs | 12 +++---- compiler/rustc_passes/src/dead.rs | 2 +- compiler/rustc_pattern_analysis/src/rustc.rs | 6 ++-- compiler/rustc_resolve/src/ident.rs | 8 ++--- .../rustc_resolve/src/late/diagnostics.rs | 8 ++--- compiler/rustc_target/src/target_features.rs | 2 +- .../src/error_reporting/infer/mod.rs | 2 +- .../error_reporting/infer/need_type_info.rs | 18 +++++----- .../src/error_reporting/traits/ambiguity.rs | 7 ++-- .../traits/on_unimplemented.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 15 ++++---- .../src/traits/effects.rs | 2 +- .../src/traits/select/mod.rs | 6 ++-- .../rustc_trait_selection/src/traits/util.rs | 2 +- compiler/rustc_type_ir/src/ty_kind/closure.rs | 3 +- src/librustdoc/clean/cfg.rs | 6 ++-- 82 files changed, 200 insertions(+), 205 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index e348cc1ab2810..4ccea02a98615 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -752,7 +752,7 @@ impl Pat { pub fn contains_never_pattern(&self) -> bool { let mut contains_never_pattern = false; self.walk(&mut |pat| { - if matches!(pat.kind, PatKind::Never) { + if let PatKind::Never = pat.kind { contains_never_pattern = true; } true diff --git a/compiler/rustc_ast/src/expand/autodiff_attrs.rs b/compiler/rustc_ast/src/expand/autodiff_attrs.rs index 90f15753e99c9..0a372f801312f 100644 --- a/compiler/rustc_ast/src/expand/autodiff_attrs.rs +++ b/compiler/rustc_ast/src/expand/autodiff_attrs.rs @@ -173,7 +173,7 @@ pub fn valid_ty_for_activity(ty: &Box, activity: DiffActivity) -> bool { } // FIXME(ZuseZ4) We should make this more robust to also // handle type aliases. Once that is done, we can be more restrictive here. - if matches!(activity, Active | ActiveOnly) { + if let Active | ActiveOnly = activity { return true; } matches!(ty.kind, TyKind::Ptr(_) | TyKind::Ref(..)) diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 09ecfaedb5ed2..0dcf7523aa77e 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -354,7 +354,7 @@ fn expr_to_lit( } } } else { - if matches!(should_emit, ShouldEmit::Nothing) { + if let ShouldEmit::Nothing = should_emit { return None; } diff --git a/compiler/rustc_attr_parsing/src/safety.rs b/compiler/rustc_attr_parsing/src/safety.rs index 817785108a1ed..345d757762cba 100644 --- a/compiler/rustc_attr_parsing/src/safety.rs +++ b/compiler/rustc_attr_parsing/src/safety.rs @@ -18,7 +18,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { emit_lint: &mut impl FnMut(AttributeLint), target_id: S::Id, ) { - if matches!(self.stage.should_emit(), ShouldEmit::Nothing) { + if let ShouldEmit::Nothing = self.stage.should_emit() { return; } diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index 7c9011505d64c..330e09cdb8422 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -395,7 +395,7 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> { format!("within this {coroutine_kind:#}"), ); diag.span_label(yield_span, "possible yield occurs here"); - if matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_)) { + if let hir::CoroutineKind::Coroutine(_) = coroutine_kind { let hir::Closure { capture_clause, fn_decl_span, .. } = self .infcx .tcx diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 2999d1f2926cc..02983cb940df1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1440,7 +1440,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } inner_expr = inner; if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) { - if matches!(inner_type.kind(), ty::RawPtr(..)) { + if let ty::RawPtr(..) = inner_type.kind() { is_raw_ptr = true; break; } @@ -2063,10 +2063,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { debug!("not later used in call"); return; } - if matches!( - self.body.local_decls[issued_borrow.borrowed_place.local].local_info(), - LocalInfo::IfThenRescopeTemp { .. } - ) { + if let LocalInfo::IfThenRescopeTemp { .. } = + self.body.local_decls[issued_borrow.borrowed_place.local].local_info() + { // A better suggestion will be issued by the `if_let_rescope` lint return; } @@ -3325,7 +3324,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); } - let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) { + let mutability = if let BorrowKind::Mut { .. } = borrow.kind() { "mut " } else { "" @@ -3559,10 +3558,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } ConstraintCategory::CallArgument(_) => { fr_name.highlight_region_name(&mut err); - if matches!( - use_span.coroutine_kind(), - Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) - ) { + if let Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) = + use_span.coroutine_kind() + { err.note( "async blocks are not executed immediately and must either take a \ reference or ownership of outside variables they use", @@ -4622,10 +4620,11 @@ impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> { ), )); } else if let Some(guard) = &arm.guard { - if matches!( - self.tcx.hir_node(arm.body.hir_id), - hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) - ) { + if let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::Ret(_), + .. + }) = self.tcx.hir_node(arm.body.hir_id) + { continue; } self.errors.push(( @@ -4637,10 +4636,11 @@ impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> { ), )); } else { - if matches!( - self.tcx.hir_node(arm.body.hir_id), - hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) - ) { + if let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::Ret(_), + .. + }) = self.tcx.hir_node(arm.body.hir_id) + { continue; } self.errors.push(( diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index f4bbdabf7f216..eb3c4fc241416 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -787,7 +787,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap(); outlived_fr_name.highlight_region_name(&mut diag); - let err_category = if matches!(category, ConstraintCategory::Return(_)) + let err_category = if let ConstraintCategory::Return(_) = category && self.regioncx.universal_regions().is_local_free_region(*outlived_fr) { LifetimeReturnCategoryErr::WrongReturn { diff --git a/compiler/rustc_borrowck/src/handle_placeholders.rs b/compiler/rustc_borrowck/src/handle_placeholders.rs index 60be521c29af0..f679e1eeae297 100644 --- a/compiler/rustc_borrowck/src/handle_placeholders.rs +++ b/compiler/rustc_borrowck/src/handle_placeholders.rs @@ -134,7 +134,7 @@ pub(crate) struct RegionTracker { impl RegionTracker { pub(crate) fn new(rvid: RegionVid, definition: &RegionDefinition<'_>) -> Self { let reachable_placeholders = - if matches!(definition.origin, NllRegionVariableOrigin::Placeholder(_)) { + if let NllRegionVariableOrigin::Placeholder(_) = definition.origin { PlaceholderReachability::Placeholders { max_universe: (definition.universe, rvid), min_placeholder: rvid, diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 8d61ffde116c5..3ebed392f444f 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -1404,7 +1404,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { self.borrow_set, |borrow_index| borrows_in_scope.contains(borrow_index), |this, _borrow_index, borrow| { - if matches!(borrow.kind, BorrowKind::Fake(_)) { + if let BorrowKind::Fake(_) = borrow.kind { return ControlFlow::Continue(()); } let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span(); diff --git a/compiler/rustc_borrowck/src/path_utils.rs b/compiler/rustc_borrowck/src/path_utils.rs index 2c94a32d369ce..fe4e5bc7e0428 100644 --- a/compiler/rustc_borrowck/src/path_utils.rs +++ b/compiler/rustc_borrowck/src/path_utils.rs @@ -50,7 +50,7 @@ pub(super) fn each_borrow_involving_path<'tcx, F, I, S>( i, borrowed, place, access ); let ctrl = op(s, i, borrowed); - if matches!(ctrl, ControlFlow::Break(_)) { + if let ControlFlow::Break(_) = ctrl { return; } } diff --git a/compiler/rustc_borrowck/src/renumber.rs b/compiler/rustc_borrowck/src/renumber.rs index d6dbc7dd831fb..4dd7b2bcbcabe 100644 --- a/compiler/rustc_borrowck/src/renumber.rs +++ b/compiler/rustc_borrowck/src/renumber.rs @@ -80,7 +80,7 @@ impl<'a, 'tcx> MutVisitor<'tcx> for RegionRenumberer<'a, 'tcx> { #[instrument(skip(self), level = "debug")] fn visit_ty(&mut self, ty: &mut Ty<'tcx>, ty_context: TyContext) { - if matches!(ty_context, TyContext::ReturnTy(_)) { + if let TyContext::ReturnTy(_) = ty_context { // We will renumber the return ty when called again with `TyContext::LocalDecl` return; } diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index d27a73535bab0..ee14387b72b05 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -295,7 +295,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> { } // Add implied bounds from impl header. - if matches!(tcx.def_kind(defining_ty_def_id), DefKind::AssocFn | DefKind::AssocConst) { + if let DefKind::AssocFn | DefKind::AssocConst = tcx.def_kind(defining_ty_def_id) { for &(ty, _) in tcx.assumed_wf_types(tcx.local_parent(defining_ty_def_id)) { let result: Result<_, ErrorGuaranteed> = param_env .and(DeeplyNormalize { value: ty }) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 78e4066ca910a..1e4314eb8c355 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -251,7 +251,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { let mut transient = DenseBitSet::new_filled(ccx.body.local_decls.len()); // Make sure to only visit reachable blocks, the dataflow engine can ICE otherwise. for (bb, data) in traversal::reachable(&ccx.body) { - if matches!(data.terminator().kind, TerminatorKind::Return) { + if data.terminator().kind == TerminatorKind::Return { let location = ccx.body.terminator_loc(bb); maybe_storage_live.seek_after_primary_effect(location); // If a local may be live here, it is definitely not transient. @@ -835,8 +835,9 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // const-eval of `panic_display` assumes the argument is `&&str` if tcx.is_lang_item(callee, LangItem::PanicDisplay) { match args[0].node.ty(&self.ccx.body.local_decls, tcx).kind() { - ty::Ref(_, ty, _) if matches!(ty.kind(), ty::Ref(_, ty, _) if ty.is_str()) => - {} + ty::Ref(_, ty, _) + if let ty::Ref(_, ty, _) = ty.kind() + && ty.is_str() => {} _ => { self.check_op(ops::PanicNonStr); } diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index f50c6af53bf13..1a80fb24b9044 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -314,7 +314,7 @@ where // i.e., we treat all qualifs as non-structural for deref projections. Generally, // we can say very little about `*ptr` even if we know that `ptr` satisfies all // sorts of properties. - if matches!(elem, ProjectionElem::Deref) { + if elem == ProjectionElem::Deref { // We have to assume that this qualifies. return true; } diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 312ebe7ddd09d..94c6fd1b32387 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -283,7 +283,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { 'tcx: 'y, { assert_eq!(callee_ty, callee_abi.layout.ty); - if matches!(callee_abi.mode, PassMode::Ignore) { + if callee_abi.mode == PassMode::Ignore { // This one is skipped. Still must be made live though! if !already_live { self.storage_live(callee_arg.as_local().unwrap())?; diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index a7a3bbebed5f1..4d10db6bb27c7 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -815,7 +815,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } else { // unsigned - if matches!(mir_op, BinOp::Add) { + if mir_op == BinOp::Add { // max unsigned Scalar::from_uint(size.unsigned_int_max(), size) } else { diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index bac3a9da48d99..862fe47790808 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -327,7 +327,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { return Err(ConstEvalErrKind::ConstMakeGlobalWithOffset(ptr)).into(); } - if matches!(self.tcx.try_get_global_alloc(alloc_id), Some(_)) { + if self.tcx.try_get_global_alloc(alloc_id).is_some() { // This points to something outside the current interpreter. return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into(); } @@ -981,7 +981,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { msg: CheckInAllocMsg, ) -> InterpResult<'tcx, (Size, Align)> { let info = self.get_alloc_info(id); - if matches!(info.kind, AllocKind::Dead) { + if info.kind == AllocKind::Dead { throw_ub!(PointerUseAfterFree(id, msg)) } interp_ok((info.size, info.align)) @@ -1072,7 +1072,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Recurse, if there is data here. // Do this *before* invoking the callback, as the callback might mutate the // allocation and e.g. replace all provenance by wildcards! - if matches!(info.kind, AllocKind::LiveData) { + if info.kind == AllocKind::LiveData { let alloc = self.get_alloc_raw(id)?; for prov in alloc.provenance().provenances() { if let Some(id) = prov.get_alloc_id() { @@ -1605,7 +1605,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { match self.ptr_try_get_alloc_id(ptr, 0) { Ok((alloc_id, offset, _)) => { let info = self.get_alloc_info(alloc_id); - if matches!(info.kind, AllocKind::TypeId) { + if info.kind == AllocKind::TypeId { // We *could* actually precisely answer this question since here, // the offset *is* the integer value. But the entire point of making // this a pointer is not to leak the integer value, so we say everything diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index d3d119c8fc9c9..321ed97163ea5 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -679,7 +679,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { span_bug!(self.cur_span(), "primitive read not possible for type: {}", op.layout().ty); } let imm = self.read_immediate_raw(op)?.right().unwrap(); - if matches!(*imm, Immediate::Uninit) { + if let Immediate::Uninit = *imm { throw_ub!(InvalidUninitBytes(None)); } interp_ok(imm) @@ -748,7 +748,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { let layout = self.layout_of_local(frame, local, layout)?; let op = *frame.locals[local].access()?; - if matches!(op, Operand::Immediate(_)) { + if let Operand::Immediate(_) = op { assert!(!layout.is_unsized()); } M::after_local_read(self, frame, local)?; diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 34296b6d8de34..9fec2f922429a 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -422,10 +422,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // Reset provenance: ensure slice tail metadata does not preserve provenance, // and ensure all pointers do not preserve partial provenance. if self.reset_provenance_and_padding { - if matches!(imm.layout.backend_repr, BackendRepr::Scalar(..)) { + if let BackendRepr::Scalar(..) = imm.layout.backend_repr { // A thin pointer. If it has provenance, we don't have to do anything. // If it does not, ensure we clear the provenance in memory. - if matches!(imm.to_scalar(), Scalar::Int(..)) { + if let Scalar::Int(..) = imm.to_scalar() { self.ecx.clear_provenance(val)?; } } else { @@ -651,7 +651,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // and then puts the value in there, so briefly we have a box with uninit contents. // FIXME: should we also skip `UnsafeCell` behind shared references? Currently that is not // needed since validation reads bypass Stacked Borrows and data race checks. - if matches!(ptr_kind, PointerKind::Box) { + if let PointerKind::Box = ptr_kind { return interp_ok(()); } } @@ -714,7 +714,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // types below! self.read_scalar( value, - if matches!(ty.kind(), ty::Float(..)) { + if let ty::Float(..) = ty.kind() { ExpectedKind::Float } else { ExpectedKind::Int @@ -762,7 +762,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if self.reset_provenance_and_padding { // Make sure we do not preserve partial provenance. This matches the thin // pointer handling in `deref_pointer`. - if matches!(scalar, Scalar::Int(..)) { + if let Scalar::Int(..) = scalar { self.ecx.clear_provenance(value)?; } self.add_data_range_place(value); diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 78feb60261bd8..02699701ced5b 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -2534,7 +2534,7 @@ impl HumanEmitter { { // We'll continue the vertical bar to point into the next note. self.draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1); - } else if matches!(code_window_status, CodeWindowStatus::Open) { + } else if let CodeWindowStatus::Open = code_window_status { // We'll close the vertical bar to visually end the code window. self.draw_col_separator_end(&mut buffer, 0, max_line_num_len + 1); } @@ -3482,7 +3482,7 @@ pub fn stderr_destination(color: ColorConfig) -> Destination { pub fn get_stderr_color_choice(color: ColorConfig, stderr: &std::io::Stderr) -> ColorChoice { let choice = color.to_color_choice(); - if matches!(choice, ColorChoice::Auto) { AutoStream::choice(stderr) } else { choice } + if let ColorChoice::Auto = choice { AutoStream::choice(stderr) } else { choice } } /// On Windows, BRIGHT_BLUE is hard to read on black. Use cyan instead. diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index ce5c830bbfcd6..b488a7f60a54a 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -148,7 +148,7 @@ impl Emitter for JsonEmitter { // // So to avoid ICEs and confused users we "upgrade" the lint level for // those `FutureBreakageItem` to warn. - if matches!(diag.level, crate::Level::Allow | crate::Level::Expect) { + if let crate::Level::Allow | crate::Level::Expect = diag.level { diag.level = crate::Level::Warning; } FutureBreakageItem { diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 148368045f4f5..4020a730949b3 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1658,7 +1658,7 @@ impl DiagCtxtInner { if is_error { self.deduplicated_err_count += 1; - } else if matches!(diagnostic.level, ForceWarning | Warning) { + } else if let ForceWarning | Warning = diagnostic.level { self.deduplicated_warn_count += 1; } self.has_printed = true; diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index beba0165549e0..90f273b15285e 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -184,8 +184,8 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) { Ok(l) => l, // Foreign statics that overflow their allowed size should emit an error Err(LayoutError::SizeOverflow(_)) - if matches!(tcx.def_kind(def_id), DefKind::Static{ .. } - if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) => + if let DefKind::Static { .. } = tcx.def_kind(def_id) + && tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod => { tcx.dcx().emit_err(errors::TooLargeStatic { span }); return; @@ -673,7 +673,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe } } ty::GenericParamDefKind::Type { .. } => { - if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) { + if let DefKind::Trait | DefKind::TraitAlias = tcx.def_kind(param.def_id) { // FIXME(precise_capturing): Structured suggestion for this would be useful tcx.dcx().emit_err(errors::SelfTyNotCaptured { trait_span: tcx.def_span(param.def_id), diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 0a6be9aa4b2fc..eefb4586d50dc 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -326,7 +326,7 @@ pub(crate) fn check_trait_item<'tcx>( let mut res = Ok(()); - if matches!(tcx.def_kind(def_id), DefKind::AssocFn) { + if tcx.def_kind(def_id) == DefKind::AssocFn { for &assoc_ty_def_id in tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id()) { @@ -2330,7 +2330,7 @@ fn lint_redundant_lifetimes<'tcx>( ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()), ); // If we are in a function, add its late-bound lifetimes too. - if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) { + if let DefKind::Fn | DefKind::AssocFn = def_kind { for (idx, var) in tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate() { diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index f1e138dbcb97a..5fea39710b1b8 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -392,7 +392,7 @@ fn emit_orphan_check_error<'tcx>( }); for &(mut ty, is_target_ty) in &tys { - let span = if matches!(is_target_ty, IsFirstInputType::Yes) { + let span = if let IsFirstInputType::Yes = is_target_ty { // Point at `D` in `impl for C in D` impl_.self_ty.span } else { diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 3d2f0466cad08..ed8f661602ad2 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -158,7 +158,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // Field defaults are allowed to use generic parameters, e.g. `field: u32 = /*defid: N + 1*/` ty::AnonConstKind::NonTypeSystem - if matches!(tcx.parent_hir_node(hir_id), Node::TyPat(_) | Node::Field(_)) => + if let Node::TyPat(_) | Node::Field(_) = tcx.parent_hir_node(hir_id) => { Some(parent_did) } diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 2eefe1eb3e922..178c47b09c84d 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -543,7 +543,7 @@ pub(super) fn explicit_predicates_of<'tcx>( } } } else { - if matches!(def_kind, DefKind::AnonConst) + if def_kind == DefKind::AnonConst && tcx.features().generic_const_exprs() && let Some(defaulted_param_def_id) = tcx.hir_opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id)) diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index 0666b335e093b..9fc184c61bd47 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -163,7 +163,7 @@ fn variance_of_opaque( generics = tcx.generics_of(def_id); // Don't mark trait params generic if we're in an RPITIT. - if matches!(force_capture_trait_args, ForceCaptureTraitArgs::Yes) + if let ForceCaptureTraitArgs::Yes = force_capture_trait_args && generics.parent.is_none() { debug_assert_eq!(tcx.def_kind(def_id), DefKind::Trait); diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 127965cb4b301..44b8b426a7ed7 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -182,7 +182,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // In order to actually ensure that equating the binders *does* // result in equal binders, and that the lhs is actually a supertype // of the rhs, we must perform a leak check here. - if matches!(leak_check, ForceLeakCheck::Yes) { + if let ForceLeakCheck::Yes = leak_check { self.leak_check(outer_universe, Some(snapshot))?; } @@ -1101,7 +1101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let fn_attrs = tcx.codegen_fn_attrs(def_id); - if matches!(fn_attrs.inline, InlineAttr::Force { .. }) { + if let InlineAttr::Force { .. } = fn_attrs.inline { return Err(TypeError::ForceInlineCast); } @@ -1111,7 +1111,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // needed to call the coercee safely. match tcx.adjust_target_feature_sig(def_id, sig, self.body_id.into()) { Some(adjusted_sig) => adjusted_sig, - None if matches!(expected_safety, Some(hir::Safety::Safe)) => { + None if let Some(hir::Safety::Safe) = expected_safety => { return Err(TypeError::TargetFeatureCast(def_id)); } None => sig, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index f1e74028f4ce7..9ab1562c055ba 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -91,7 +91,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // FIXME(#73154): For now, we do leak check when coercing function // pointers in typeck, instead of only during borrowck. This can lead // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful. - if matches!(error, Some(TypeError::RegionsInsufficientlyPolymorphic(..))) { + if let Some(TypeError::RegionsInsufficientlyPolymorphic(..)) = error { return; } @@ -531,7 +531,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // of our inference guesses in `emit_type_mismatch_suggestions`, so // only suggest things when we know our type error is precisely due to // a type mismatch, and not via some projection or something. See #116155. - if matches!(source, TypeMismatchSource::Ty(_)) + if let TypeMismatchSource::Ty(_) = source && let Some(ideal_method) = ideal_method && Some(ideal_method.def_id) == self @@ -1214,13 +1214,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } let fn_sig = fn_ty.fn_sig(self.tcx).skip_binder(); - let Some(&arg) = fn_sig - .inputs() - .get(arg_idx + if matches!(kind, CallableKind::Method) { 1 } else { 0 }) + let Some(&arg) = + fn_sig.inputs().get(arg_idx + if let CallableKind::Method = kind { 1 } else { 0 }) else { return; }; - if matches!(arg.kind(), ty::Param(_)) + if let ty::Param(_) = arg.kind() && fn_sig.output().contains(arg) && self.node_ty(args[arg_idx].hir_id) == checked_ty { @@ -1229,11 +1228,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args[arg_idx].span, format!( "this argument influences the {} of `{}`", - if matches!(kind, CallableKind::Constructor) { - "type" - } else { - "return type" - }, + if let CallableKind::Constructor = kind { "type" } else { "return type" }, callable ), ); @@ -1259,7 +1254,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir::def::Res::Def(kind, def_id) = path.res else { return; }; - let callable_kind = if matches!(kind, hir::def::DefKind::Ctor(_, _)) { + let callable_kind = if let hir::def::DefKind::Ctor(_, _) = kind { CallableKind::Constructor } else { CallableKind::Function diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index da719e615fd70..ff85f53ddf309 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -216,7 +216,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Don't write user type annotations for const param types, since we give them // identity args just so that we can trivially substitute their `EarlyBinder`. // We enforce that they match their type in MIR later on. - if matches!(self.tcx.def_kind(def_id), DefKind::ConstParam) { + if self.tcx.def_kind(def_id) == DefKind::ConstParam { return; } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index 854202c312705..728c0f613a4a9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -439,7 +439,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // the args list does not, then we should chop off all of the lifetimes, // since they're all elided. let segment_args = segment.args().args; - if matches!(own_args[0].kind(), ty::GenericArgKind::Lifetime(_)) + if let ty::GenericArgKind::Lifetime(_) = own_args[0].kind() && segment_args.first().is_some_and(|arg| arg.is_ty_or_const()) && let Some(offset) = own_args.iter().position(|arg| { matches!(arg.kind(), ty::GenericArgKind::Type(_) | ty::GenericArgKind::Const(_)) diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index 799e82ec13b80..709eec2e0e5e2 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -169,17 +169,15 @@ impl<'hir> Visitor<'hir> for CheckLoopVisitor<'hir> { self.with_context(LabeledBlock, |v| v.visit_block(b)); } hir::ExprKind::Block(b, None) - if matches!(self.cx_stack.last(), Some(&Fn) | Some(&ConstBlock)) => + if let Some(Fn) | Some(ConstBlock) = self.cx_stack.last() => { self.with_context(Normal, |v| v.visit_block(b)); } hir::ExprKind::Block( b @ hir::Block { rules: hir::BlockCheckMode::DefaultBlock, .. }, None, - ) if matches!( - self.cx_stack.last(), - Some(&Normal) | Some(&AnonConst) | Some(&UnlabeledBlock(_)) - ) => + ) if let Some(Normal) | Some(AnonConst) | Some(UnlabeledBlock(_)) = + self.cx_stack.last() => { self.with_context(UnlabeledBlock(b.span.shrink_to_lo()), |v| v.visit_block(b)); } diff --git a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs index 38413cca633c9..0d003942de3e4 100644 --- a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs +++ b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs @@ -81,7 +81,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } - if matches!(pick.kind, probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick) { + if let probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick = pick.kind { // avoid repeatedly adding unneeded `&*`s if pick.autoderefs == 1 && matches!( @@ -274,7 +274,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // No need to lint if this is an inherent method called on a specific type, like `Vec::foo(...)`, // since such methods take precedence over trait methods. - if matches!(pick.kind, probe::PickKind::InherentImplPick) { + if let probe::PickKind::InherentImplPick = pick.kind { return; } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 1a25f6a582f22..ed793cdf01c76 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -2042,7 +2042,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { (xform_self_ty, xform_ret_ty) = self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args); - if matches!(probe.kind, WhereClauseCandidate(_)) { + if let WhereClauseCandidate(_) = probe.kind { // `WhereClauseCandidate` requires that the self type is a param, // because it has special behavior with candidate preference as an // inherent pick. diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 4b9ad345210dd..9de6cdfcf8835 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -816,7 +816,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Report to emit the diagnostic return Err(()); } else if !unsatisfied_predicates.is_empty() { - if matches!(rcvr_ty.kind(), ty::Param(_)) { + if let ty::Param(_) = rcvr_ty.kind() { // We special case the situation where we are looking for `_` in // `::method` because otherwise the machinery will look for blanket // implementations that have unsatisfied trait bounds to suggest, leading us to claim @@ -3580,7 +3580,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(within_macro_span, "due to this macro variable"); } - if matches!(source, SelfSource::QPath(_)) && args.is_some() { + if let SelfSource::QPath(_) = source + && args.is_some() + { self.find_builder_fn(err, rcvr_ty, expr_id); } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 06fd89837d516..7e8f7e6ae3d0e 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -486,7 +486,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pat_info: PatInfo<'tcx>, ) -> Ty<'tcx> { #[cfg(debug_assertions)] - if matches!(pat_info.binding_mode, ByRef::Yes(_, Mutability::Mut)) + if let ByRef::Yes(_, Mutability::Mut) = pat_info.binding_mode && pat_info.max_ref_mutbl != MutblCap::Mut && self.downgrade_mut_inside_shared() { @@ -1235,7 +1235,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) } - if matches!(bm.0, ByRef::Yes(_, Mutability::Mut)) + if let ByRef::Yes(_, Mutability::Mut) = bm.0 && let MutblCap::WeaklyNot(and_pat_span) = pat_info.max_ref_mutbl { let mut err = struct_span_code_err!( diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index a48db2cc855c0..1b43cd59ddfbe 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -281,7 +281,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("convert_place_derefs_to_mutable: i={} expr={:?}", i, expr); let mut source = self.node_ty(expr.hir_id); - if matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Deref, _)) { + if let hir::ExprKind::Unary(hir::UnOp::Deref, _) = expr.kind { // Clear previous flag; after a pointer indirection it does not apply any more. inside_union = false; } diff --git a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs index 7be5daf610565..7bd97ea21dde0 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -190,7 +190,7 @@ impl<'tcx> TypeRelation> for MatchAgainstHigherRankedOutlives<'tcx> #[instrument(skip(self), level = "trace")] fn tys(&mut self, pattern: Ty<'tcx>, value: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { // FIXME(non_lifetime_binders): What to do here? - if matches!(pattern.kind(), ty::Error(_) | ty::Bound(..)) { + if let ty::Error(_) | ty::Bound(..) = pattern.kind() { // Unlike normal `TypeRelation` rules, `ty::Error` does not equal any type. self.no_match() } else if pattern == value { diff --git a/compiler/rustc_lint/src/early/diagnostics/check_cfg.rs b/compiler/rustc_lint/src/early/diagnostics/check_cfg.rs index 0c8d7523a9dc5..d00852e28489e 100644 --- a/compiler/rustc_lint/src/early/diagnostics/check_cfg.rs +++ b/compiler/rustc_lint/src/early/diagnostics/check_cfg.rs @@ -70,7 +70,9 @@ fn cargo_help_sub( // `build_script_build`) to try to figure out if we are building a Cargo build script let unescaped = &inst(EscapeQuotes::No); - if matches!(&sess.opts.crate_name, Some(crate_name) if crate_name == "build_script_build") { + if let Some(crate_name) = &sess.opts.crate_name + && crate_name == "build_script_build" + { lints::UnexpectedCfgCargoHelp::lint_cfg(unescaped) } else { lints::UnexpectedCfgCargoHelp::lint_cfg_and_build_rs(unescaped, &inst(EscapeQuotes::Yes)) diff --git a/compiler/rustc_lint/src/lifetime_syntax.rs b/compiler/rustc_lint/src/lifetime_syntax.rs index 0cac91c234080..44e3f1dcf5931 100644 --- a/compiler/rustc_lint/src/lifetime_syntax.rs +++ b/compiler/rustc_lint/src/lifetime_syntax.rs @@ -358,7 +358,7 @@ fn emit_mismatch_diagnostic<'tcx>( } } - if matches!(lifetime.source, Path { .. } | OutlivesBound | PreciseCapturing) { + if let Path { .. } | OutlivesBound | PreciseCapturing = lifetime.source { allow_suggesting_implicit = false; } diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index bf3192d9df173..5f880f5596654 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -575,7 +575,7 @@ impl<'tcx> TyCtxt<'tcx> { // expr. Node::Block(Block { expr: Some(e), .. }) if cur_id != e.hir_id => return None, Node::Block(Block { expr: Some(e), .. }) - if matches!(e.kind, ExprKind::If(_, _, None)) => + if let ExprKind::If(_, _, None) = e.kind => { return None; } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index bed902e8334bb..7f1ca26455a90 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -264,7 +264,7 @@ fn explain_lint_level_source( err.note_once(format!( "`{flag} {hyphen_case_lint_name}` implied by `{flag} {hyphen_case_flag_val}`" )); - if matches!(orig_level, Level::Warn | Level::Deny) { + if let Level::Warn | Level::Deny = orig_level { err.help_once(format!( "to override `{flag} {hyphen_case_flag_val}` add `#[allow({name})]`" )); diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 18520089e3ea3..5601176f9d617 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -403,7 +403,7 @@ impl<'tcx> TyCtxt<'tcx> { return EvalResult::Allow; } - if matches!(allow_unstable, AllowUnstable::Yes) { + if let AllowUnstable::Yes = allow_unstable { return EvalResult::Allow; } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 3bdc5fdb420c2..88759c6c0b235 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1879,13 +1879,16 @@ fn pretty_print_const_value_tcx<'tcx>( let u8_type = tcx.types.u8; match (ct, ty.kind()) { // Byte/string slices, printed as (byte) string literals. - (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => { + (_, ty::Ref(_, inner_ty, _)) if let ty::Str = inner_ty.kind() => { if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) { fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?; return Ok(()); } } - (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => { + (_, ty::Ref(_, inner_ty, _)) + if let ty::Slice(t) = inner_ty.kind() + && *t == u8_type => + { if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) { pretty_print_byte_str(fmt, data)?; return Ok(()); diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index bd4188dd0ff49..46ed5ef807ec6 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -25,7 +25,7 @@ impl<'tcx> Statement<'tcx> { /// Changes a statement to a nop. This is both faster than deleting instructions and avoids /// invalidating statement indices in `Location`s. pub fn make_nop(&mut self, drop_debuginfo: bool) { - if matches!(self.kind, StatementKind::Nop) { + if self.kind == StatementKind::Nop { return; } let replaced_stmt = std::mem::replace(&mut self.kind, StatementKind::Nop); diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index edbb736128cf9..0eda22ba01e35 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -1050,7 +1050,7 @@ impl<'tcx> PatRangeBoundary<'tcx> { // we can do scalar comparisons. E.g. `unicode-normalization` has // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared // in this way. - (Finite(a), Finite(b)) if matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Char) => { + (Finite(a), Finite(b)) if let ty::Int(_) | ty::Uint(_) | ty::Char = ty.kind() => { if let (Some(a), Some(b)) = (a.try_to_scalar_int(), b.try_to_scalar_int()) { let sz = ty.primitive_size(tcx); let cmp = match ty.kind() { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 471bd1d937e94..49ef49a531ff4 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1703,14 +1703,12 @@ impl<'tcx> TyCtxt<'tcx> { let def_kind = self.def_kind(def_id); if def_kind.has_codegen_attrs() { self.codegen_fn_attrs(def_id) - } else if matches!( - def_kind, - DefKind::AnonConst - | DefKind::AssocConst - | DefKind::Const - | DefKind::InlineConst - | DefKind::GlobalAsm - ) { + } else if let DefKind::AnonConst + | DefKind::AssocConst + | DefKind::Const + | DefKind::InlineConst + | DefKind::GlobalAsm = def_kind + { CodegenFnAttrs::EMPTY } else { bug!( @@ -2171,7 +2169,7 @@ impl<'tcx> TyCtxt<'tcx> { // They have visibilities inherited from the module they are defined in. // Visibilities for opaque types are meaningless, but still provided // so that all items have visibilities. - if matches!(def_kind, DefKind::Closure | DefKind::OpaqueTy) { + if let DefKind::Closure | DefKind::OpaqueTy = def_kind { let parent_mod = self.parent_module_from_def_id(def_id).to_def_id(); feed.visibility(ty::Visibility::Restricted(parent_mod)); } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 2e64fc290fcc2..9c5fa47d0fd1a 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -490,7 +490,7 @@ pub fn suggest_constraining_type_params<'a>( // Suggestion: // trait Foo {... } // - insert: `where T: Zar` - if matches!(param.kind, hir::GenericParamKind::Type { default: Some(_), .. }) { + if let hir::GenericParamKind::Type { default: Some(_), .. } = param.kind { // If we are here and the where clause span is of non-zero length // it means we're dealing with an empty where clause like this: // fn foo(x: X) where { ... } diff --git a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs index 953ad62be0a86..d03e593e37b91 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs @@ -160,7 +160,7 @@ impl<'tcx> InhabitedPredicate<'tcx> { pub fn all(tcx: TyCtxt<'tcx>, iter: impl IntoIterator) -> Self { let mut result = Self::True; for pred in iter { - if matches!(pred, Self::False) { + if pred == Self::False { return Self::False; } result = result.and(tcx, pred); @@ -171,7 +171,7 @@ impl<'tcx> InhabitedPredicate<'tcx> { pub fn any(tcx: TyCtxt<'tcx>, iter: impl IntoIterator) -> Self { let mut result = Self::False; for pred in iter { - if matches!(pred, Self::True) { + if pred == Self::True { return Self::True; } result = result.or(tcx, pred); diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index 7eb74b52b44c6..0a6a2228b7b98 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -62,7 +62,7 @@ pub(crate) fn provide(providers: &mut Providers) { /// requires calling [`InhabitedPredicate::instantiate`] fn inhabited_predicate_adt(tcx: TyCtxt<'_>, def_id: DefId) -> InhabitedPredicate<'_> { if let Some(def_id) = def_id.as_local() { - if matches!(tcx.representability(def_id), ty::Representability::Infinite(_)) { + if let ty::Representability::Infinite(_) = tcx.representability(def_id) { return InhabitedPredicate::True; } } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 798e14c6f378f..6e6a8cfc1d228 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3379,7 +3379,7 @@ define_print_and_forward_display! { fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) { // Iterate all (non-anonymous) local crate items no matter where they are defined. for id in tcx.hir_free_items() { - if matches!(tcx.def_kind(id.owner_id), DefKind::Use) { + if tcx.def_kind(id.owner_id) == DefKind::Use { continue; } diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 691cb43b724a4..8d15d6e68c351 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -260,7 +260,7 @@ pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) - pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] { let mut traits = Vec::new(); for id in tcx.hir_free_items() { - if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) { + if let DefKind::Trait | DefKind::TraitAlias = tcx.def_kind(id.owner_id) { traits.push(id.owner_id.to_def_id()) } } diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index 1f5d31932f1a2..defa532ac8321 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -343,7 +343,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let l = self.eval_operand(left).and_then(|l| self.use_ecx(|this| this.ecx.read_immediate(&l))); // Check for exceeding shifts *even if* we cannot evaluate the LHS. - if matches!(op, BinOp::Shr | BinOp::Shl) { + if let BinOp::Shr | BinOp::Shl = op { let r = r.clone()?; // We need the type of the LHS. We cannot use `place_layout` as that is the type // of the result, which for checked binops is not the same! @@ -561,7 +561,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let right = self.use_ecx(|this| this.ecx.read_immediate(&right))?; let val = self.use_ecx(|this| this.ecx.binary_op(bin_op, &left, &right))?; - if matches!(val.layout.backend_repr, BackendRepr::ScalarPair(..)) { + if let BackendRepr::ScalarPair(..) = val.layout.backend_repr { // FIXME `Value` should properly support pairs in `Immediate`... but currently // it does not. let (val, overflow) = val.to_pair(&self.ecx); diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 948f965ed7ad0..7390d4556242a 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1582,7 +1582,7 @@ impl<'v> RootCollector<'_, 'v> { } fn process_impl_item(&mut self, id: hir::ImplItemId) { - if matches!(self.tcx.def_kind(id.owner_id), DefKind::AssocFn) { + if self.tcx.def_kind(id.owner_id) == DefKind::AssocFn { self.push_if_root(id.owner_id.def_id); } } @@ -1718,7 +1718,7 @@ fn create_mono_items_for_default_impls<'tcx>( ) { let impl_ = tcx.impl_trait_header(item.owner_id); - if matches!(impl_.polarity, ty::ImplPolarity::Negative) { + if impl_.polarity == ty::ImplPolarity::Negative { return; } diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 168921655a394..990b0ded5a246 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -1344,7 +1344,7 @@ where .is_some_and(|c| has_only_region_constraints(c.result)) { candidates.retain(|c| { - if matches!(c.source, CandidateSource::Impl(_)) { + if let CandidateSource::Impl(_) = c.source { debug!(?c, "unsoundly dropping impl in favor of builtin dyn-candidate"); false } else { @@ -1385,7 +1385,7 @@ where // Extract non-nested alias bound candidates, will be preferred over where bounds if // we're proving an auto-trait, sizedness trait or default trait. - if matches!(candidate_preference_mode, CandidatePreferenceMode::Marker) + if let CandidatePreferenceMode::Marker = candidate_preference_mode && candidates.iter().any(|c| { matches!(c.source, CandidateSource::AliasBound(AliasBoundKind::SelfBounds)) }) diff --git a/compiler/rustc_parse/src/parser/asm.rs b/compiler/rustc_parse/src/parser/asm.rs index 41c3b0f0b676a..17856d6fa24c1 100644 --- a/compiler/rustc_parse/src/parser/asm.rs +++ b/compiler/rustc_parse/src/parser/asm.rs @@ -77,7 +77,7 @@ fn eat_operand_keyword<'a>( exp: ExpKeywordPair, asm_macro: AsmMacro, ) -> PResult<'a, bool> { - if matches!(asm_macro, AsmMacro::Asm) { + if asm_macro == AsmMacro::Asm { Ok(p.eat_keyword(exp)) } else { let span = p.token.span; @@ -259,10 +259,7 @@ pub fn parse_asm_args<'a>( // things it could have been. match template.kind { ast::ExprKind::Lit(token_lit) - if matches!( - token_lit.kind, - token::LitKind::Str | token::LitKind::StrRaw(_) - ) => {} + if let token::LitKind::Str | token::LitKind::StrRaw(_) = token_lit.kind => {} ast::ExprKind::MacCall(..) => {} _ => { let err = dcx.create_err(errors::AsmExpectedOther { diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index 44fdf146f9c73..2d1b033f67da1 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -253,7 +253,7 @@ impl<'a> Parser<'a> { // pre-attribute position supplied, if `f` indicated it is necessary. // (The caller is responsible for providing a non-`None` `pre_attr_pos` // if this is a possibility.) - if matches!(use_pre_attr_pos, UsePreAttrPos::Yes) { + if let UsePreAttrPos::Yes = use_pre_attr_pos { collect_pos = pre_attr_pos.unwrap(); } @@ -372,7 +372,7 @@ impl<'a> Parser<'a> { self.capture_state .parser_replacements .push((ParserRange(start_pos..end_pos), Some(target))); - } else if matches!(self.capture_state.capturing, Capturing::No) { + } else if let Capturing::No = self.capture_state.capturing { // Only clear the ranges once we've finished capturing entirely, i.e. we've finished // the outermost call to this method. self.capture_state.parser_replacements.clear(); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 4f6860fead8d0..d0bf5583550ed 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -762,7 +762,9 @@ impl<'a> Parser<'a> { } // Check for misspelled keywords if there are no suggestions added to the diagnostic. - if matches!(&err.suggestions, Suggestions::Enabled(list) if list.is_empty()) { + if let Suggestions::Enabled(list) = &err.suggestions + && list.is_empty() + { self.check_for_misspelled_kw(&mut err, &expected); } Err(err) @@ -2280,7 +2282,7 @@ impl<'a> Parser<'a> { { let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| { let ed = this.token.span.with_neighbor(this.prev_token.span).edition(); - if matches!(fn_parse_mode.context, crate::parser::item::FnContext::Trait) + if let crate::parser::item::FnContext::Trait = fn_parse_mode.context && (fn_parse_mode.req_name)(ed, IsDotDotDot::No) { err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)"); diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index fa5e61d24d911..1e7e679c89300 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1064,7 +1064,7 @@ impl<'a> Parser<'a> { for c in float_str.chars() { if c == '_' || c.is_ascii_alphanumeric() { ident_like.push(c); - } else if matches!(c, '.' | '+' | '-') { + } else if let '.' | '+' | '-' = c { if !ident_like.is_empty() { components.push(IdentLike(mem::take(&mut ident_like))); } @@ -2977,7 +2977,7 @@ impl<'a> Parser<'a> { let (pat, expr) = self.parse_for_head()?; let pat = Box::new(pat); // Recover from missing expression in `for` loop - if matches!(expr.kind, ExprKind::Block(..)) + if let ExprKind::Block(..) = expr.kind && self.token.kind != token::OpenBrace && self.may_recover() { @@ -3082,7 +3082,7 @@ impl<'a> Parser<'a> { pub(crate) fn eat_label(&mut self) -> Option