From cc907f80b95c6ec530c5ee1b05b044a468f07eca Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Wed, 12 Jul 2023 21:49:27 -0400 Subject: [PATCH] Re-format let-else per rustfmt update --- compiler/rustc_ast_lowering/src/asm.rs | 7 +- .../src/diagnostics/conflict_errors.rs | 64 +++-- .../rustc_borrowck/src/diagnostics/mod.rs | 14 +- .../src/diagnostics/move_errors.rs | 10 +- .../src/diagnostics/mutability_errors.rs | 8 +- .../src/diagnostics/region_errors.rs | 40 +-- .../src/diagnostics/region_name.rs | 4 +- .../rustc_borrowck/src/region_infer/mod.rs | 13 +- compiler/rustc_borrowck/src/type_check/mod.rs | 28 +-- .../rustc_borrowck/src/universal_regions.rs | 4 +- compiler/rustc_builtin_macros/src/asm.rs | 3 +- .../src/deriving/cmp/ord.rs | 4 +- .../src/deriving/cmp/partial_ord.rs | 4 +- compiler/rustc_builtin_macros/src/env.rs | 7 +- .../src/proc_macro_harness.rs | 4 +- .../src/debuginfo/metadata.rs | 5 +- .../src/debuginfo/metadata/enums/cpp_like.rs | 6 +- .../src/debuginfo/metadata/enums/mod.rs | 2 +- .../src/debuginfo/metadata/enums/native.rs | 10 +- .../rustc_codegen_ssa/src/mir/debuginfo.rs | 6 +- .../rustc_codegen_ssa/src/target_features.rs | 8 +- .../rustc_const_eval/src/const_eval/error.rs | 4 +- .../src/interpret/eval_context.rs | 4 +- .../rustc_const_eval/src/interpret/memory.rs | 6 +- .../rustc_const_eval/src/interpret/place.rs | 10 +- .../src/interpret/terminator.rs | 33 ++- .../src/transform/check_consts/check.rs | 3 +- .../src/transform/promote_consts.rs | 10 +- .../src/transform/validate.rs | 17 +- .../src/graph/dominators/mod.rs | 4 +- compiler/rustc_errors/src/markdown/parse.rs | 2 +- compiler/rustc_errors/src/markdown/term.rs | 2 +- compiler/rustc_expand/src/base.rs | 2 +- compiler/rustc_expand/src/config.rs | 15 +- compiler/rustc_expand/src/expand.rs | 10 +- compiler/rustc_expand/src/mbe/diagnostics.rs | 3 +- compiler/rustc_expand/src/mbe/metavar_expr.rs | 11 +- compiler/rustc_expand/src/mbe/transcribe.rs | 8 +- compiler/rustc_hir/src/hir.rs | 12 +- .../rustc_hir_analysis/src/astconv/mod.rs | 106 ++++---- .../rustc_hir_analysis/src/check/dropck.rs | 5 +- .../src/check/intrinsicck.rs | 8 +- compiler/rustc_hir_analysis/src/collect.rs | 12 +- .../src/collect/predicates_of.rs | 10 +- .../src/collect/resolve_bound_vars.rs | 12 +- .../wrong_number_of_generic_args.rs | 55 +++-- compiler/rustc_hir_typeck/src/_match.rs | 29 ++- compiler/rustc_hir_typeck/src/callee.rs | 6 +- compiler/rustc_hir_typeck/src/coercion.rs | 4 +- compiler/rustc_hir_typeck/src/demand.rs | 201 +++++++++++----- compiler/rustc_hir_typeck/src/expr.rs | 17 +- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 95 +++++--- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 10 +- .../src/fn_ctxt/suggestions.rs | 62 +++-- .../rustc_hir_typeck/src/method/confirm.rs | 3 +- compiler/rustc_hir_typeck/src/method/probe.rs | 16 +- .../rustc_hir_typeck/src/method/suggest.rs | 45 ++-- .../rustc_hir_typeck/src/rvalue_scopes.rs | 4 +- compiler/rustc_hir_typeck/src/upvar.rs | 11 +- compiler/rustc_incremental/src/persist/fs.rs | 14 +- compiler/rustc_index/src/bit_set.rs | 4 +- compiler/rustc_infer/src/errors/mod.rs | 3 +- .../src/infer/error_reporting/mod.rs | 5 +- .../infer/error_reporting/need_type_info.rs | 6 +- .../mismatched_static_lifetime.rs | 8 +- .../nice_region_error/static_impl_trait.rs | 4 +- .../src/infer/error_reporting/note.rs | 44 ++-- .../src/infer/error_reporting/suggest.rs | 20 +- compiler/rustc_interface/src/interface.rs | 3 +- compiler/rustc_lint/src/array_into_iter.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 19 +- compiler/rustc_lint/src/cast_ref_to_mut.rs | 4 +- .../src/for_loops_over_fallibles.rs | 4 +- compiler/rustc_lint/src/levels.rs | 16 +- compiler/rustc_lint/src/noop_method_call.rs | 7 +- .../src/opaque_hidden_inferred_bound.rs | 11 +- compiler/rustc_lint/src/traits.rs | 14 +- compiler/rustc_lint/src/types.rs | 22 +- compiler/rustc_lint/src/unused.rs | 4 +- .../src/diagnostics/diagnostic_builder.rs | 14 +- .../src/diagnostics/subdiagnostic.rs | 4 +- compiler/rustc_macros/src/newtype.rs | 6 +- compiler/rustc_metadata/src/creader.rs | 8 +- compiler/rustc_metadata/src/locator.rs | 8 +- compiler/rustc_metadata/src/rmeta/decoder.rs | 24 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 8 +- compiler/rustc_metadata/src/rmeta/table.rs | 6 +- compiler/rustc_middle/src/ty/consts/int.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 8 +- compiler/rustc_middle/src/ty/util.rs | 3 +- .../rustc_mir_build/src/build/custom/parse.rs | 4 +- .../src/build/custom/parse/instruction.rs | 6 +- .../src/build/expr/as_place.rs | 12 +- .../rustc_mir_build/src/build/matches/mod.rs | 8 +- .../rustc_mir_build/src/build/matches/test.rs | 6 +- .../rustc_mir_build/src/check_unsafety.rs | 4 +- .../src/thir/pattern/check_match.rs | 4 +- compiler/rustc_mir_dataflow/src/impls/mod.rs | 8 +- compiler/rustc_mir_transform/src/copy_prop.rs | 8 +- .../src/dataflow_const_prop.rs | 2 +- compiler/rustc_mir_transform/src/dest_prop.rs | 10 +- .../src/early_otherwise_branch.rs | 47 ++-- compiler/rustc_mir_transform/src/generator.rs | 4 +- .../rustc_mir_transform/src/instsimplify.rs | 24 +- .../src/lower_intrinsics.rs | 4 +- .../src/remove_uninit_drops.rs | 9 +- compiler/rustc_mir_transform/src/simplify.rs | 3 +- compiler/rustc_mir_transform/src/sroa.rs | 4 +- compiler/rustc_mir_transform/src/ssa.rs | 8 +- .../src/uninhabited_enum_branching.rs | 3 +- .../rustc_parse/src/parser/diagnostics.rs | 5 +- compiler/rustc_parse/src/parser/mod.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 14 +- compiler/rustc_passes/src/liveness.rs | 8 +- compiler/rustc_passes/src/stability.rs | 4 +- compiler/rustc_resolve/src/imports.rs | 4 +- compiler/rustc_resolve/src/late.rs | 11 +- .../rustc_resolve/src/late/diagnostics.rs | 38 ++- compiler/rustc_resolve/src/lib.rs | 5 +- compiler/rustc_span/src/lib.rs | 3 +- .../src/solve/assembly/mod.rs | 8 +- .../src/solve/eval_ctxt/select.rs | 5 +- .../rustc_trait_selection/src/solve/mod.rs | 9 +- .../src/solve/project_goals.rs | 151 ++++++------ .../src/solve/trait_goals.rs | 8 +- .../src/traits/auto_trait.rs | 11 +- .../src/traits/coherence.rs | 5 +- .../src/traits/error_reporting/mod.rs | 27 ++- .../src/traits/error_reporting/suggestions.rs | 227 ++++++++++++------ .../rustc_trait_selection/src/traits/mod.rs | 18 +- .../src/traits/outlives_bounds.rs | 3 +- .../src/traits/select/candidate_assembly.rs | 3 +- .../src/traits/select/confirmation.rs | 7 +- .../src/traits/specialize/mod.rs | 10 +- compiler/rustc_ty_utils/src/assoc.rs | 4 +- compiler/rustc_ty_utils/src/instance.rs | 6 +- compiler/rustc_ty_utils/src/layout.rs | 9 +- .../rustc_ty_utils/src/layout_sanity_check.rs | 4 +- library/core/src/array/mod.rs | 2 +- library/core/src/str/pattern.rs | 4 +- src/bootstrap/clean.rs | 4 +- src/bootstrap/format.rs | 8 +- src/librustdoc/clean/blanket_impl.rs | 10 +- src/librustdoc/clean/mod.rs | 3 +- src/librustdoc/clean/simplify.rs | 4 +- src/librustdoc/clean/types.rs | 14 +- src/librustdoc/clean/utils.rs | 3 +- src/librustdoc/doctest.rs | 3 +- src/librustdoc/formats/renderer.rs | 7 +- src/librustdoc/html/format.rs | 7 +- src/librustdoc/html/highlight.rs | 6 +- src/librustdoc/html/render/context.rs | 7 +- src/librustdoc/html/render/mod.rs | 4 +- .../passes/check_doc_test_visibility.rs | 3 +- .../passes/collect_intra_doc_links.rs | 3 +- src/librustdoc/passes/lint/bare_urls.rs | 9 +- .../passes/lint/check_code_block_syntax.rs | 11 +- src/librustdoc/passes/lint/html_tags.rs | 4 +- src/librustdoc/passes/propagate_doc_cfg.rs | 5 +- src/tools/build_helper/src/git.rs | 8 +- .../collect-license-metadata/src/path_tree.rs | 5 +- src/tools/compiletest/src/header.rs | 5 +- 162 files changed, 1404 insertions(+), 947 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index d350498bc96..ab55c09465b 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -352,7 +352,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let idx2 = *o.get(); let (ref op2, op_sp2) = operands[idx2]; - let Some(asm::InlineAsmRegOrRegClass::Reg(reg2)) = op2.reg() else { + let Some(asm::InlineAsmRegOrRegClass::Reg(reg2)) = op2.reg() + else { unreachable!(); }; @@ -368,7 +369,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { assert!(!*late); let out_op_sp = if input { op_sp2 } else { op_sp }; Some(out_op_sp) - }, + } _ => None, }; @@ -377,7 +378,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { op_span2: op_sp2, reg1_name: reg.name(), reg2_name: reg2.name(), - in_out + in_out, }); } Entry::Vacant(v) => { diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index c8c8b72b389..6e7b0c2e11f 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -714,7 +714,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { _ => None, }; - let Some(borrow_level) = borrow_level else { return false; }; + let Some(borrow_level) = borrow_level else { + return false; + }; let sugg = move_sites .iter() .map(|move_site| { @@ -763,7 +765,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .typeck_root_def_id(self.mir_def_id().to_def_id()) .as_local() .and_then(|def_id| tcx.hir().get_generics(def_id)) - else { return; }; + else { + return; + }; // Try to find predicates on *generic params* that would allow copying `ty` let ocx = ObligationCtxt::new(&self.infcx); let copy_did = tcx.require_lang_item(LangItem::Copy, Some(span)); @@ -1220,18 +1224,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { return; }; let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local); - let Some((inner_call_loc, inner_call_term)) = inner_param_uses.into_iter().find_map(|loc| { - let Either::Right(term) = self.body.stmt_at(loc) else { - debug!("{:?} is a statement, so it can't be a call", loc); - return None; - }; - let TerminatorKind::Call { args, .. } = &term.kind else { - debug!("not a call: {:?}", term); - return None; - }; - debug!("checking call args for uses of inner_param: {:?}", args); - args.contains(&Operand::Move(inner_param)).then_some((loc, term)) - }) else { + let Some((inner_call_loc, inner_call_term)) = + inner_param_uses.into_iter().find_map(|loc| { + let Either::Right(term) = self.body.stmt_at(loc) else { + debug!("{:?} is a statement, so it can't be a call", loc); + return None; + }; + let TerminatorKind::Call { args, .. } = &term.kind else { + debug!("not a call: {:?}", term); + return None; + }; + debug!("checking call args for uses of inner_param: {:?}", args); + args.contains(&Operand::Move(inner_param)).then_some((loc, term)) + }) + else { debug!("no uses of inner_param found as a by-move call arg"); return; }; @@ -1442,21 +1448,24 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } // Get closure's arguments - let ty::Closure(_, substs) = typeck_results.expr_ty(closure_expr).kind() else { /* hir::Closure can be a generator too */ return }; + let ty::Closure(_, substs) = typeck_results.expr_ty(closure_expr).kind() else { + /* hir::Closure can be a generator too */ + return; + }; let sig = substs.as_closure().sig(); let tupled_params = tcx.erase_late_bound_regions(sig.inputs().iter().next().unwrap().map_bound(|&b| b)); let ty::Tuple(params) = tupled_params.kind() else { return }; // Find the first argument with a matching type, get its name - let Some((_, this_name)) = params - .iter() - .zip(hir.body_param_names(closure.body)) - .find(|(param_ty, name)|{ + let Some((_, this_name)) = + params.iter().zip(hir.body_param_names(closure.body)).find(|(param_ty, name)| { // FIXME: also support deref for stuff like `Rc` arguments param_ty.peel_refs() == local_ty && name != &Ident::empty() }) - else { return }; + else { + return; + }; let spans; if let Some((_path_expr, qpath)) = finder.error_path @@ -2899,7 +2908,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { { let def_id = def_id.expect_local(); for operand in operands { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand else { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + operand + else { continue; }; debug!( @@ -2908,7 +2919,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); // Find the local from the operand. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + let Some(assigned_from_local) = + assigned_from.local_or_deref_local() + else { continue; }; @@ -2961,7 +2974,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); // Find the local from the rvalue. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { continue }; + let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + continue; + }; debug!( "annotate_argument_and_return_for_borrow: \ assigned_from_local={:?}", @@ -3009,7 +3024,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { assigned_to, args ); for operand in args { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand else { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand + else { continue; }; debug!( diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 0e56463e17c..e51da961add 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -847,14 +847,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { kind: TerminatorKind::Call { fn_span, call_source, .. }, .. }) = &self.body[location.block].terminator { - let Some((method_did, method_substs)) = - rustc_middle::util::find_self_call( - self.infcx.tcx, - &self.body, - target_temp, - location.block, - ) - else { + let Some((method_did, method_substs)) = rustc_middle::util::find_self_call( + self.infcx.tcx, + &self.body, + target_temp, + location.block, + ) else { return normal_ret; }; diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 8b77477a31a..3d4ca320ac3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -184,7 +184,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } // Error with the pattern LookupResult::Exact(_) => { - let LookupResult::Parent(Some(mpi)) = self.move_data.rev_lookup.find(move_from.as_ref()) else { + let LookupResult::Parent(Some(mpi)) = + self.move_data.rev_lookup.find(move_from.as_ref()) + else { // move_from should be a projection from match_place. unreachable!("Probably not unreachable..."); }; @@ -494,8 +496,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if let LocalInfo::User(BindingForm::Var(VarBindingForm { pat_span, .. })) = *bind_to.local_info() { - let Ok(pat_snippet) = - self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) else { continue; }; + let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) + else { + continue; + }; let Some(stripped) = pat_snippet.strip_prefix('&') else { suggestions.push(( bind_to.source_info.span.shrink_to_lo(), diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 1f2fefadf65..a0a145ef70a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -648,8 +648,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let def_id = self.body.source.def_id(); let hir_id = hir_map.local_def_id_to_hir_id(def_id.as_local().unwrap()); let node = hir_map.find(hir_id); - let Some(hir::Node::Item(item)) = node else { return; }; - let hir::ItemKind::Fn(.., body_id) = item.kind else { return; }; + let Some(hir::Node::Item(item)) = node else { + return; + }; + let hir::ItemKind::Fn(.., body_id) = item.kind else { + return; + }; let body = self.infcx.tcx.hir().body(body_id); let mut v = V { assign_span: span, err, ty, suggested: false }; diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 617c85174cb..415ff5aea03 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -224,12 +224,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut hrtb_bounds = vec![]; gat_id_and_generics.iter().flatten().for_each(|(gat_hir_id, generics)| { for pred in generics.predicates { - let BoundPredicate( - WhereBoundPredicate { - bound_generic_params, - bounds, - .. - }) = pred else { continue; }; + let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) = pred + else { + continue; + }; if bound_generic_params .iter() .rfind(|bgp| hir.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id) @@ -813,7 +811,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { return; } let suitable_region = self.infcx.tcx.is_suitable_region(f); - let Some(suitable_region) = suitable_region else { return; }; + let Some(suitable_region) = suitable_region else { + return; + }; let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.def_id); @@ -848,7 +848,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let Some((alias_tys, alias_span, lt_addition_span)) = self .infcx .tcx - .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) else { return; }; + .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) + else { + return; + }; // in case the return type of the method is a type alias let mut spans_suggs: Vec<_> = Vec::new(); @@ -932,8 +935,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut visitor = TraitObjectVisitor(FxIndexSet::default()); visitor.visit_ty(param.param_ty); - let Some((ident, self_ty)) = - NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &visitor.0) else { return; }; + let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait( + tcx, + instance.def_id(), + &visitor.0, + ) else { + return; + }; self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty); } @@ -981,23 +989,25 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { sup: RegionVid, ) { let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else { - return + return; }; let Some((ty_sub, _)) = self .infcx .tcx .is_suitable_region(sub) - .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else { - return + .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) + else { + return; }; let Some((ty_sup, _)) = self .infcx .tcx .is_suitable_region(sup) - .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else { - return + .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) + else { + return; }; suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag); diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 074f37bed13..963adc01894 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -325,8 +325,8 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { // Can't have BrEnv in functions, constants or generators. bug!("BrEnv outside of closure."); }; - let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) - = tcx.hir().expect_expr(self.mir_hir_id()).kind + let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) = + tcx.hir().expect_expr(self.mir_hir_id()).kind else { bug!("Closure is not defined by a closure expr"); }; diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index e45d3a2c882..9202d0b06ff 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -2058,10 +2058,17 @@ impl<'tcx> RegionInferenceContext<'tcx> { let mut extra_info = vec![]; for constraint in path.iter() { let outlived = constraint.sub; - let Some(origin) = self.var_infos.get(outlived) else { continue; }; - let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; }; + let Some(origin) = self.var_infos.get(outlived) else { + continue; + }; + let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin + else { + continue; + }; debug!(?constraint, ?p); - let ConstraintCategory::Predicate(span) = constraint.category else { continue; }; + let ConstraintCategory::Predicate(span) = constraint.category else { + continue; + }; extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span)); // We only want to point to one break; diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index a15e1065c81..638cede6aaa 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -2039,28 +2039,16 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } CastKind::PointerCoercion(PointerCoercion::MutToConstPointer) => { - let ty::RawPtr(ty::TypeAndMut { - ty: ty_from, - mutbl: hir::Mutability::Mut, - }) = op.ty(body, tcx).kind() else { - span_mirbug!( - self, - rvalue, - "unexpected base type for cast {:?}", - ty, - ); + let ty::RawPtr(ty::TypeAndMut { ty: ty_from, mutbl: hir::Mutability::Mut }) = + op.ty(body, tcx).kind() + else { + span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,); return; }; - let ty::RawPtr(ty::TypeAndMut { - ty: ty_to, - mutbl: hir::Mutability::Not, - }) = ty.kind() else { - span_mirbug!( - self, - rvalue, - "unexpected target type for cast {:?}", - ty, - ); + let ty::RawPtr(ty::TypeAndMut { ty: ty_to, mutbl: hir::Mutability::Not }) = + ty.kind() + else { + span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,); return; }; if let Err(terr) = self.sub_types( diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 7821b82bf2b..4d9c4b178dc 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -929,7 +929,9 @@ fn for_each_late_bound_region_in_item<'tcx>( } for bound_var in tcx.late_bound_vars(tcx.hir().local_def_id_to_hir_id(mir_def_id)) { - let ty::BoundVariableKind::Region(bound_region) = bound_var else { continue; }; + let ty::BoundVariableKind::Region(bound_region) = bound_var else { + continue; + }; let liberated_region = ty::Region::new_free(tcx, mir_def_id.to_def_id(), bound_region); f(liberated_region); } diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 6187e4f513b..19acefc38e3 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -157,8 +157,7 @@ pub fn parse_asm_args<'a>( } else if p.eat_keyword(sym::sym) { let expr = p.parse_expr()?; let ast::ExprKind::Path(qself, path) = &expr.kind else { - let err = diag - .create_err(errors::AsmSymNoPath { span: expr.span }); + let err = diag.create_err(errors::AsmSymNoPath { span: expr.span }); return Err(err); }; let sym = ast::InlineAsmSym { diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs index 4401cf8a9c5..ea81cee78b7 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs @@ -61,8 +61,8 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> Bl |cx, fold| match fold { CsFold::Single(field) => { let [other_expr] = &field.other_selflike_exprs[..] else { - cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); - }; + cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); + }; let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, cmp_path.clone(), args) } diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index 54b6cb7d713..a5b3a504e38 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -94,8 +94,8 @@ fn cs_partial_cmp( |cx, fold| match fold { CsFold::Single(field) => { let [other_expr] = &field.other_selflike_exprs[..] else { - cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); - }; + cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); + }; let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, partial_cmp_path.clone(), args) } diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index 8f64e332861..bcff475f626 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -83,7 +83,12 @@ pub fn expand_env<'cx>( None => { // Use the string literal in the code in the diagnostic to avoid confusing diagnostics, // e.g. when the literal contains escape sequences. - let ast::ExprKind::Lit(ast::token::Lit { kind: ast::token::LitKind::Str, symbol: original_var, ..}) = &var_expr.kind else { + let ast::ExprKind::Lit(ast::token::Lit { + kind: ast::token::LitKind::Str, + symbol: original_var, + .. + }) = &var_expr.kind + else { unreachable!("`expr_to_string` ensures this is a string lit") }; cx.emit_err(errors::EnvNotDefined { diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index b35a2e2a292..a7908373b6d 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -89,7 +89,9 @@ impl<'a> CollectProcMacros<'a> { } fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) { - let Some((trait_name, proc_attrs)) = parse_macro_name_and_helper_attrs(self.handler, attr, "derive") else { + let Some((trait_name, proc_attrs)) = + parse_macro_name_and_helper_attrs(self.handler, attr, "derive") + else { return; }; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index d61400d3fa3..a56faf735f1 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -739,7 +739,10 @@ fn build_foreign_type_di_node<'ll, 'tcx>( debug!("build_foreign_type_di_node: {:?}", t); let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else { - bug!("build_foreign_type_di_node() called with unexpected type: {:?}", unique_type_id.expect_ty()); + bug!( + "build_foreign_type_di_node() called with unexpected type: {:?}", + unique_type_id.expect_ty() + ); }; build_type_with_children( diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index b2765ffc934..45698407e83 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -199,7 +199,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let enum_type_and_layout = cx.layout_of(enum_type); let enum_type_name = compute_debuginfo_type_name(cx.tcx, enum_type, false); @@ -667,7 +667,9 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( generator_type_and_layout: TyAndLayout<'tcx>, generator_type_di_node: &'ll DIType, ) -> SmallVec<&'ll DIType> { - let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } = generator_type_and_layout.variants else { + let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } = + generator_type_and_layout.variants + else { bug!("This function only supports layouts with directly encoded tags.") }; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index 8746ce0c5b1..008f21ae3f5 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -51,7 +51,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let enum_type_and_layout = cx.layout_of(enum_type); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 4d1cd64865f..3799b69ee10 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -57,7 +57,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let containing_scope = get_namespace_for_item(cx, enum_adt_def.did()); let enum_type_and_layout = cx.layout_of(enum_type); @@ -132,9 +132,9 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { let generator_type = unique_type_id.expect_ty(); - let &ty::Generator(generator_def_id, _, _ ) = generator_type.kind() else { + let &ty::Generator(generator_def_id, _, _) = generator_type.kind() else { bug!("build_generator_di_node() called with non-generator type: `{:?}`", generator_type) - }; + }; let containing_scope = get_namespace_for_item(cx, generator_def_id); let generator_type_and_layout = cx.layout_of(generator_type); @@ -158,7 +158,9 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( let generator_layout = cx.tcx.optimized_mir(generator_def_id).generator_layout().unwrap(); - let Variants::Multiple { tag_encoding: TagEncoding::Direct, ref variants, .. } = generator_type_and_layout.variants else { + let Variants::Multiple { tag_encoding: TagEncoding::Direct, ref variants, .. } = + generator_type_and_layout.variants + else { bug!( "Encountered generator with non-direct-tag layout: {:?}", generator_type_and_layout diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 4b27b64962d..34b8d8b5a6f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -186,7 +186,11 @@ fn calculate_debuginfo_offset< } => { let offset = indirect_offsets.last_mut().unwrap_or(&mut direct_offset); let FieldsShape::Array { stride, count: _ } = place.layout().fields else { - span_bug!(var.source_info.span, "ConstantIndex on non-array type {:?}", place.layout()) + span_bug!( + var.source_info.span, + "ConstantIndex on non-array type {:?}", + place.layout() + ) }; *offset += stride * index; place = place.project_constant_index(bx, index); diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 9e06fec550d..7b5d83c612a 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -369,13 +369,9 @@ pub fn from_target_feature( // We allow comma separation to enable multiple features. target_features.extend(value.as_str().split(',').filter_map(|feature| { let Some(feature_gate) = supported_target_features.get(feature) else { - let msg = - format!("the feature named `{}` is not valid for this target", feature); + let msg = format!("the feature named `{}` is not valid for this target", feature); let mut err = tcx.sess.struct_span_err(item.span(), msg); - err.span_label( - item.span(), - format!("`{}` is not valid for this target", feature), - ); + err.span_label(item.span(), format!("`{}` is not valid for this target", feature)); if let Some(stripped) = feature.strip_prefix('+') { let valid = supported_target_features.contains_key(stripped); if valid { diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index 7890d878d08..ffeff8d079a 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -150,8 +150,8 @@ where tcx.sess.create_err(Spanned { span, node: layout_error.into_diagnostic() }); err.code(rustc_errors::error_code!(E0080)); let Some((mut err, handler)) = err.into_diagnostic() else { - panic!("did not emit diag"); - }; + panic!("did not emit diag"); + }; for frame in frames { err.eager_subdiagnostic(handler, frame); } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 5e5ad31d8c2..568618908e3 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -604,7 +604,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // the last field). Can't have foreign types here, how would we // adjust alignment and size for them? let field = layout.field(self, layout.fields.count() - 1); - let Some((unsized_size, mut unsized_align)) = self.size_and_align_of(metadata, &field)? else { + let Some((unsized_size, mut unsized_align)) = + self.size_and_align_of(metadata, &field)? + else { // A field with an extern type. We don't know the actual dynamic size // or the alignment. return Ok(None); diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 1125d8d1f0e..7b44a20ef03 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -1060,11 +1060,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = Size::from_bytes(len); let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size, Align::ONE)? else { // zero-sized access - assert_matches!( - src.next(), - None, - "iterator said it was empty but returned an element" - ); + assert_matches!(src.next(), None, "iterator said it was empty but returned an element"); return Ok(()); }; diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index c2fb61753fe..a9b2b43f1e6 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -545,14 +545,17 @@ where // wrong type. let tcx = *self.tcx; - let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else { + let Some(mut alloc) = + self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? + else { // zero-sized access return Ok(()); }; match value { Immediate::Scalar(scalar) => { - let Abi::Scalar(s) = layout.abi else { span_bug!( + let Abi::Scalar(s) = layout.abi else { + span_bug!( self.cur_span(), "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}", ) @@ -565,7 +568,8 @@ where // We checked `ptr_align` above, so all fields will have the alignment they need. // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. - let Abi::ScalarPair(a, b) = layout.abi else { span_bug!( + let Abi::ScalarPair(a, b) = layout.abi else { + span_bug!( self.cur_span(), "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", layout diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index 97d7a68e190..9c500790ce6 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -390,7 +390,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { )); // Allocate enough memory to hold `src`. let Some((size, align)) = self.size_and_align_of_mplace(&src)? else { - span_bug!(self.cur_span(), "unsized fn arg with `extern` type tail should not be allowed") + span_bug!( + self.cur_span(), + "unsized fn arg with `extern` type tail should not be allowed" + ) }; let ptr = self.allocate_ptr(size, align, MemoryKind::Stack)?; let dest_place = @@ -468,10 +471,18 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { | ty::InstanceDef::ThreadLocalShim(..) | ty::InstanceDef::Item(_) => { // We need MIR for this fn - let Some((body, instance)) = - M::find_mir_or_eval_fn(self, instance, caller_abi, args, destination, target, unwind)? else { - return Ok(()); - }; + let Some((body, instance)) = M::find_mir_or_eval_fn( + self, + instance, + caller_abi, + args, + destination, + target, + unwind, + )? + else { + return Ok(()); + }; // Compute callee information using the `instance` returned by // `find_mir_or_eval_fn`. @@ -702,8 +713,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .tcx .struct_tail_erasing_lifetimes(receiver_place.layout.ty, self.param_env); let ty::Dynamic(data, _, ty::Dyn) = receiver_tail.kind() else { - span_bug!(self.cur_span(), "dynamic call on non-`dyn` type {}", receiver_tail) - }; + span_bug!( + self.cur_span(), + "dynamic call on non-`dyn` type {}", + receiver_tail + ) + }; assert!(receiver_place.layout.is_unsized()); // Get the required information from the vtable. @@ -721,7 +736,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Now determine the actual method to call. We can do that in two different ways and // compare them to ensure everything fits. - let Some(ty::VtblEntry::Method(fn_inst)) = self.get_vtable_entries(vptr)?.get(idx).copied() else { + let Some(ty::VtblEntry::Method(fn_inst)) = + self.get_vtable_entries(vptr)?.get(idx).copied() + else { // FIXME(fee1-dead) these could be variants of the UB info enum instead of this throw_ub_custom!(fluent::const_eval_dyn_call_not_a_method); }; diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index 14540e8dfe7..fa71606eeb2 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -778,8 +778,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { if trait_ref.self_ty().is_closure() && tcx.fn_trait_kind_from_def_id(trait_id).is_some() => { - let ty::Closure(closure_def_id, substs) = - *trait_ref.self_ty().kind() + let ty::Closure(closure_def_id, substs) = *trait_ref.self_ty().kind() else { unreachable!() }; diff --git a/compiler/rustc_const_eval/src/transform/promote_consts.rs b/compiler/rustc_const_eval/src/transform/promote_consts.rs index 1b39a76e460..0df110f8fbe 100644 --- a/compiler/rustc_const_eval/src/transform/promote_consts.rs +++ b/compiler/rustc_const_eval/src/transform/promote_consts.rs @@ -759,11 +759,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let (mut rvalue, source_info) = { let statement = &mut self.source[loc.block].statements[loc.statement_index]; let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else { - span_bug!( - statement.source_info.span, - "{:?} is not an assignment", - statement - ); + span_bug!(statement.source_info.span, "{:?} is not an assignment", statement); }; ( @@ -859,7 +855,9 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let local_decls = &mut self.source.local_decls; let loc = candidate.location; let statement = &mut blocks[loc.block].statements[loc.statement_index]; - let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = &mut statement.kind else { + let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = + &mut statement.kind + else { bug!() }; diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index 4cc923cd935..e516145894b 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -214,9 +214,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { stack.clear(); stack.insert(bb); loop { - let Some(parent)= parent[bb].take() else { - break - }; + let Some(parent) = parent[bb].take() else { break }; let no_cycle = stack.insert(parent); if !no_cycle { self.fail( @@ -399,7 +397,10 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; let Some(layout) = gen_body.generator_layout() else { - self.fail(location, format!("No generator layout for {:?}", parent_ty)); + self.fail( + location, + format!("No generator layout for {:?}", parent_ty), + ); return; }; @@ -409,13 +410,17 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; let Some(f_ty) = layout.field_tys.get(local) else { - self.fail(location, format!("Out of bounds local {:?} for {:?}", local, parent_ty)); + self.fail( + location, + format!("Out of bounds local {:?} for {:?}", local, parent_ty), + ); return; }; f_ty.ty } else { - let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else { + let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) + else { fail_out_of_bounds(self, location); return; }; diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index a5db14d9102..85ef2de9b5e 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -176,9 +176,7 @@ pub fn dominators(graph: &G) -> Dominators { // // ...this may be the case if a MirPass modifies the CFG to remove // or rearrange certain blocks/edges. - let Some(v) = real_to_pre_order[v] else { - continue - }; + let Some(v) = real_to_pre_order[v] else { continue }; // eval returns a vertex x from which semi[x] is minimum among // vertices semi[v] +> x *> v. diff --git a/compiler/rustc_errors/src/markdown/parse.rs b/compiler/rustc_errors/src/markdown/parse.rs index 362a451fde6..d3a08da6283 100644 --- a/compiler/rustc_errors/src/markdown/parse.rs +++ b/compiler/rustc_errors/src/markdown/parse.rs @@ -272,7 +272,7 @@ fn parse_ordered_li(buf: &[u8]) -> Parsed<'_> { fn get_indented_section(buf: &[u8]) -> (&[u8], &[u8]) { let mut end = buf.len(); for (idx, window) in buf.windows(2).enumerate() { - let &[ch, next_ch] = window else {unreachable!("always 2 elements")}; + let &[ch, next_ch] = window else { unreachable!("always 2 elements") }; if idx >= buf.len().saturating_sub(2) && next_ch == b'\n' { // End of stream end = buf.len().saturating_sub(1); diff --git a/compiler/rustc_errors/src/markdown/term.rs b/compiler/rustc_errors/src/markdown/term.rs index e45ba6d2cda..88c3c8b9ff2 100644 --- a/compiler/rustc_errors/src/markdown/term.rs +++ b/compiler/rustc_errors/src/markdown/term.rs @@ -149,7 +149,7 @@ fn write_wrapping( let Some((end_idx, _ch)) = iter.nth(ch_count) else { // Write entire line buf.write_all(to_write.as_bytes())?; - cur.set(cur.get()+to_write.chars().count()); + cur.set(cur.get() + to_write.chars().count()); break; }; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 8a251ea29d7..4b0907cf15a 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1366,7 +1366,7 @@ pub fn parse_macro_name_and_helper_attrs( return None; } let Some(trait_attr) = list[0].meta_item() else { - diag.emit_err(errors::NotAMetaItem {span: list[0].span()}); + diag.emit_err(errors::NotAMetaItem { span: list[0].span() }); return None; }; let trait_ident = match trait_attr.ident() { diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 3e43eae006f..4ec5ac22e90 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -313,9 +313,10 @@ impl<'a> StripUnconfigured<'a> { /// the attribute is incorrect. pub(crate) fn expand_cfg_attr(&self, attr: &Attribute, recursive: bool) -> Vec { let Some((cfg_predicate, expanded_attrs)) = - rustc_parse::parse_cfg_attr(attr, &self.sess.parse_sess) else { - return vec![]; - }; + rustc_parse::parse_cfg_attr(attr, &self.sess.parse_sess) + else { + return vec![]; + }; // Lint on zero attributes in source. if expanded_attrs.is_empty() { @@ -365,7 +366,9 @@ impl<'a> StripUnconfigured<'a> { // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token // for `attr` when we expand it to `#[attr]` let mut orig_trees = orig_tokens.into_trees(); - let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = orig_trees.next().unwrap() else { + let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = + orig_trees.next().unwrap() + else { panic!("Bad tokens for attribute {:?}", attr); }; let pound_span = pound_token.span; @@ -373,7 +376,9 @@ impl<'a> StripUnconfigured<'a> { let mut trees = vec![AttrTokenTree::Token(pound_token, Spacing::Alone)]; if attr.style == AttrStyle::Inner { // For inner attributes, we do the same thing for the `!` in `#![some_attr]` - let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = orig_trees.next().unwrap() else { + let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = + orig_trees.next().unwrap() + else { panic!("Bad tokens for attribute {:?}", attr); }; trees.push(AttrTokenTree::Token(bang_token, Spacing::Alone)); diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 9850723a857..3b6db9fd39c 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -651,7 +651,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { ExpandResult::Ready(match invoc.kind { InvocationKind::Bang { mac, .. } => match ext { SyntaxExtensionKind::Bang(expander) => { - let Ok(tok_result) = expander.expand(self.cx, span, mac.args.tokens.clone()) else { + let Ok(tok_result) = expander.expand(self.cx, span, mac.args.tokens.clone()) + else { return ExpandResult::Ready(fragment_kind.dummy(span)); }; self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) @@ -704,7 +705,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.emit_err(UnsupportedKeyValue { span }); } let inner_tokens = attr_item.args.inner_tokens(); - let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) else { + let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) + else { return ExpandResult::Ready(fragment_kind.dummy(span)); }; self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span) @@ -1087,9 +1089,7 @@ impl InvocationCollectorNode for P { // Work around borrow checker not seeing through `P`'s deref. let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); - let ItemKind::Mod(_, mod_kind) = &mut node.kind else { - unreachable!() - }; + let ItemKind::Mod(_, mod_kind) = &mut node.kind else { unreachable!() }; let ecx = &mut collector.cx; let (file_path, dir_path, dir_ownership) = match mod_kind { diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 3593bed2d02..03de33dc854 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -42,7 +42,8 @@ pub(super) fn failed_to_match_macro<'cx>( return result; } - let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure else { + let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure + else { return DummyResult::any(sp); }; diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index 6e919615019..b6382dcb894 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -104,13 +104,10 @@ fn parse_depth<'sess>( span: Span, ) -> PResult<'sess, usize> { let Some(tt) = iter.next() else { return Ok(0) }; - let TokenTree::Token(token::Token { - kind: token::TokenKind::Literal(lit), .. - }, _) = tt else { - return Err(sess.span_diagnostic.struct_span_err( - span, - "meta-variable expression depth must be a literal" - )); + let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else { + return Err(sess + .span_diagnostic + .struct_span_err(span, "meta-variable expression depth must be a literal")); }; if let Ok(lit_kind) = LitKind::from_token_lit(*lit) && let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index d523d3eacbe..a5f83b88f7e 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -182,9 +182,7 @@ pub(super) fn transcribe<'a>( LockstepIterSize::Constraint(len, _) => { // We do this to avoid an extra clone above. We know that this is a // sequence already. - let mbe::TokenTree::Sequence(sp, seq) = seq else { - unreachable!() - }; + let mbe::TokenTree::Sequence(sp, seq) = seq else { unreachable!() }; // Is the repetition empty? if len == 0 { @@ -399,7 +397,9 @@ fn lockstep_iter_size( } TokenTree::MetaVarExpr(_, expr) => { let default_rslt = LockstepIterSize::Unconstrained; - let Some(ident) = expr.ident() else { return default_rslt; }; + let Some(ident) = expr.ident() else { + return default_rslt; + }; let name = MacroRulesNormalizedIdent::new(ident); match lookup_cur_matched(name, interpolations, repeats) { Some(MatchedSeq(ads)) => { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 6c419471de1..35ef30114b7 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3150,7 +3150,9 @@ impl<'hir> Item<'hir> { /// Expect an [`ItemKind::ForeignMod`] or panic. #[track_caller] pub fn expect_foreign_mod(&self) -> (Abi, &'hir [ForeignItemRef]) { - let ItemKind::ForeignMod { abi, items } = self.kind else { self.expect_failed("a foreign module") }; + let ItemKind::ForeignMod { abi, items } = self.kind else { + self.expect_failed("a foreign module") + }; (abi, items) } @@ -3201,14 +3203,18 @@ impl<'hir> Item<'hir> { pub fn expect_trait( self, ) -> (IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]) { - let ItemKind::Trait(is_auto, unsafety, gen, bounds, items) = self.kind else { self.expect_failed("a trait") }; + let ItemKind::Trait(is_auto, unsafety, gen, bounds, items) = self.kind else { + self.expect_failed("a trait") + }; (is_auto, unsafety, gen, bounds, items) } /// Expect an [`ItemKind::TraitAlias`] or panic. #[track_caller] pub fn expect_trait_alias(&self) -> (&'hir Generics<'hir>, GenericBounds<'hir>) { - let ItemKind::TraitAlias(gen, bounds) = self.kind else { self.expect_failed("a trait alias") }; + let ItemKind::TraitAlias(gen, bounds) = self.kind else { + self.expect_failed("a trait alias") + }; (gen, bounds) } diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index db3d41ed247..e9c9151ca23 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -1267,9 +1267,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { "you might have meant to specify type parameters on enum \ `{type_name}`" ); - let Some(args) = assoc_segment.args else { return; }; + let Some(args) = assoc_segment.args else { + return; + }; // Get the span of the generics args *including* the leading `::`. - let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext); + let args_span = + assoc_segment.ident.span.shrink_to_hi().to(args.span_ext); if tcx.generics_of(adt_def.did()).count() == 0 { // FIXME(estebank): we could also verify that the arguments being // work for the `enum`, instead of just looking if it takes *any*. @@ -1281,49 +1284,56 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); return; } - let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else { + let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) + else { err.note(msg); return; }; - let (qself_sugg_span, is_self) = if let hir::TyKind::Path( - hir::QPath::Resolved(_, path) - ) = &qself.kind { - // If the path segment already has type params, we want to overwrite - // them. - match &path.segments { - // `segment` is the previous to last element on the path, - // which would normally be the `enum` itself, while the last - // `_` `PathSegment` corresponds to the variant. - [.., hir::PathSegment { - ident, - args, - res: Res::Def(DefKind::Enum, _), - .. - }, _] => ( - // We need to include the `::` in `Type::Variant::` - // to point the span to `::`, not just ``. - ident.span.shrink_to_hi().to(args.map_or( - ident.span.shrink_to_hi(), - |a| a.span_ext)), - false, - ), - [segment] => ( - // We need to include the `::` in `Type::Variant::` - // to point the span to `::`, not just ``. - segment.ident.span.shrink_to_hi().to(segment.args.map_or( - segment.ident.span.shrink_to_hi(), - |a| a.span_ext)), - kw::SelfUpper == segment.ident.name, - ), - _ => { - err.note(msg); - return; + let (qself_sugg_span, is_self) = + if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = + &qself.kind + { + // If the path segment already has type params, we want to overwrite + // them. + match &path.segments { + // `segment` is the previous to last element on the path, + // which would normally be the `enum` itself, while the last + // `_` `PathSegment` corresponds to the variant. + [ + .., + hir::PathSegment { + ident, + args, + res: Res::Def(DefKind::Enum, _), + .. + }, + _, + ] => ( + // We need to include the `::` in `Type::Variant::` + // to point the span to `::`, not just ``. + ident.span.shrink_to_hi().to(args + .map_or(ident.span.shrink_to_hi(), |a| a.span_ext)), + false, + ), + [segment] => ( + // We need to include the `::` in `Type::Variant::` + // to point the span to `::`, not just ``. + segment.ident.span.shrink_to_hi().to(segment + .args + .map_or(segment.ident.span.shrink_to_hi(), |a| { + a.span_ext + })), + kw::SelfUpper == segment.ident.name, + ), + _ => { + err.note(msg); + return; + } } - } - } else { - err.note(msg); - return; - }; + } else { + err.note(msg); + return; + }; let suggestion = vec![ if is_self { // Account for people writing `Self::Variant::`, where @@ -1455,7 +1465,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }; let trait_did = bound.def_id(); - let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else { + let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) + else { // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let msg = format!("found associated const `{assoc_ident}` when type was expected"); @@ -1814,7 +1825,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { debug!("qpath_to_ty: self.item_def_id()={:?}", def_id); - let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) + let parent_def_id = def_id + .as_local() + .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id()); debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id); @@ -1850,7 +1863,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &[path_str], item_segment.ident.name, ); - return Ty::new_error(tcx,reported) + return Ty::new_error(tcx, reported); }; debug!("qpath_to_ty: self_type={:?}", self_ty); @@ -2688,7 +2701,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let hir = tcx.hir(); let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) = - hir.get(fn_hir_id) else { return None }; + hir.get(fn_hir_id) + else { + return None; + }; let i = hir.get_parent(fn_hir_id).expect_item().expect_impl(); let trait_ref = self.instantiate_mono_trait_ref( diff --git a/compiler/rustc_hir_analysis/src/check/dropck.rs b/compiler/rustc_hir_analysis/src/check/dropck.rs index 13d1abe2a65..2bb4cc39f92 100644 --- a/compiler/rustc_hir_analysis/src/check/dropck.rs +++ b/compiler/rustc_hir_analysis/src/check/dropck.rs @@ -81,8 +81,9 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( self_type_did: DefId, adt_to_impl_substs: SubstsRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_substs, CheckRegions::OnlyEarlyBound) else { - return Ok(()) + let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_substs, CheckRegions::OnlyEarlyBound) + else { + return Ok(()); }; let drop_impl_span = tcx.def_span(drop_impl_did); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index 0bb1467ef31..15be441e947 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -186,18 +186,14 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else { let msg = format!("type `{ty}` cannot be used with this register class"); let mut err = self.tcx.sess.struct_span_err(expr.span, msg); - let supported_tys: Vec<_> = - supported_tys.iter().map(|(t, _)| t.to_string()).collect(); + let supported_tys: Vec<_> = supported_tys.iter().map(|(t, _)| t.to_string()).collect(); err.note(format!( "register class `{}` supports these types: {}", reg_class.name(), supported_tys.join(", "), )); if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) { - err.help(format!( - "consider using the `{}` register class instead", - suggest.name() - )); + err.help(format!("consider using the `{}` register class instead", suggest.name())); } err.emit(); return Some(asm_ty); diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index f47df4f215b..d724dce89f4 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1282,7 +1282,9 @@ fn suggest_impl_trait<'tcx>( item_ty: Ty<'tcx>| { let trait_name = tcx.item_name(trait_def_id); let args_tuple = substs.type_at(1); - let ty::Tuple(types) = *args_tuple.kind() else { return None; }; + let ty::Tuple(types) = *args_tuple.kind() else { + return None; + }; let types = types.make_suggestable(tcx, false)?; let maybe_ret = if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") }; @@ -1315,8 +1317,12 @@ fn suggest_impl_trait<'tcx>( format_as_parenthesized, ), ] { - let Some(trait_def_id) = trait_def_id else { continue; }; - let Some(assoc_item_def_id) = assoc_item_def_id else { continue; }; + let Some(trait_def_id) = trait_def_id else { + continue; + }; + let Some(assoc_item_def_id) = assoc_item_def_id else { + continue; + }; if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy { continue; } diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 12936664130..81e4aa25427 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -66,7 +66,11 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen Some(ImplTraitInTraitData::Trait { opaque_def_id, fn_def_id }) => { let opaque_ty_id = tcx.hir().local_def_id_to_hir_id(opaque_def_id.expect_local()); let opaque_ty_node = tcx.hir().get(opaque_ty_id); - let Node::Item(&Item { kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping, .. }), .. }) = opaque_ty_node else { + let Node::Item(&Item { + kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping, .. }), + .. + }) = opaque_ty_node + else { bug!("unexpected {opaque_ty_node:?}") }; @@ -397,7 +401,9 @@ fn compute_bidirectional_outlives_predicates<'tcx>( continue; } - let Some(dup_index) = generics.param_def_id_to_index(icx.tcx, dup_def.to_def_id()) else { bug!() }; + let Some(dup_index) = generics.param_def_id_to_index(icx.tcx, dup_def.to_def_id()) else { + bug!() + }; let dup_region = ty::Region::new_early_bound( tcx, diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index acd0bcd8e5c..c0eba18f838 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -749,9 +749,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { // `fn foo<'a>() -> MyAnonTy<'a> { ... }` // ^ ^this gets resolved in the current scope for lifetime in lifetimes { - let hir::GenericArg::Lifetime(lifetime) = lifetime else { - continue - }; + let hir::GenericArg::Lifetime(lifetime) = lifetime else { continue }; self.visit_lifetime(lifetime); // Check for predicates like `impl for<'a> Trait>` @@ -759,12 +757,8 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { // well-supported at the moment, so this doesn't work. // In the future, this should be fixed and this error should be removed. let def = self.map.defs.get(&lifetime.hir_id).cloned(); - let Some(ResolvedArg::LateBound(_, _, def_id)) = def else { - continue - }; - let Some(def_id) = def_id.as_local() else { - continue - }; + let Some(ResolvedArg::LateBound(_, _, def_id)) = def else { continue }; + let Some(def_id) = def_id.as_local() else { continue }; let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); // Ensure that the parent of the def is an item, not HRTB let parent_id = self.tcx.hir().parent_id(hir_id); diff --git a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs index ee3457282d3..0828fe9e0f2 100644 --- a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs @@ -360,9 +360,11 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { &[] }; ret.extend(params.iter().filter_map(|p| { - let hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } - = p.kind - else { return None }; + let hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } = + p.kind + else { + return None; + }; let hir::ParamName::Plain(name) = p.name else { return None }; Some(name.to_string()) })); @@ -793,29 +795,36 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { num_trait_generics_except_self: usize, ) { let sm = self.tcx.sess.source_map(); - let hir::ExprKind::MethodCall(_, rcvr, args, _) = expr.kind else { return; }; + let hir::ExprKind::MethodCall(_, rcvr, args, _) = expr.kind else { + return; + }; if num_assoc_fn_excess_args != num_trait_generics_except_self { return; } - let Some(gen_args) = self.gen_args.span_ext() else { return; }; - let Ok(generics) = sm.span_to_snippet(gen_args) else { return; }; - let Ok(rcvr) = sm.span_to_snippet( - rcvr.span.find_ancestor_inside(expr.span).unwrap_or(rcvr.span) - ) else { return; }; - let Ok(rest) = - (match args { - [] => Ok(String::new()), - [arg] => sm.span_to_snippet( - arg.span.find_ancestor_inside(expr.span).unwrap_or(arg.span), - ), - [first, .., last] => { - let first_span = - first.span.find_ancestor_inside(expr.span).unwrap_or(first.span); - let last_span = - last.span.find_ancestor_inside(expr.span).unwrap_or(last.span); - sm.span_to_snippet(first_span.to(last_span)) - } - }) else { return; }; + let Some(gen_args) = self.gen_args.span_ext() else { + return; + }; + let Ok(generics) = sm.span_to_snippet(gen_args) else { + return; + }; + let Ok(rcvr) = + sm.span_to_snippet(rcvr.span.find_ancestor_inside(expr.span).unwrap_or(rcvr.span)) + else { + return; + }; + let Ok(rest) = (match args { + [] => Ok(String::new()), + [arg] => { + sm.span_to_snippet(arg.span.find_ancestor_inside(expr.span).unwrap_or(arg.span)) + } + [first, .., last] => { + let first_span = first.span.find_ancestor_inside(expr.span).unwrap_or(first.span); + let last_span = last.span.find_ancestor_inside(expr.span).unwrap_or(last.span); + sm.span_to_snippet(first_span.to(last_span)) + } + }) else { + return; + }; let comma = if args.len() > 0 { ", " } else { "" }; let trait_path = self.tcx.def_path_str(trait_def_id); let method_name = self.tcx.item_name(self.def_id); diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index e8720a5da02..6a27e78c594 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -188,11 +188,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir = self.tcx.hir(); // First, check that we're actually in the tail of a function. - let Some(body_id) = hir.maybe_body_owned_by(self.body_id) else { return; }; + let Some(body_id) = hir.maybe_body_owned_by(self.body_id) else { + return; + }; let body = hir.body(body_id); - let hir::ExprKind::Block(block, _) = body.value.kind else { return; }; - let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. }) - = block.innermost_block().stmts.last() else { return; }; + let hir::ExprKind::Block(block, _) = body.value.kind else { + return; + }; + let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. }) = + block.innermost_block().stmts.last() + else { + return; + }; if last_expr.hir_id != expr.hir_id { return; } @@ -201,7 +208,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(ret) = hir .find_by_def_id(self.body_id) .and_then(|owner| owner.fn_decl()) - .map(|decl| decl.output.span()) else { return; }; + .map(|decl| decl.output.span()) + else { + return; + }; let Expectation::IsLast(stmt) = expectation else { return; }; @@ -508,9 +518,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span, kind: TypeVariableOriginKind::OpaqueTypeInference(rpit_def_id), .. - } = self.type_var_origin(expected)? else { return None; }; + } = self.type_var_origin(expected)? + else { + return None; + }; - let Some(rpit_local_def_id) = rpit_def_id.as_local() else { return None; }; + let Some(rpit_local_def_id) = rpit_def_id.as_local() else { + return None; + }; if !matches!( self.tcx.hir().expect_item(rpit_local_def_id).expect_opaque_ty().origin, hir::OpaqueTyOrigin::FnReturn(..) diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index f306653c1ab..eb695d6b859 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -499,15 +499,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) { if let [callee_expr, rest @ ..] = arg_exprs { - let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr) else { + let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr) + else { return; }; // First, do a probe with `IsSuggestion(true)` to avoid emitting // any strange errors. If it's successful, then we'll do a true // method lookup. - let Ok(pick) = self - .lookup_probe_for_diagnostic( + let Ok(pick) = self.lookup_probe_for_diagnostic( segment.ident, callee_ty, call_expr, diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index dc58d99ed9d..c03267787cb 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1670,7 +1670,9 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { expr: &hir::Expr<'tcx>, ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>, ) { - let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { return;}; + let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { + return; + }; let mut span: MultiSpan = vec![loop_span].into(); span.push_span_label(loop_span, "this might have zero elements to iterate on"); const MAXITER: usize = 3; diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index cc8198aab25..80db01e08db 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -102,7 +102,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found_expr: &mut &'tcx hir::Expr<'tcx>, expected_expr: &mut Option<&'tcx hir::Expr<'tcx>>, ) { - let Some(expected_expr) = expected_expr else { return; }; + let Some(expected_expr) = expected_expr else { + return; + }; if !found_expr.span.eq_ctxt(expected_expr.span) { return; @@ -121,11 +123,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir::ExprKind::Unary( hir::UnOp::Deref, hir::Expr { kind: hir::ExprKind::Path(found_path), .. }, - ) = found_expr.kind else { return; }; + ) = found_expr.kind + else { + return; + }; let hir::ExprKind::Unary( hir::UnOp::Deref, hir::Expr { kind: hir::ExprKind::Path(expected_path), .. }, - ) = expected_expr.kind else { return; }; + ) = expected_expr.kind + else { + return; + }; for (path, name, idx, var) in [ (expected_path, "left_val", 0, expected_expr), @@ -285,16 +293,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> bool { let hir = self.tcx.hir(); - let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { return false; }; - let [hir::PathSegment { ident, args: None, .. }] = p.segments else { return false; }; - let hir::def::Res::Local(local_hir_id) = p.res else { return false; }; - let hir::Node::Pat(pat) = hir.get(local_hir_id) else { return false; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { + return false; + }; + let [hir::PathSegment { ident, args: None, .. }] = p.segments else { + return false; + }; + let hir::def::Res::Local(local_hir_id) = p.res else { + return false; + }; + let hir::Node::Pat(pat) = hir.get(local_hir_id) else { + return false; + }; let (init_ty_hir_id, init) = match hir.get_parent(pat.hir_id) { hir::Node::Local(hir::Local { ty: Some(ty), init, .. }) => (ty.hir_id, *init), hir::Node::Local(hir::Local { init: Some(init), .. }) => (init.hir_id, Some(*init)), _ => return false, }; - let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else { return false; }; + let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else { + return false; + }; // Locate all the usages of the relevant binding. struct FindExprs<'tcx> { @@ -413,14 +431,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Bindings always update their recorded type after the fact, so we // need to look at the *following* usage's type to see when the // binding became incompatible. - let [binding, next_usage] = *window else { continue; }; + let [binding, next_usage] = *window else { + continue; + }; // Don't go past the binding (always gonna be a nonsense label if so) if binding.hir_id == expr.hir_id { break; } - let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { continue; }; + let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { + continue; + }; // If the type is not constrained in a way making it not possible to // equate with `expected_ty` by this point, skip. @@ -634,27 +656,36 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { error: Option>, ) { let parent = self.tcx.hir().parent_id(expr.hir_id); - let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;}; - let Some(hir::Node::Expr(hir::Expr { - kind: hir::ExprKind::Assign(lhs, rhs, _), .. - })) = self.tcx.hir().find(parent) else {return; }; + let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else { + return; + }; + let Some(hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. })) = + self.tcx.hir().find(parent) + else { + return; + }; if rhs.hir_id != expr.hir_id || expected.is_closure() { return; } - let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; }; - let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; }; - let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; }; + let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { + return; + }; + let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { + return; + }; + let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { + return; + }; - let Ok(pick) = self - .lookup_probe_for_diagnostic( - path.ident, - self_ty, - deref, - probe::ProbeScope::TraitsInScope, - None, - ) else { - return; - }; + let Ok(pick) = self.lookup_probe_for_diagnostic( + path.ident, + self_ty, + deref, + probe::ProbeScope::TraitsInScope, + None, + ) else { + return; + }; let in_scope_methods = self.probe_for_name_many( probe::Mode::MethodCall, path.ident, @@ -793,8 +824,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { - let ty::Adt(e, substs_e) = expected.kind() else { return false; }; - let ty::Adt(f, substs_f) = found.kind() else { return false; }; + let ty::Adt(e, substs_e) = expected.kind() else { + return false; + }; + let ty::Adt(f, substs_f) = found.kind() else { + return false; + }; if e.did() != f.did() { return false; } @@ -1039,7 +1074,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // In case Option is wanted, but * is provided, suggest calling new ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => { // Unwrap option - let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; }; + let ty::Adt(adt, _) = substs.type_at(0).kind() else { + return false; + }; (adt, "") } @@ -1061,10 +1098,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (sym::NonZeroI128, tcx.types.i128), ]; - let Some((s, _)) = map - .iter() - .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t)) - else { return false; }; + let Some((s, _)) = map.iter().find(|&&(s, t)| { + self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t) + }) else { + return false; + }; let path = self.tcx.def_path_str(adt.non_enum_variant().def_id); @@ -1152,7 +1190,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let local_parent = self.tcx.hir().parent_id(local_id); - let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else { + let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = + self.tcx.hir().find(local_parent) + else { return None; }; @@ -1161,7 +1201,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir_id: expr_hir_id, kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }), .. - })) = self.tcx.hir().find(param_parent) else { + })) = self.tcx.hir().find(param_parent) + else { return None; }; @@ -1174,7 +1215,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .. })), 1, - ) = (hir, closure_params_len) else { + ) = (hir, closure_params_len) + else { return None; }; @@ -2028,11 +2070,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !hir::is_range_literal(expr) { return; } - let hir::ExprKind::Struct( - hir::QPath::LangItem(LangItem::Range, ..), - [start, end], - _, - ) = expr.kind else { return; }; + let hir::ExprKind::Struct(hir::QPath::LangItem(LangItem::Range, ..), [start, end], _) = + expr.kind + else { + return; + }; let parent = self.tcx.hir().parent_id(expr.hir_id); if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) { // Ignore `Foo { field: a..Default::default() }` @@ -2048,8 +2090,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // cannot guide the method probe. expectation = None; } - let hir::ExprKind::Call(method_name, _) = expr.kind else { return; }; - let ty::Adt(adt, _) = checked_ty.kind() else { return; }; + let hir::ExprKind::Call(method_name, _) = expr.kind else { + return; + }; + let ty::Adt(adt, _) = checked_ty.kind() else { + return; + }; if self.tcx.lang_items().range_struct() != Some(adt.did()) { return; } @@ -2059,8 +2105,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } // Check if start has method named end. - let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; }; - let [hir::PathSegment { ident, .. }] = p.segments else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { + return; + }; + let [hir::PathSegment { ident, .. }] = p.segments else { + return; + }; let self_ty = self.typeck_results.borrow().expr_ty(start.expr); let Ok(_pick) = self.lookup_probe_for_diagnostic( *ident, @@ -2068,7 +2118,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr, probe::ProbeScope::AllTraits, expectation, - ) else { return; }; + ) else { + return; + }; let mut sugg = "."; let mut span = start.expr.span.between(end.expr.span); if span.lo() + BytePos(2) == span.hi() { @@ -2097,17 +2149,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !checked_ty.is_unit() { return; } - let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; }; - let hir::def::Res::Local(hir_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { + return; + }; + let hir::def::Res::Local(hir_id) = path.res else { + return; + }; let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { return; }; - let Some(hir::Node::Local(hir::Local { - ty: None, - init: Some(init), - .. - })) = self.tcx.hir().find_parent(pat.hir_id) else { return; }; - let hir::ExprKind::Block(block, None) = init.kind else { return; }; + let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = + self.tcx.hir().find_parent(pat.hir_id) + else { + return; + }; + let hir::ExprKind::Block(block, None) = init.kind else { + return; + }; if block.expr.is_some() { return; } @@ -2115,8 +2173,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(block.span, "this empty block is missing a tail expression"); return; }; - let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; }; - let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else { return; }; + let hir::StmtKind::Semi(tail_expr) = stmt.kind else { + return; + }; + let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else { + return; + }; if self.can_eq(self.param_env, expected_ty, ty) { err.span_suggestion_short( stmt.span.with_lo(tail_expr.span.hi()), @@ -2135,7 +2197,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, checked_ty: Ty<'tcx>, ) { - let Some(hir::Node::Expr(parent_expr)) = self.tcx.hir().find_parent(expr.hir_id) else { return; }; + let Some(hir::Node::Expr(parent_expr)) = self.tcx.hir().find_parent(expr.hir_id) else { + return; + }; enum CallableKind { Function, Method, @@ -2151,7 +2215,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 }) else { return; }; + let Some(&arg) = fn_sig + .inputs() + .get(arg_idx + if matches!(kind, CallableKind::Method) { 1 } else { 0 }) + else { + return; + }; if matches!(arg.kind(), ty::Param(_)) && fn_sig.output().contains(arg) && self.node_ty(args[arg_idx].hir_id) == checked_ty @@ -2185,8 +2254,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; match parent_expr.kind { hir::ExprKind::Call(fun, args) => { - let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else { return; }; - let hir::def::Res::Def(kind, def_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else { + return; + }; + let hir::def::Res::Def(kind, def_id) = path.res else { + return; + }; let callable_kind = if matches!(kind, hir::def::DefKind::Ctor(_, _)) { CallableKind::Constructor } else { @@ -2195,7 +2268,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { maybe_emit_help(def_id, path.segments[0].ident, args, callable_kind); } hir::ExprKind::MethodCall(method, _receiver, args, _span) => { - let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id) else { return; }; + let Some(def_id) = + self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id) + else { + return; + }; maybe_emit_help(def_id, method.ident, args, CallableKind::Method) } _ => return, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 72b29f7b6e9..6e3c117dd9e 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -650,7 +650,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else { // Avoid ICE when `break` is inside a closure (#65383). - return Ty::new_error_with_message(tcx, + return Ty::new_error_with_message( + tcx, expr.span, "break was outside loop, but no error was emitted", ); @@ -1390,11 +1391,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let parent_node = self.tcx.hir().parent_iter(expr.hir_id).find(|(_, node)| { !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. })) }); - let Some((_, + let Some(( + _, hir::Node::Local(hir::Local { ty: Some(ty), .. }) - | hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. })) - ) = parent_node else { - return + | hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }), + )) = parent_node + else { + return; }; if let hir::TyKind::Array(_, length) = ty.peel_refs().kind && let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length @@ -2416,7 +2419,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { base: &'tcx hir::Expr<'tcx>, ty: Ty<'tcx>, ) { - let Some(output_ty) = self.get_impl_future_output_ty(ty) else { return; }; + let Some(output_ty) = self.get_impl_future_output_ty(ty) else { + return; + }; let mut add_label = true; if let ty::Adt(def, _) = output_ty.kind() { // no field access on enum type 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 ed9bb4945af..b3ee284d8d7 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 @@ -14,14 +14,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, error: &mut traits::FulfillmentError<'tcx>, ) -> bool { - let (traits::ExprItemObligation(def_id, hir_id, idx) | traits::ExprBindingObligation(def_id, _, hir_id, idx)) - = *error.obligation.cause.code().peel_derives() else { return false; }; + let (traits::ExprItemObligation(def_id, hir_id, idx) + | traits::ExprBindingObligation(def_id, _, hir_id, idx)) = + *error.obligation.cause.code().peel_derives() + else { + return false; + }; let hir = self.tcx.hir(); - let hir::Node::Expr(expr) = hir.get(hir_id) else { return false; }; + let hir::Node::Expr(expr) = hir.get(hir_id) else { + return false; + }; - let Some(unsubstituted_pred) = - self.tcx.predicates_of(def_id).instantiate_identity(self.tcx).predicates.into_iter().nth(idx) - else { return false; }; + let Some(unsubstituted_pred) = self + .tcx + .predicates_of(def_id) + .instantiate_identity(self.tcx) + .predicates + .into_iter() + .nth(idx) + else { + return false; + }; let generics = self.tcx.generics_of(def_id); let predicate_substs = match unsubstituted_pred.kind().skip_binder() { @@ -229,14 +242,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .generics_of(def_id) .own_substs(ty::InternalSubsts::identity_for_item(self.tcx, def_id)); - let Some((index, _)) = own_substs - .iter() - .enumerate() - .find(|(_, arg)| **arg == param_to_point_at) else { return false }; - let Some(arg) = segment - .args() - .args - .get(index) else { return false; }; + let Some((index, _)) = + own_substs.iter().enumerate().find(|(_, arg)| **arg == param_to_point_at) + else { + return false; + }; + let Some(arg) = segment.args().args.get(index) else { + return false; + }; error.obligation.cause.span = arg .span() .find_ancestor_in_same_ctxt(error.obligation.cause.span) @@ -573,9 +586,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Find out which of `in_ty_elements` refer to `param`. // FIXME: It may be better to take the first if there are multiple, // just so that the error points to a smaller expression. - let Some((drill_expr, drill_ty)) = is_iterator_singleton(expr_elements.iter().zip( in_ty_elements.iter()).filter(|(_expr_elem, in_ty_elem)| { - find_param_in_ty((*in_ty_elem).into(), param) - })) else { + let Some((drill_expr, drill_ty)) = + is_iterator_singleton(expr_elements.iter().zip(in_ty_elements.iter()).filter( + |(_expr_elem, in_ty_elem)| find_param_in_ty((*in_ty_elem).into(), param), + )) + else { // The param is not mentioned, or it is mentioned in multiple indexes. return Err(expr); }; @@ -594,7 +609,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // First, confirm that this struct is the same one as in the types, and if so, // find the right variant. - let Res::Def(expr_struct_def_kind, expr_struct_def_id) = self.typeck_results.borrow().qpath_res(expr_struct_path, expr.hir_id) else { + let Res::Def(expr_struct_def_kind, expr_struct_def_id) = + self.typeck_results.borrow().qpath_res(expr_struct_path, expr.hir_id) + else { return Err(expr); }; @@ -621,16 +638,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We need to know which of the generic parameters mentions our target param. // We expect that at least one of them does, since it is expected to be mentioned. - let Some((drill_generic_index, generic_argument_type)) = - is_iterator_singleton( - in_ty_adt_generic_args.iter().enumerate().filter( - |(_index, in_ty_generic)| { - find_param_in_ty(*in_ty_generic, param) - }, - ), - ) else { - return Err(expr); - }; + let Some((drill_generic_index, generic_argument_type)) = is_iterator_singleton( + in_ty_adt_generic_args + .iter() + .enumerate() + .filter(|(_index, in_ty_generic)| find_param_in_ty(*in_ty_generic, param)), + ) else { + return Err(expr); + }; let struct_generic_parameters: &ty::Generics = self.tcx.generics_of(in_ty_adt.did()); if drill_generic_index >= struct_generic_parameters.params.len() { @@ -703,7 +718,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // This is (possibly) a constructor call, like `Some(...)` or `MyStruct(a, b, c)`. - let Res::Def(expr_struct_def_kind, expr_ctor_def_id) = self.typeck_results.borrow().qpath_res(expr_callee_path, expr_callee.hir_id) else { + let Res::Def(expr_struct_def_kind, expr_ctor_def_id) = + self.typeck_results.borrow().qpath_res(expr_callee_path, expr_callee.hir_id) + else { return Err(expr); }; @@ -744,16 +761,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We need to know which of the generic parameters mentions our target param. // We expect that at least one of them does, since it is expected to be mentioned. - let Some((drill_generic_index, generic_argument_type)) = - is_iterator_singleton( - in_ty_adt_generic_args.iter().enumerate().filter( - |(_index, in_ty_generic)| { - find_param_in_ty(*in_ty_generic, param) - }, - ), - ) else { - return Err(expr); - }; + let Some((drill_generic_index, generic_argument_type)) = is_iterator_singleton( + in_ty_adt_generic_args + .iter() + .enumerate() + .filter(|(_index, in_ty_generic)| find_param_in_ty(*in_ty_generic, param)), + ) else { + return Err(expr); + }; let struct_generic_parameters: &ty::Generics = self.tcx.generics_of(in_ty_adt.did()); if drill_generic_index >= struct_generic_parameters.params.len() { @@ -794,7 +809,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .map(|field| field.ty(self.tcx, *in_ty_adt_generic_args)) .enumerate() - .filter(|(_index, field_type)| find_param_in_ty((*field_type).into(), param)) + .filter(|(_index, field_type)| find_param_in_ty((*field_type).into(), param)), ) else { return Err(expr); }; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 41f5fafe72f..5c5aef33413 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -753,11 +753,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } errors.retain(|error| { - let Error::Invalid( - provided_idx, - expected_idx, - Compatibility::Incompatible(Some(e)), - ) = error else { return true }; + let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(e))) = + error + else { + return true; + }; let (provided_ty, provided_span) = provided_arg_tys[*provided_idx]; let trace = mk_trace(provided_span, formal_and_expected_inputs[*expected_idx], provided_ty); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 79a7c016185..5d80137f212 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -97,8 +97,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>) -> bool, ) -> bool { - let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) - else { return false; }; + let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) else { + return false; + }; if can_satisfy(output) { let (sugg_call, mut applicability) = match inputs.len() { 0 => ("".to_string(), Applicability::MachineApplicable), @@ -180,10 +181,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { rhs_ty: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool, ) -> bool { - let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) - else { return false; }; - let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) - else { return false; }; + let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) else { + return false; + }; + let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) else { + return false; + }; if can_satisfy(lhs_output_ty, rhs_output_ty) { let mut sugg = vec![]; @@ -635,7 +638,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // is and we were expecting a Box, ergo Pin>, we // can suggest Box::pin. let parent = self.tcx.hir().parent_id(expr.hir_id); - let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else { + let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = + self.tcx.hir().find(parent) + else { return false; }; match fn_name.kind { @@ -850,12 +855,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn( - hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. }, + hir::FnSig { + decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, + .. + }, hir::Generics { params, predicates, .. }, _body_id, ), .. - })) = fn_node else { return }; + })) = fn_node + else { + return; + }; if params.get(expected_ty_as_param.index as usize).is_none() { return; @@ -1081,8 +1092,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool { - let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; }; - let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; }; + let ty::Adt(adt_def, substs) = expr_ty.kind() else { + return false; + }; + let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { + return false; + }; if adt_def != expected_adt_def { return false; } @@ -1205,7 +1220,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return false; } - let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; }; + let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { + return false; + }; if !self.tcx.is_diagnostic_item(sym::Option, def.did()) { return false; } @@ -1327,7 +1344,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed), span, }) => { - let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(*span) else { return false; }; + let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(*span) else { + return false; + }; if !(snippet.starts_with("0x") || snippet.starts_with("0X")) { return false; } @@ -1367,10 +1386,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Provided expression needs to be a literal `0`. - let ExprKind::Lit(Spanned { - node: rustc_ast::LitKind::Int(0, _), - span, - }) = expr.kind else { + let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(0, _), span }) = expr.kind else { return false; }; @@ -1401,7 +1417,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, expected_ty: Ty<'tcx>, ) -> bool { - let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else { + let Some((DefKind::AssocFn, old_def_id)) = + self.typeck_results.borrow().type_dependent_def(expr.hir_id) + else { return false; }; let old_item_name = self.tcx.item_name(old_def_id); @@ -1494,8 +1512,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found_ty: Ty<'tcx>, expr: &hir::Expr<'_>, ) { - let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; }; - let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; }; + let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { + return; + }; + let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { + return; + }; let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return }; let results = self.typeck_results.borrow(); // First, look for a `Clone::clone` call diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 87edb803148..168eb3a6cdc 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -171,7 +171,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // time writing the results into the various typeck results. let mut autoderef = self.autoderef(self.call_expr.span, unadjusted_self_ty); let Some((ty, n)) = autoderef.nth(pick.autoderefs) else { - return Ty::new_error_with_message(self.tcx, + return Ty::new_error_with_message( + self.tcx, rustc_span::DUMMY_SP, format!("failed autoderef {}", pick.autoderefs), ); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 03a3eebbdf5..45c9f15c0d5 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1938,13 +1938,21 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { /// Determine if the associated item withe the given DefId matches /// the desired name via a doc alias. fn matches_by_doc_alias(&self, def_id: DefId) -> bool { - let Some(name) = self.method_name else { return false; }; - let Some(local_def_id) = def_id.as_local() else { return false; }; + let Some(name) = self.method_name else { + return false; + }; + let Some(local_def_id) = def_id.as_local() else { + return false; + }; let hir_id = self.fcx.tcx.hir().local_def_id_to_hir_id(local_def_id); let attrs = self.fcx.tcx.hir().attrs(hir_id); for attr in attrs { - let sym::doc = attr.name_or_empty() else { continue; }; - let Some(values) = attr.meta_item_list() else { continue; }; + let sym::doc = attr.name_or_empty() else { + continue; + }; + let Some(values) = attr.meta_item_list() else { + continue; + }; for v in values { if v.name_or_empty() != sym::alias { continue; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 5f924f30936..7bdbcc56da4 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1699,10 +1699,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// we try to suggest `rect.area()` pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) { debug!("suggest_assoc_method_call segs: {:?}", segs); - let [seg1, seg2] = segs else { return; }; + let [seg1, seg2] = segs else { + return; + }; let Some(mut diag) = - self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod) - else { return }; + self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod) + else { + return; + }; let map = self.infcx.tcx.hir(); let body_id = self.tcx.hir().body_owned_by(self.body_id); @@ -1839,17 +1843,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item_name: Ident, ) { let tcx = self.tcx; - let SelfSource::MethodCall(expr) = source else { return; }; + let SelfSource::MethodCall(expr) = source else { + return; + }; let call_expr = tcx.hir().expect_expr(tcx.hir().parent_id(expr.hir_id)); - let ty::Adt(kind, substs) = actual.kind() else { return; }; + let ty::Adt(kind, substs) = actual.kind() else { + return; + }; match kind.adt_kind() { ty::AdtKind::Enum => { let matching_variants: Vec<_> = kind .variants() .iter() .flat_map(|variant| { - let [field] = &variant.fields.raw[..] else { return None; }; + let [field] = &variant.fields.raw[..] else { + return None; + }; let field_ty = field.ty(tcx, substs); // Skip `_`, since that'll just lead to ambiguity. @@ -1927,15 +1937,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Target wrapper types - types that wrap or pretend to wrap another type, // perhaps this inner type is meant to be called? ty::AdtKind::Struct | ty::AdtKind::Union => { - let [first] = ***substs else { return; }; - let ty::GenericArgKind::Type(ty) = first.unpack() else { return; }; + let [first] = ***substs else { + return; + }; + let ty::GenericArgKind::Type(ty) = first.unpack() else { + return; + }; let Ok(pick) = self.lookup_probe_for_diagnostic( item_name, ty, call_expr, ProbeScope::TraitsInScope, None, - ) else { return; }; + ) else { + return; + }; let name = self.ty_to_value_string(actual); let inner_id = kind.did(); @@ -2100,7 +2116,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) = pred.kind().no_bound_vars() else { - continue + continue; }; let adt = match trait_pred.self_ty().ty_adt_def() { Some(adt) if adt.did().is_local() => adt, @@ -2197,7 +2213,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item_name: Ident, expected: Expectation<'tcx>, ) { - let SelfSource::QPath(ty) = self_source else { return; }; + let SelfSource::QPath(ty) = self_source else { + return; + }; for (deref_ty, _) in self.autoderef(rustc_span::DUMMY_SP, rcvr_ty).skip(1) { if let Ok(pick) = self.probe_for_name( Mode::Path, @@ -2834,9 +2852,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found: Ty<'tcx>, expected: Ty<'tcx>, ) -> bool { - let Some((_def_id_or_name, output, _inputs)) = - self.extract_callable_info(found) else { - return false; + let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else { + return false; }; if !self.can_coerce(output, expected) { diff --git a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index 22c9e796107..091e88abe97 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -74,9 +74,7 @@ pub fn resolve_rvalue_scopes<'a, 'tcx>( debug!("start resolving rvalue scopes, def_id={def_id:?}"); debug!("rvalue_scope: rvalue_candidates={:?}", scope_tree.rvalue_candidates); for (&hir_id, candidate) in &scope_tree.rvalue_candidates { - let Some(Node::Expr(expr)) = hir_map.find(hir_id) else { - bug!("hir node does not exist") - }; + let Some(Node::Expr(expr)) = hir_map.find(hir_id) else { bug!("hir node does not exist") }; record_rvalue_scope(&mut rvalue_scopes, expr, candidate); } rvalue_scopes diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 208c40a3932..93ef0d6ff53 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -644,7 +644,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for capture in captures { match capture.info.capture_kind { ty::UpvarCapture::ByRef(_) => { - let PlaceBase::Upvar(upvar_id) = capture.place.base else { bug!("expected upvar") }; + let PlaceBase::Upvar(upvar_id) = capture.place.base else { + bug!("expected upvar") + }; let origin = UpvarRegion(upvar_id, closure_span); let upvar_region = self.next_region_var(origin); capture.region = Some(upvar_region); @@ -1064,14 +1066,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // ``` debug!("no path starting from it is used"); - match closure_clause { // Only migrate if closure is a move closure hir::CaptureBy::Value => { let mut diagnostics_info = FxHashSet::default(); - let upvars = self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar"); + let upvars = + self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar"); let upvar = upvars[&var_hir_id]; - diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span }); + diagnostics_info + .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span }); return Some(diagnostics_info); } hir::CaptureBy::Ref => {} diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 7708deecec7..929a1e149b6 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -730,13 +730,13 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { debug!("garbage_collect_session_directories() - inspecting: {}", directory_name); let Ok(timestamp) = extract_timestamp_from_session_dir(directory_name) else { - debug!( - "found session-dir with malformed timestamp: {}", - crate_directory.join(directory_name).display() - ); - // Ignore it - return None; - }; + debug!( + "found session-dir with malformed timestamp: {}", + crate_directory.join(directory_name).display() + ); + // Ignore it + return None; + }; if is_finalized(directory_name) { let lock_file_path = crate_directory.join(lock_file_name); diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index 15bc3b4e388..12a7ecf8133 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -804,9 +804,7 @@ impl<'a, T: Idx> Iterator for ChunkedBitIter<'a, T> { // advance the iterator to the start of the next chunk, before proceeding in chunk sized // steps. while self.index % CHUNK_BITS != 0 { - let Some(item) = self.next() else { - return init - }; + let Some(item) = self.next() else { return init }; init = f(init, item); } let start_chunk = self.index / CHUNK_BITS; diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index 7e1fa08f23a..1ffa8633afd 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -363,7 +363,8 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { let ( hir::Ty { kind: hir::TyKind::Ref(lifetime_sub, _), .. }, hir::Ty { kind: hir::TyKind::Ref(lifetime_sup, _), .. }, - ) = (self.ty_sub, self.ty_sup) else { + ) = (self.ty_sub, self.ty_sup) + else { return false; }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index b826ced0453..37249b62e8b 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2109,14 +2109,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { found: Ty<'tcx>, expected_fields: &List>, ) -> Option { - let [expected_tup_elem] = expected_fields[..] else { return None}; + let [expected_tup_elem] = expected_fields[..] else { return None }; if !self.same_type_modulo_infer(expected_tup_elem, found) { return None; } - let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) - else { return None }; + let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) else { return None }; let sugg = if code.starts_with('(') && code.ends_with(')') { let before_close = span.hi() - BytePos::from_u32(1); diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index a90a41f5d70..d192624b17e 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -419,7 +419,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } let Some(InferSource { span, kind }) = local_visitor.infer_source else { - return self.bad_inference_failure_err(failure_span, arg_data, error_code) + return self.bad_inference_failure_err(failure_span, arg_data, error_code); }; let (source_kind, name) = kind.ty_localized_msg(self); @@ -1157,9 +1157,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { continue; } - let Some(param_ty) = self.opt_node_type(param.hir_id) else { - continue - }; + let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue }; if self.generic_arg_contains_target(param_ty.into()) { self.update_infer_source(InferSource { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs index 2c63a390410..d46dd8f3268 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs @@ -38,8 +38,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else { return None; }; - let (ObligationCauseCode::BindingObligation(_, binding_span) | ObligationCauseCode::ExprBindingObligation(_, binding_span, ..)) - = *parent.code() else { + let (ObligationCauseCode::BindingObligation(_, binding_span) + | ObligationCauseCode::ExprBindingObligation(_, binding_span, ..)) = *parent.code() + else { return None; }; @@ -67,7 +68,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, .. }), .. - }) = impl_node else { + }) = impl_node + else { bug!("Node not an impl."); }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index a9b485a6f7e..d70fea20cf4 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -503,7 +503,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { // Get the `Ident` of the method being called and the corresponding `impl` (to point at // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called). - let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &v.0) else { + let Some((ident, self_ty)) = + NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &v.0) + else { return false; }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs index e55e9e75fb6..6517b904404 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs @@ -295,12 +295,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // but right now it's not really very smart when it comes to implicit `Sized` // predicates and bounds on the trait itself. - let Some(impl_def_id) = - self.tcx.associated_item(impl_item_def_id).impl_container(self.tcx) else { return; }; - let Some(trait_ref) = self - .tcx - .impl_trait_ref(impl_def_id) - else { return; }; + let Some(impl_def_id) = self.tcx.associated_item(impl_item_def_id).impl_container(self.tcx) + else { + return; + }; + let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) else { + return; + }; let trait_substs = trait_ref .subst_identity() // Replace the explicit self type with `Self` for better suggestion rendering @@ -309,20 +310,25 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let trait_item_substs = ty::InternalSubsts::identity_for_item(self.tcx, impl_item_def_id) .rebase_onto(self.tcx, impl_def_id, trait_substs); - let Ok(trait_predicates) = self - .tcx - .explicit_predicates_of(trait_item_def_id) - .instantiate_own(self.tcx, trait_item_substs) - .map(|(pred, _)| { - if pred.is_suggestable(self.tcx, false) { - Ok(pred.to_string()) - } else { - Err(()) - } - }) - .collect::, ()>>() else { return; }; + let Ok(trait_predicates) = + self.tcx + .explicit_predicates_of(trait_item_def_id) + .instantiate_own(self.tcx, trait_item_substs) + .map(|(pred, _)| { + if pred.is_suggestable(self.tcx, false) { + Ok(pred.to_string()) + } else { + Err(()) + } + }) + .collect::, ()>>() + else { + return; + }; - let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) else { return; }; + let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) else { + return; + }; let suggestion = if trait_predicates.is_empty() { WhereClauseSuggestions::Remove { span: generics.where_clause_span } diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index b0e7cf23cae..aac2a43648b 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -526,13 +526,23 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag: &mut Diagnostic, ) { // 0. Extract fn_decl from hir - let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }), .. }) = hir else { return; }; + let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }), + .. + }) = hir + else { + return; + }; let hir::Body { params, .. } = self.tcx.hir().body(*body); // 1. Get the substs of the closure. // 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1]. - let Some(expected) = exp_found.expected.skip_binder().substs.get(1) else { return; }; - let Some(found) = exp_found.found.skip_binder().substs.get(1) else { return; }; + let Some(expected) = exp_found.expected.skip_binder().substs.get(1) else { + return; + }; + let Some(found) = exp_found.found.skip_binder().substs.get(1) else { + return; + }; let expected = expected.unpack(); let found = found.unpack(); // 3. Extract the tuple type from Fn trait and suggest the change. @@ -711,7 +721,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let hir = self.tcx.hir(); for stmt in blk.stmts.iter().rev() { - let hir::StmtKind::Local(local) = &stmt.kind else { continue; }; + let hir::StmtKind::Local(local) = &stmt.kind else { + continue; + }; local.pat.walk(&mut find_compatible_candidates); } match hir.find_parent(blk.hir_id) { diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 953c2e4b8f8..6471dce88c2 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -190,7 +190,8 @@ pub fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec) -> Check ExpectedValues::Some(FxHashSet::default()) }); - let ExpectedValues::Some(expected_values) = expected_values else { + let ExpectedValues::Some(expected_values) = expected_values + else { bug!("`expected_values` should be a list a values") }; diff --git a/compiler/rustc_lint/src/array_into_iter.rs b/compiler/rustc_lint/src/array_into_iter.rs index bccb0a94e98..d0967ba5644 100644 --- a/compiler/rustc_lint/src/array_into_iter.rs +++ b/compiler/rustc_lint/src/array_into_iter.rs @@ -81,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter { let adjustments = cx.typeck_results().expr_adjustments(receiver_arg); let Some(Adjustment { kind: Adjust::Borrow(_), target }) = adjustments.last() else { - return + return; }; let types = diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b821933e908..03835f8151c 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -793,9 +793,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { _ => return, } - let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { - return - }; + let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return }; if self.impling_types.is_none() { let mut impls = LocalDefIdSet::default(); @@ -1458,9 +1456,7 @@ impl TypeAliasBounds { impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { - return - }; + let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { return }; if cx.tcx.type_of(item.owner_id.def_id).skip_binder().has_opaque_types() { // Bounds are respected for `type X = impl Trait` and `type X = (impl Trait, Y);` return; @@ -2147,8 +2143,8 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { match predicate.bounded_ty.kind { hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { let Res::Def(DefKind::TyParam, def_id) = path.res else { - continue; - }; + continue; + }; let index = ty_generics.param_def_id_to_index[&def_id]; ( Self::lifetimes_outliving_type(inferred_outlives, index), @@ -2570,7 +2566,10 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { Some((variant, definitely_inhabited)) }); let Some(first_variant) = potential_variants.next() else { - return Some(InitError::from("enums with no inhabited variants have no valid value").spanned(span)); + return Some( + InitError::from("enums with no inhabited variants have no valid value") + .spanned(span), + ); }; // So we have at least one potentially inhabited variant. Might we have two? let Some(second_variant) = potential_variants.next() else { @@ -3181,7 +3180,7 @@ impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels { let mut chars = possible_label.chars(); let Some(c) = chars.next() else { // Empty string means a leading ':' in this section, which is not a label - break + break; }; // A label starts with an alphabetic character or . or _ and continues with alphanumeric characters, _, or $ if (c.is_alphabetic() || matches!(c, '.' | '_')) diff --git a/compiler/rustc_lint/src/cast_ref_to_mut.rs b/compiler/rustc_lint/src/cast_ref_to_mut.rs index 84308d48c10..82bb70bc9e7 100644 --- a/compiler/rustc_lint/src/cast_ref_to_mut.rs +++ b/compiler/rustc_lint/src/cast_ref_to_mut.rs @@ -37,7 +37,9 @@ declare_lint_pass!(CastRefToMut => [CAST_REF_TO_MUT]); impl<'tcx> LateLintPass<'tcx> for CastRefToMut { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else { return; }; + let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else { + return; + }; let e = e.peel_blocks(); let e = if let ExprKind::Cast(e, t) = e.kind diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index 7b58bf03bbe..71832c1b7af 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -119,7 +119,9 @@ fn suggest_question_mark<'tcx>( span: Span, ) -> bool { let Some(body_id) = cx.enclosing_body else { return false }; - let Some(into_iterator_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { return false }; + let Some(into_iterator_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { + return false; + }; if !cx.tcx.is_diagnostic_item(sym::Result, adt.did()) { return false; diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 8376835f52c..c9ee2da6fdf 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -265,7 +265,10 @@ impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> { self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur) } fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) { - let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id else { bug!("unstable expectation id should already be mapped") }; + let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id + else { + bug!("unstable expectation id should already be mapped") + }; let key = LintExpectationId::Unstable { attr_id, lint_index: None }; self.unstable_to_stable_ids.entry(key).or_insert(LintExpectationId::Stable { @@ -542,7 +545,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let Ok(ids) = self.store.find_lints(&lint_name) else { // errors handled in check_lint_name_cmdline above - continue + continue; }; for id in ids { // ForceWarn and Forbid cannot be overridden @@ -685,9 +688,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { Some(lvl) => lvl, }; - let Some(mut metas) = attr.meta_item_list() else { - continue - }; + let Some(mut metas) = attr.meta_item_list() else { continue }; if metas.is_empty() { // This emits the unused_attributes lint for `#[level()]` @@ -956,8 +957,9 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { continue; } - let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src else { - continue + let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src + else { + continue; }; self.emit_spanned_lint( diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index d56c35bb677..79430393a64 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -79,8 +79,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { // We only care about method calls corresponding to the `Clone`, `Deref` and `Borrow` // traits and ignore any other method call. - let Some((DefKind::AssocFn, did)) = - cx.typeck_results().type_dependent_def(expr.hir_id) + let Some((DefKind::AssocFn, did)) = cx.typeck_results().type_dependent_def(expr.hir_id) else { return; }; @@ -98,9 +97,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { .tcx .normalize_erasing_regions(cx.param_env, cx.typeck_results().node_substs(expr.hir_id)); // Resolve the trait method instance. - let Ok(Some(i)) = ty::Instance::resolve(cx.tcx, cx.param_env, did, substs) else { - return - }; + let Ok(Some(i)) = ty::Instance::resolve(cx.tcx, cx.param_env, did, substs) else { return }; // (Re)check that it implements the noop diagnostic. let Some(name) = cx.tcx.get_diagnostic_name(i.def_id()) else { return }; diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index 09a1651c2f5..5fd42942e30 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -68,7 +68,9 @@ declare_lint_pass!(OpaqueHiddenInferredBound => [OPAQUE_HIDDEN_INFERRED_BOUND]); impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { - let hir::ItemKind::OpaqueTy(opaque) = &item.kind else { return; }; + let hir::ItemKind::OpaqueTy(opaque) = &item.kind else { + return; + }; let def_id = item.owner_id.def_id.to_def_id(); let infcx = &cx.tcx.infer_ctxt().build(); // For every projection predicate in the opaque type's explicit bounds, @@ -116,7 +118,12 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { .subst_iter_copied(cx.tcx, &proj.projection_ty.substs) { let assoc_pred = assoc_pred.fold_with(proj_replacer); - let Ok(assoc_pred) = traits::fully_normalize(infcx, traits::ObligationCause::dummy(), cx.param_env, assoc_pred) else { + let Ok(assoc_pred) = traits::fully_normalize( + infcx, + traits::ObligationCause::dummy(), + cx.param_env, + assoc_pred, + ) else { continue; }; // If that predicate doesn't hold modulo regions (but passed during type-check), diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index de11208062d..56508a2a6cc 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { let predicates = cx.tcx.explicit_predicates_of(item.owner_id); for &(predicate, span) in predicates.predicates { let ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() else { - continue + continue; }; let def_id = trait_predicate.trait_ref.def_id; if cx.tcx.lang_items().drop_trait() == Some(def_id) { @@ -100,9 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { if trait_predicate.trait_ref.self_ty().is_impl_trait() { continue; } - let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { - return - }; + let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_spanned_lint( DROP_BOUNDS, span, @@ -113,15 +111,11 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { } fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) { - let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { - return - }; + let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { return }; for bound in &bounds[..] { let def_id = bound.trait_ref.trait_def_id(); if cx.tcx.lang_items().drop_trait() == def_id { - let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { - return - }; + let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_spanned_lint(DYN_DROP, bound.span, DropGlue { tcx: cx.tcx, def_id }); } } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 2509d493a4c..0e30d9c8604 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -560,7 +560,10 @@ fn lint_nan<'tcx>( let expr = expr.peel_blocks().peel_borrows(); match expr.kind { ExprKind::Path(qpath) => { - let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id() else { return false; }; + let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id() + else { + return false; + }; matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::f32_nan | sym::f64_nan)) } @@ -1584,10 +1587,10 @@ impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { let t = cx.tcx.type_of(it.owner_id).subst_identity(); let ty = cx.tcx.erase_regions(t); let Ok(layout) = cx.layout_of(ty) else { return }; - let Variants::Multiple { - tag_encoding: TagEncoding::Direct, tag, ref variants, .. - } = &layout.variants else { - return + let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, ref variants, .. } = + &layout.variants + else { + return; }; let tag_size = tag.size(&cx.tcx).bytes(); @@ -1760,8 +1763,13 @@ impl InvalidAtomicOrdering { } fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]) - else {return }; + let Some((method, args)) = Self::inherent_atomic_method_call( + cx, + expr, + &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak], + ) else { + return; + }; let fail_order_arg = match method { sym::fetch_update => &args[1], diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 5015b751eee..e35cc8de66f 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -94,7 +94,9 @@ declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]); impl<'tcx> LateLintPass<'tcx> for UnusedResults { fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { - let hir::StmtKind::Semi(mut expr) = s.kind else { return; }; + let hir::StmtKind::Semi(mut expr) = s.kind else { + return; + }; let mut expr_is_from_block = false; while let hir::ExprKind::Block(blk, ..) = expr.kind diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 2e6e84ad80e..e9a5cd9de97 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -203,14 +203,18 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { if first && (nested.input.is_empty() || nested.input.peek(Token![,])) { self.slug.set_once(path.clone(), path.span().unwrap()); first = false; - return Ok(()) + return Ok(()); } first = false; let Ok(nested) = nested.value() else { - span_err(nested.input.span().unwrap(), "diagnostic slug must be the first argument").emit(); - return Ok(()) + span_err( + nested.input.span().unwrap(), + "diagnostic slug must be the first argument", + ) + .emit(); + return Ok(()); }; if path.is_ident("code") { @@ -221,7 +225,9 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { #diag.code(rustc_errors::DiagnosticId::Error(#code.to_string())); }); } else { - span_err(path.span().unwrap(), "unknown argument").note("only the `code` parameter is valid after the slug").emit(); + span_err(path.span().unwrap(), "unknown argument") + .note("only the `code` parameter is valid after the slug") + .emit(); // consume the buffer so we don't have syntax errors from syn let _ = nested.parse::(); diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index e8dc986914e..877e9745054 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -188,7 +188,9 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { let mut kind_slugs = vec![]; for attr in self.variant.ast().attrs { - let Some(SubdiagnosticVariant { kind, slug, no_span }) = SubdiagnosticVariant::from_attr(attr, self)? else { + let Some(SubdiagnosticVariant { kind, slug, no_span }) = + SubdiagnosticVariant::from_attr(attr, self)? + else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. continue; diff --git a/compiler/rustc_macros/src/newtype.rs b/compiler/rustc_macros/src/newtype.rs index 415a89b0f92..72b47de1abc 100644 --- a/compiler/rustc_macros/src/newtype.rs +++ b/compiler/rustc_macros/src/newtype.rs @@ -36,7 +36,8 @@ impl Parse for Newtype { false } "max" => { - let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta else { + let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta + else { panic!("#[max = NUMBER] attribute requires max value"); }; @@ -47,7 +48,8 @@ impl Parse for Newtype { false } "debug_format" => { - let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta else { + let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta + else { panic!("#[debug_format = FMT] attribute requires a format"); }; diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index b3976d756eb..571af82d13a 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -741,7 +741,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { }; info!("panic runtime not found -- loading {}", name); - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a panic runtime @@ -774,7 +776,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore); } - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a profiler runtime diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index a89d7b464e2..a1511c4b570 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -804,8 +804,12 @@ fn get_metadata_section<'p>( } // Length of the compressed stream - this allows linkers to pad the section if they want - let Ok(len_bytes) = <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) else { - return Err(MetadataError::LoadFailure("invalid metadata length found".to_string())); + let Ok(len_bytes) = + <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) + else { + return Err(MetadataError::LoadFailure( + "invalid metadata length found".to_string(), + )); }; let compressed_len = u32::from_be_bytes(len_bytes) as usize; diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index b9318aee581..8fa1d365728 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -311,8 +311,10 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { let Some(tcx) = self.tcx else { - bug!("No TyCtxt found for decoding. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "No TyCtxt found for decoding. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; tcx } @@ -448,8 +450,10 @@ impl<'a, 'tcx> Decodable> for SyntaxContext { let cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode SyntaxContext without Session.\ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode SyntaxContext without Session.\ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cname = cdata.root.name(); @@ -470,8 +474,10 @@ impl<'a, 'tcx> Decodable> for ExpnId { let local_cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode ExpnId without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode ExpnId without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cnum = CrateNum::decode(decoder); @@ -521,8 +527,10 @@ impl<'a, 'tcx> Decodable> for Span { let hi = lo + len; let Some(sess) = decoder.sess else { - bug!("Cannot decode Span without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`.") + bug!( + "Cannot decode Span without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ) }; // Index of the file in the corresponding crate's list of encoded files. diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 01dd35b0e5b..fc1062a48b4 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1671,7 +1671,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_info_for_macro(&mut self, def_id: LocalDefId) { let tcx = self.tcx; - let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() }; + let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { + bug!() + }; self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules); record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body); } @@ -1911,7 +1913,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { FxHashMap::default(); for id in tcx.hir().items() { - let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { continue; }; + let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { + continue; + }; let def_id = id.owner_id.to_def_id(); self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id)); diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index a4313d79ab1..4287799a8e6 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -323,7 +323,7 @@ impl FixedSizeEncoding for Option> { impl LazyArray { #[inline] fn write_to_bytes_impl(self, b: &mut [u8; 8]) { - let ([position_bytes, meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks_mut::<4>() else { panic!() }; let position = self.position.get(); let position: u32 = position.try_into().unwrap(); @@ -346,7 +346,7 @@ impl FixedSizeEncoding for LazyArray { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; if *meta_bytes == [0; 4] { return Default::default(); } @@ -365,7 +365,7 @@ impl FixedSizeEncoding for Option> { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; LazyArray::from_bytes_impl(position_bytes, meta_bytes) } diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 1e43fab457e..624195cfb28 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -418,7 +418,7 @@ impl TryFrom for char { #[inline] fn try_from(int: ScalarInt) -> Result { - let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::())) else { + let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::())) else { return Err(CharTryFromScalarInt); }; match char::from_u32(bits.try_into().unwrap()) { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 638e1efa65c..c8ad9bd1830 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2713,12 +2713,16 @@ impl<'tcx> TyCtxt<'tcx> { return false; } - let Some(item) = self.opt_associated_item(def_id) else { return false; }; + let Some(item) = self.opt_associated_item(def_id) else { + return false; + }; if item.container != ty::AssocItemContainer::ImplContainer { return false; } - let Some(trait_item_def_id) = item.trait_item_def_id else { return false; }; + let Some(trait_item_def_id) = item.trait_item_def_id else { + return false; + }; return !self .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id) diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index e2e4a2dbdc8..8a83214edc7 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -358,7 +358,8 @@ impl<'tcx> TyCtxt<'tcx> { } let Some(item_id) = self.associated_item_def_ids(impl_did).first() else { - self.sess.delay_span_bug(self.def_span(impl_did), "Drop impl without drop function"); + self.sess + .delay_span_bug(self.def_span(impl_did), "Drop impl without drop function"); return; }; diff --git a/compiler/rustc_mir_build/src/build/custom/parse.rs b/compiler/rustc_mir_build/src/build/custom/parse.rs index 803207d9dc6..c494929cbff 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse.rs @@ -241,9 +241,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { }); } - let Some(trailing) = block.expr else { - return Err(self.expr_error(expr_id, "terminator")) - }; + let Some(trailing) = block.expr else { return Err(self.expr_error(expr_id, "terminator")) }; let span = self.thir[trailing].span; let terminator = self.parse_terminator(trailing)?; data.terminator = Some(Terminator { diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 4cb9d7babe1..8a841759900 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -78,7 +78,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span, item_description: "no arms".to_string(), expected: "at least one arm".to_string(), - }) + }); }; let otherwise = &self.thir[*otherwise]; @@ -87,7 +87,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span: otherwise.span, item_description: format!("{:?}", otherwise.pattern.kind), expected: "wildcard pattern".to_string(), - }) + }); }; let otherwise = self.parse_block(otherwise.body)?; @@ -100,7 +100,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span: arm.pattern.span, item_description: format!("{:?}", arm.pattern.kind), expected: "constant pattern".to_string(), - }) + }); }; values.push(value.eval_bits(self.tcx, self.param_env, arm.pattern.ty)); targets.push(self.parse_block(arm.body)?); diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 60acd279f9e..c122230b841 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -175,11 +175,8 @@ fn to_upvars_resolved_place_builder<'tcx>( projection: &[PlaceElem<'tcx>], ) -> Option> { let Some((capture_index, capture)) = - find_capture_matching_projections( - &cx.upvars, - var_hir_id, - &projection, - ) else { + find_capture_matching_projections(&cx.upvars, var_hir_id, &projection) + else { let closure_span = cx.tcx.def_span(closure_def_id); if !enable_precise_capture(closure_span) { bug!( @@ -189,10 +186,7 @@ fn to_upvars_resolved_place_builder<'tcx>( projection ) } else { - debug!( - "No associated capture found for {:?}[{:#?}]", - var_hir_id, projection, - ); + debug!("No associated capture found for {:?}[{:#?}]", var_hir_id, projection,); } return None; }; diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 10770213c9a..34e0e572a1b 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -607,9 +607,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // }; // ``` if let Some(place) = initializer.try_to_place(self) { - let LocalInfo::User(BindingForm::Var( - VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. }, - )) = **self.local_decls[local].local_info.as_mut().assert_crate_local() else { + let LocalInfo::User(BindingForm::Var(VarBindingForm { + opt_match_place: Some((ref mut match_place, _)), + .. + })) = **self.local_decls[local].local_info.as_mut().assert_crate_local() + else { bug!("Let binding to non-user variable.") }; *match_place = Some(place); diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index e6806177dec..9ac5f00ee46 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -88,7 +88,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { switch_ty: Ty<'tcx>, options: &mut FxIndexMap, u128>, ) -> bool { - let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else { + let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) + else { return false; }; @@ -126,7 +127,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidate: &Candidate<'pat, 'tcx>, variants: &mut BitSet, ) -> bool { - let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else { + let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) + else { return false; }; diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 6b2b140fa25..6e9df1c2daa 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -712,9 +712,7 @@ pub fn thir_check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { return; } - let Ok((thir, expr)) = tcx.thir_body(def) else { - return - }; + let Ok((thir, expr)) = tcx.thir_body(def) else { return }; let thir = &thir.borrow(); // If `thir` is empty, a type error occurred, skip this body. if thir.exprs.is_empty() { diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index ef60f08bf02..0eaaa411415 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -942,7 +942,9 @@ fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>( /// This analysis is *not* subsumed by NLL. fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, pat: &Pat<'tcx>) { // Extract `sub` in `binding @ sub`. - let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else { return }; + let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else { + return; + }; let is_binding_by_move = |ty: Ty<'tcx>| !ty.is_copy_modulo_regions(cx.tcx, cx.param_env); diff --git a/compiler/rustc_mir_dataflow/src/impls/mod.rs b/compiler/rustc_mir_dataflow/src/impls/mod.rs index cb74bea724a..633b99a332b 100644 --- a/compiler/rustc_mir_dataflow/src/impls/mod.rs +++ b/compiler/rustc_mir_dataflow/src/impls/mod.rs @@ -321,7 +321,9 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, 'tcx> { // Mark all places as "maybe init" if they are mutably borrowed. See #90752. for_each_mut_borrow(statement, location, |place| { - let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { return }; + let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { + return; + }; on_all_children_bits(self.tcx, self.body, self.move_data(), mpi, |child| { trans.gen(child); }) @@ -343,7 +345,9 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, 'tcx> { } for_each_mut_borrow(terminator, location, |place| { - let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { return }; + let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { + return; + }; on_all_children_bits(self.tcx, self.body, self.move_data(), mpi, |child| { trans.gen(child); }) diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 3df459dfa79..47d9f52bfb5 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -76,9 +76,11 @@ fn fully_moved_locals(ssa: &SsaLocals, body: &Body<'_>) -> BitSet { let mut fully_moved = BitSet::new_filled(body.local_decls.len()); for (_, rvalue, _) in ssa.assignments(body) { - let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) - = rvalue - else { continue }; + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) + | Rvalue::CopyForDeref(place)) = rvalue + else { + continue; + }; let Some(rhs) = place.as_local() else { continue }; if !ssa.is_ssa(rhs) { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 5b6cbb5577c..7d7588fcaec 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -281,7 +281,7 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> { let FlatSet::Elem(choice) = discr_value else { // Do nothing if we don't know which branch will be taken. - return + return; }; if target.value.map(|n| n == choice).unwrap_or(!handled) { diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index a31551cf619..b73b72c3192 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -218,9 +218,9 @@ impl<'tcx> MirPass<'tcx> for DestinationPropagation { if merged_locals.contains(*src) { continue; } - let Some(dest) = - candidates.iter().find(|dest| !merged_locals.contains(**dest)) else { - continue; + let Some(dest) = candidates.iter().find(|dest| !merged_locals.contains(**dest)) + else { + continue; }; if !tcx.consider_optimizing(|| { format!("{} round {}", tcx.def_path_str(def_id), round_count) @@ -601,9 +601,7 @@ impl WriteInfo { rhs: &Operand<'tcx>, body: &Body<'tcx>, ) { - let Some(rhs) = rhs.place() else { - return - }; + let Some(rhs) = rhs.place() else { return }; if let Some(pair) = places_to_candidate_pair(lhs, rhs, body) { self.skip_pair = Some(pair); } diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 8a7b027ddda..319fb4eaf3e 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -107,9 +107,7 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { for i in 0..body.basic_blocks.len() { let bbs = &*body.basic_blocks; let parent = BasicBlock::from_usize(i); - let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { - continue - }; + let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { continue }; if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_data)) { break; @@ -119,10 +117,9 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { should_cleanup = true; - let TerminatorKind::SwitchInt { - discr: parent_op, - targets: parent_targets - } = &bbs[parent].terminator().kind else { + let TerminatorKind::SwitchInt { discr: parent_op, targets: parent_targets } = + &bbs[parent].terminator().kind + else { unreachable!() }; // Always correct since we can only switch on `Copy` types @@ -168,7 +165,8 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { ); let eq_new_targets = parent_targets.iter().map(|(value, child)| { - let TerminatorKind::SwitchInt{ targets, .. } = &bbs[child].terminator().kind else { + let TerminatorKind::SwitchInt { targets, .. } = &bbs[child].terminator().kind + else { unreachable!() }; (value, targets.target_for_value(value)) @@ -311,11 +309,9 @@ fn evaluate_candidate<'tcx>( parent: BasicBlock, ) -> Option> { let bbs = &body.basic_blocks; - let TerminatorKind::SwitchInt { - targets, - discr: parent_discr, - } = &bbs[parent].terminator().kind else { - return None + let TerminatorKind::SwitchInt { targets, discr: parent_discr } = &bbs[parent].terminator().kind + else { + return None; }; let parent_ty = parent_discr.ty(body.local_decls(), tcx); let parent_dest = { @@ -332,18 +328,16 @@ fn evaluate_candidate<'tcx>( }; let (_, child) = targets.iter().next()?; let child_terminator = &bbs[child].terminator(); - let TerminatorKind::SwitchInt { - targets: child_targets, - discr: child_discr, - } = &child_terminator.kind else { - return None + let TerminatorKind::SwitchInt { targets: child_targets, discr: child_discr } = + &child_terminator.kind + else { + return None; }; let child_ty = child_discr.ty(body.local_decls(), tcx); if child_ty != parent_ty { return None; } - let Some(StatementKind::Assign(boxed)) - = &bbs[child].statements.first().map(|x| &x.kind) else { + let Some(StatementKind::Assign(boxed)) = &bbs[child].statements.first().map(|x| &x.kind) else { return None; }; let (_, Rvalue::Discriminant(child_place)) = &**boxed else { @@ -383,12 +377,8 @@ fn verify_candidate_branch<'tcx>( return false; } // ...assign the discriminant of `place` in that statement - let StatementKind::Assign(boxed) = &branch.statements[0].kind else { - return false - }; - let (discr_place, Rvalue::Discriminant(from_place)) = &**boxed else { - return false - }; + let StatementKind::Assign(boxed) = &branch.statements[0].kind else { return false }; + let (discr_place, Rvalue::Discriminant(from_place)) = &**boxed else { return false }; if *from_place != place { return false; } @@ -397,8 +387,9 @@ fn verify_candidate_branch<'tcx>( return false; } // ...terminate on a `SwitchInt` that invalidates that local - let TerminatorKind::SwitchInt{ discr: switch_op, targets, .. } = &branch.terminator().kind else { - return false + let TerminatorKind::SwitchInt { discr: switch_op, targets, .. } = &branch.terminator().kind + else { + return false; }; if *switch_op != Operand::Move(*discr_place) { return false; diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 264bc61f1b3..1154086d9b0 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -1763,7 +1763,9 @@ fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &GeneratorLayout<'tcx>, bo debug!(?decl); if !decl.ignore_for_traits && linted_tys.insert(decl.ty) { - let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { continue }; + let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { + continue; + }; check_must_not_suspend_ty( tcx, diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index e4dc617620e..a6af2eabda1 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -189,19 +189,19 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { statements: &mut Vec>, ) { let TerminatorKind::Call { func, args, destination, target, .. } = &mut terminator.kind - else { return }; + else { + return; + }; // It's definitely not a clone if there are multiple arguments if args.len() != 1 { return; } - let Some(destination_block) = *target - else { return }; + let Some(destination_block) = *target else { return }; // Only bother looking more if it's easy to know what we're calling - let Some((fn_def_id, fn_substs)) = func.const_fn_def() - else { return }; + let Some((fn_def_id, fn_substs)) = func.const_fn_def() else { return }; // Clone needs one subst, so we can cheaply rule out other stuff if fn_substs.len() != 1 { @@ -212,8 +212,7 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { // doing DefId lookups to figure out what we're actually calling. let arg_ty = args[0].ty(self.local_decls, self.tcx); - let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() - else { return }; + let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() else { return }; if !inner_ty.is_trivially_pure_clone_copy() { return; @@ -234,8 +233,7 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { return; } - let Some(arg_place) = args.pop().unwrap().place() - else { return }; + let Some(arg_place) = args.pop().unwrap().place() else { return }; statements.push(Statement { source_info: terminator.source_info, @@ -254,8 +252,12 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { terminator: &mut Terminator<'tcx>, _statements: &mut Vec>, ) { - let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { return; }; - let Some(target_block) = target else { return; }; + let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { + return; + }; + let Some(target_block) = target else { + return; + }; let func_ty = func.ty(self.local_decls, self.tcx); let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(self.tcx, func_ty) else { return; diff --git a/compiler/rustc_mir_transform/src/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs index ce98e9b0c84..eccc59f923d 100644 --- a/compiler/rustc_mir_transform/src/lower_intrinsics.rs +++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs @@ -251,7 +251,9 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics { if let (Some(target), Some(arg)) = (*target, args[0].place()) { let ty::RawPtr(ty::TypeAndMut { ty: dest_ty, .. }) = destination.ty(local_decls, tcx).ty.kind() - else { bug!(); }; + else { + bug!(); + }; block.statements.push(Statement { source_info: terminator.source_info, diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index 283931de043..d46690cc8b9 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -38,8 +38,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { let mut to_remove = vec![]; for (bb, block) in body.basic_blocks.iter_enumerated() { let terminator = block.terminator(); - let TerminatorKind::Drop { place, .. } = &terminator.kind - else { continue }; + let TerminatorKind::Drop { place, .. } = &terminator.kind else { continue }; maybe_inits.seek_before_primary_effect(body.terminator_loc(bb)); @@ -64,9 +63,9 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { for bb in to_remove { let block = &mut body.basic_blocks_mut()[bb]; - let TerminatorKind::Drop { target, .. } - = &block.terminator().kind - else { unreachable!() }; + let TerminatorKind::Drop { target, .. } = &block.terminator().kind else { + unreachable!() + }; // Replace block terminator with `Goto`. block.terminator_mut().kind = TerminatorKind::Goto { target: *target }; diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index e59219321b7..b7a51cfd619 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -199,7 +199,8 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { let last = current; *start = last; while let Some((current, mut terminator)) = terminators.pop() { - let Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } = terminator else { + let Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } = terminator + else { unreachable!(); }; *changed |= *target != last; diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 881a1547c52..c8fa7fc4b2a 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -161,7 +161,9 @@ struct ReplacementMap<'tcx> { impl<'tcx> ReplacementMap<'tcx> { fn replace_place(&self, tcx: TyCtxt<'tcx>, place: PlaceRef<'tcx>) -> Option> { - let &[PlaceElem::Field(f, _), ref rest @ ..] = place.projection else { return None; }; + let &[PlaceElem::Field(f, _), ref rest @ ..] = place.projection else { + return None; + }; let fields = self.fragments[place.local].as_ref()?; let (_, new_local) = fields[f]?; Some(Place { local: new_local, projection: tcx.mk_place_elems(&rest) }) diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index 8dc2dfe13bd..04bc461c815 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -266,9 +266,11 @@ fn compute_copy_classes(ssa: &mut SsaLocals, body: &Body<'_>) { let mut copies = IndexVec::from_fn_n(|l| l, body.local_decls.len()); for (local, rvalue, _) in ssa.assignments(body) { - let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) - = rvalue - else { continue }; + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) + | Rvalue::CopyForDeref(place)) = rvalue + else { + continue; + }; let Some(rhs) = place.as_local() else { continue }; let local_ty = body.local_decls()[local].ty; diff --git a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs index 5389b9f52eb..092bcb5c979 100644 --- a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs +++ b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs @@ -105,7 +105,8 @@ impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { for bb in body.basic_blocks.indices() { trace!("processing block {:?}", bb); - let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks[bb], tcx, body) else { + let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks[bb], tcx, body) + else { continue; }; diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 0ce6a570d25..8455803ad0c 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1434,8 +1434,9 @@ impl<'a> Parser<'a> { self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err) } IsStandalone::Subexpr => { - let Ok(base_src) = self.span_to_snippet(base.span) - else { return help_base_case(err, base) }; + let Ok(base_src) = self.span_to_snippet(base.span) else { + return help_base_case(err, base); + }; match kind.fixity { UnaryFixity::Pre => { self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err) diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index c23420661fa..e4d843b7c8b 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1289,7 +1289,9 @@ impl<'a> Parser<'a> { delimited.then(|| { // We've confirmed above that there is a delimiter so unwrapping is OK. - let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { unreachable!() }; + let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { + unreachable!() + }; DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens } }) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index f48900c3c52..c93d65b02f9 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1432,9 +1432,9 @@ impl CheckAttrVisitor<'_> { }; let Some(ItemLike::Item(Item { - kind: ItemKind::Fn(FnSig { decl, .. }, generics, _), - .. - })) = item else { + kind: ItemKind::Fn(FnSig { decl, .. }, generics, _), .. + })) = item + else { bug!("should be a function item"); }; @@ -2106,8 +2106,12 @@ impl CheckAttrVisitor<'_> { } let tcx = self.tcx; - let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else { return; }; - let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else { return; }; + let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else { + return; + }; + let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else { + return; + }; let def_id = hir_id.expect_owner().def_id; let param_env = ty::ParamEnv::empty(); diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 803ca05b202..3ebba7056e9 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -1683,12 +1683,16 @@ impl<'tcx> Liveness<'_, 'tcx> { opt_body: Option<&hir::Body<'_>>, ) -> Vec { let mut suggs = Vec::new(); - let Some(opt_body) = opt_body else { return suggs; }; + let Some(opt_body) = opt_body else { + return suggs; + }; let mut visitor = CollectLitsVisitor { lit_exprs: vec![] }; intravisit::walk_body(&mut visitor, opt_body); for lit_expr in visitor.lit_exprs { let hir::ExprKind::Lit(litx) = &lit_expr.kind else { continue }; - let rustc_ast::LitKind::Str(syb, _) = litx.node else{ continue; }; + let rustc_ast::LitKind::Str(syb, _) = litx.node else { + continue; + }; let name_str: &str = syb.as_str(); let name_pa = format!("{{{name}}}"); if name_str.contains(&name_pa) { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index b81b7ad6013..25a3d38c144 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -856,7 +856,9 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { /// See issue #94972 for details on why this is a special case fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool { // Get the LocalDefId so we can lookup the item to check the kind. - let Some(owner) = id.as_owner() else { return false; }; + let Some(owner) = id.as_owner() else { + return false; + }; let def_id = owner.def_id; let Some(stab) = tcx.stability().local_stability(def_id) else { diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index d37fe783bba..526fc9c3aa5 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1300,9 +1300,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() }; let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else { - self.tcx.sess.create_err(CannotGlobImportAllCrates { - span: import.span, - }).emit(); + self.tcx.sess.create_err(CannotGlobImportAllCrates { span: import.span }).emit(); return; }; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index f6c7aecf8b0..a715a1453a3 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -2460,8 +2460,11 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { F: FnOnce(&mut Self), { debug!("with_generic_param_rib"); - let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } - = lifetime_kind else { panic!() }; + let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } = + lifetime_kind + else { + panic!() + }; let mut function_type_rib = Rib::new(kind); let mut function_value_rib = Rib::new(kind); @@ -2972,7 +2975,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { F: FnOnce(Ident, String, Option) -> ResolutionError<'a>, { // If there is a TraitRef in scope for an impl, then the method must be in the trait. - let Some((module, _)) = self.current_trait_ref else { return; }; + let Some((module, _)) = self.current_trait_ref else { + return; + }; ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); let key = BindingKey::new(ident, ns); let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 78ef72a7e34..753a1adc66d 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -446,20 +446,29 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { err: &mut Diagnostic, base_error: &BaseError, ) { - let Some(ty) = self.diagnostic_metadata.current_type_path else { return; }; - let TyKind::Path(_, path) = &ty.kind else { return; }; + let Some(ty) = self.diagnostic_metadata.current_type_path else { + return; + }; + let TyKind::Path(_, path) = &ty.kind else { + return; + }; for segment in &path.segments { - let Some(params) = &segment.args else { continue; }; - let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; }; + let Some(params) = &segment.args else { + continue; + }; + let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { + continue; + }; for param in ¶ms.args { - let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; }; + let ast::AngleBracketedArg::Constraint(constraint) = param else { + continue; + }; let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else { continue; }; for bound in bounds { - let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None) - = bound else - { + let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None) = bound + else { continue; }; if base_error.span == trait_ref.span { @@ -1148,7 +1157,11 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { &poly_trait_ref.trait_ref.path.segments[..] { if ident.span == span { - let Some(new_where_bound_predicate) = mk_where_bound_predicate(path, poly_trait_ref, ty) else { return false; }; + let Some(new_where_bound_predicate) = + mk_where_bound_predicate(path, poly_trait_ref, ty) + else { + return false; + }; err.span_suggestion_verbose( *where_span, format!("constrain the associated type to `{}`", ident), @@ -1831,7 +1844,8 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { None, ) { Some(found) => { - let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) else { + let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) + else { return TypoCandidate::None; }; if found == name { @@ -2677,7 +2691,9 @@ fn mk_where_bound_predicate( use rustc_span::DUMMY_SP; let modified_segments = { let mut segments = path.segments.clone(); - let [preceding @ .., second_last, last] = segments.as_mut_slice() else { return None; }; + let [preceding @ .., second_last, last] = segments.as_mut_slice() else { + return None; + }; let mut segments = ThinVec::from(preceding); let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocConstraint { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index da3d86a4718..faa672db59c 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1871,7 +1871,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } else { let crate_id = if finalize { let Some(crate_id) = - self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) else { return Some(self.dummy_binding); }; + self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) + else { + return Some(self.dummy_binding); + }; crate_id } else { self.crate_loader(|c| c.maybe_process_path_extern(ident.name))? diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 3bb9c4920c4..5c56337d1e0 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -2159,7 +2159,8 @@ where // If this is not an empty or invalid span, we want to hash the last // position that belongs to it, as opposed to hashing the first // position past it. - let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else { + let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) + else { Hash::hash(&TAG_INVALID_SPAN, hasher); return; }; diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index 28138054ae5..a93845d3331 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -160,8 +160,8 @@ pub(super) trait GoalKind<'tcx>: Self::probe_and_match_goal_against_assumption(ecx, goal, assumption, |ecx| { let tcx = ecx.tcx(); let ty::Dynamic(bounds, _, _) = *goal.predicate.self_ty().kind() else { - bug!("expected object type in `consider_object_bound_candidate`"); - }; + bug!("expected object type in `consider_object_bound_candidate`"); + }; ecx.add_goals( structural_traits::predicates_for_object_candidate( &ecx, @@ -352,9 +352,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { candidates: &mut Vec>, ) { let tcx = self.tcx(); - let &ty::Alias(_, projection_ty) = goal.predicate.self_ty().kind() else { - return - }; + let &ty::Alias(_, projection_ty) = goal.predicate.self_ty().kind() else { return }; let normalized_self_candidates: Result<_, NoSolution> = self.probe(|_| CandidateKind::NormalizedSelfTyAssembly).enter(|ecx| { diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs index bf6cbef8c3b..d08cb3530f5 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs @@ -221,10 +221,7 @@ fn rematch_object<'tcx>( mut nested: Vec>, ) -> SelectionResult<'tcx, Selection<'tcx>> { let self_ty = goal.predicate.self_ty(); - let ty::Dynamic(data, _, source_kind) = *self_ty.kind() - else { - bug!() - }; + let ty::Dynamic(data, _, source_kind) = *self_ty.kind() else { bug!() }; let source_trait_ref = data.principal().unwrap().with_self_ty(infcx.tcx, self_ty); let (is_upcasting, target_trait_ref_unnormalized) = if Some(goal.predicate.def_id()) diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index 77809d8d2ba..9dfb793d0a4 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -266,12 +266,11 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { return Err(NoSolution); } - let Certainty::Maybe(maybe_cause) = responses.iter().fold( - Certainty::AMBIGUOUS, - |certainty, response| { + let Certainty::Maybe(maybe_cause) = + responses.iter().fold(Certainty::AMBIGUOUS, |certainty, response| { certainty.unify_with(response.value.certainty) - }, - ) else { + }) + else { bug!("expected flounder response to be ambiguous") }; diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index e53b784a756..9b701ca2023 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -146,89 +146,88 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { return Err(NoSolution); } - ecx.probe( - |r| CandidateKind::Candidate { name: "impl".into(), result: *r }).enter( - |ecx| { - let impl_substs = ecx.fresh_substs_for_item(impl_def_id); - let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs); + ecx.probe(|r| CandidateKind::Candidate { name: "impl".into(), result: *r }).enter(|ecx| { + let impl_substs = ecx.fresh_substs_for_item(impl_def_id); + let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs); - ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?; + ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?; - let where_clause_bounds = tcx - .predicates_of(impl_def_id) - .instantiate(tcx, impl_substs) - .predicates - .into_iter() - .map(|pred| goal.with(tcx, pred)); - ecx.add_goals(where_clause_bounds); + let where_clause_bounds = tcx + .predicates_of(impl_def_id) + .instantiate(tcx, impl_substs) + .predicates + .into_iter() + .map(|pred| goal.with(tcx, pred)); + ecx.add_goals(where_clause_bounds); - // In case the associated item is hidden due to specialization, we have to - // return ambiguity this would otherwise be incomplete, resulting in - // unsoundness during coherence (#105782). - let Some(assoc_def) = fetch_eligible_assoc_item_def( - ecx, - goal.param_env, - goal_trait_ref, - goal.predicate.def_id(), - impl_def_id - )? else { - return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); - }; + // In case the associated item is hidden due to specialization, we have to + // return ambiguity this would otherwise be incomplete, resulting in + // unsoundness during coherence (#105782). + let Some(assoc_def) = fetch_eligible_assoc_item_def( + ecx, + goal.param_env, + goal_trait_ref, + goal.predicate.def_id(), + impl_def_id, + )? + else { + return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); + }; - if !assoc_def.item.defaultness(tcx).has_value() { - let guar = tcx.sess.delay_span_bug( - tcx.def_span(assoc_def.item.def_id), - "missing value for assoc item in impl", - ); - let error_term = match assoc_def.item.kind { - ty::AssocKind::Const => ty::Const::new_error(tcx, - guar, - tcx.type_of(goal.predicate.def_id()) - .subst(tcx, goal.predicate.projection_ty.substs), - ) - .into(), - ty::AssocKind::Type => Ty::new_error(tcx,guar).into(), - ty::AssocKind::Fn => unreachable!(), - }; - ecx.eq(goal.param_env, goal.predicate.term, error_term) - .expect("expected goal term to be fully unconstrained"); - return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes); - } - - // Getting the right substitutions here is complex, e.g. given: - // - a goal ` as Trait>::Assoc` - // - the applicable impl `impl Trait for Vec` - // - and the impl which defines `Assoc` being `impl Trait for Vec` - // - // We first rebase the goal substs onto the impl, going from `[Vec, i32, u64]` - // to `[u32, u64]`. - // - // And then map these substs to the substs of the defining impl of `Assoc`, going - // from `[u32, u64]` to `[u32, i32, u64]`. - let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto( - tcx, - goal_trait_ref.def_id, - impl_substs, + if !assoc_def.item.defaultness(tcx).has_value() { + let guar = tcx.sess.delay_span_bug( + tcx.def_span(assoc_def.item.def_id), + "missing value for assoc item in impl", ); - let substs = ecx.translate_substs( - goal.param_env, - impl_def_id, - impl_substs_with_gat, - assoc_def.defining_node, - ); - - // Finally we construct the actual value of the associated type. - let term = match assoc_def.item.kind { - ty::AssocKind::Type => tcx.type_of(assoc_def.item.def_id).map_bound(|ty| ty.into()), - ty::AssocKind::Const => bug!("associated const projection is not supported yet"), - ty::AssocKind::Fn => unreachable!("we should never project to a fn"), + let error_term = match assoc_def.item.kind { + ty::AssocKind::Const => ty::Const::new_error( + tcx, + guar, + tcx.type_of(goal.predicate.def_id()) + .subst(tcx, goal.predicate.projection_ty.substs), + ) + .into(), + ty::AssocKind::Type => Ty::new_error(tcx, guar).into(), + ty::AssocKind::Fn => unreachable!(), }; - - ecx.eq(goal.param_env, goal.predicate.term, term.subst(tcx, substs)) + ecx.eq(goal.param_env, goal.predicate.term, error_term) .expect("expected goal term to be fully unconstrained"); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - }, - ) + return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes); + } + + // Getting the right substitutions here is complex, e.g. given: + // - a goal ` as Trait>::Assoc` + // - the applicable impl `impl Trait for Vec` + // - and the impl which defines `Assoc` being `impl Trait for Vec` + // + // We first rebase the goal substs onto the impl, going from `[Vec, i32, u64]` + // to `[u32, u64]`. + // + // And then map these substs to the substs of the defining impl of `Assoc`, going + // from `[u32, u64]` to `[u32, i32, u64]`. + let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto( + tcx, + goal_trait_ref.def_id, + impl_substs, + ); + let substs = ecx.translate_substs( + goal.param_env, + impl_def_id, + impl_substs_with_gat, + assoc_def.defining_node, + ); + + // Finally we construct the actual value of the associated type. + let term = match assoc_def.item.kind { + ty::AssocKind::Type => tcx.type_of(assoc_def.item.def_id).map_bound(|ty| ty.into()), + ty::AssocKind::Const => bug!("associated const projection is not supported yet"), + ty::AssocKind::Fn => unreachable!("we should never project to a fn"), + }; + + ecx.eq(goal.param_env, goal.predicate.term, term.subst(tcx, substs)) + .expect("expected goal term to be fully unconstrained"); + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + }) } fn consider_auto_trait_candidate( diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index ef5f25b1f7f..40668145096 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -600,11 +600,9 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { // which will ICE for region vars. let substs = ecx.tcx().erase_regions(goal.predicate.trait_ref.substs); - let Some(assume) = rustc_transmute::Assume::from_const( - ecx.tcx(), - goal.param_env, - substs.const_at(3), - ) else { + let Some(assume) = + rustc_transmute::Assume::from_const(ecx.tcx(), goal.param_env, substs.const_at(3)) + else { return Err(NoSolution); }; diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index cb38d0ac847..67e7e5bfa53 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -152,14 +152,9 @@ impl<'tcx> AutoTraitFinder<'tcx> { // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing // SelectionContext to return it back to us. - let Some((new_env, user_env)) = self.evaluate_predicates( - &infcx, - trait_did, - ty, - orig_env, - orig_env, - &mut fresh_preds, - ) else { + let Some((new_env, user_env)) = + self.evaluate_predicates(&infcx, trait_did, ty, orig_env, orig_env, &mut fresh_preds) + else { return AutoTraitResult::NegativeImpl; }; diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 1b1285e1b46..dc72cd6517a 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -376,7 +376,7 @@ fn impl_intersection_has_negative_obligation( // do the impls unify? If not, then it's not currently possible to prove any // obligations about their intersection. let Ok(InferOk { obligations: equate_obligations, .. }) = - infcx.at(&ObligationCause::dummy(), impl_env).eq(DefineOpaqueTypes::No,subject1, subject2) + infcx.at(&ObligationCause::dummy(), impl_env).eq(DefineOpaqueTypes::No, subject1, subject2) else { debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2); return false; @@ -437,8 +437,7 @@ fn prove_negated_obligation<'tcx>( let body_def_id = body_def_id.as_local().unwrap_or(CRATE_DEF_ID); let ocx = ObligationCtxt::new(&infcx); - let Ok(wf_tys) = ocx.assumed_wf_types(param_env, body_def_id) - else { + let Ok(wf_tys) = ocx.assumed_wf_types(param_env, body_def_id) else { return false; }; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 4dc06d2bfac..a0facd94bfd 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -2708,10 +2708,17 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>, ) { - let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) = obligation.predicate.kind().skip_binder() else { return; }; + let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) = + obligation.predicate.kind().skip_binder() + else { + return; + }; let (ObligationCauseCode::BindingObligation(item_def_id, span) - | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..)) - = *obligation.cause.code().peel_derives() else { return; }; + | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..)) = + *obligation.cause.code().peel_derives() + else { + return; + }; debug!(?pred, ?item_def_id, ?span); let (Some(node), true) = ( @@ -2880,10 +2887,16 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { src: trait_ref.substs.type_at(1), }; let scope = trait_ref.substs.type_at(2); - let Some(assume) = - rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, trait_ref.substs.const_at(3)) else { - span_bug!(span, "Unable to construct rustc_transmute::Assume where it was previously possible"); - }; + let Some(assume) = rustc_transmute::Assume::from_const( + self.infcx.tcx, + obligation.param_env, + trait_ref.substs.const_at(3), + ) else { + span_bug!( + span, + "Unable to construct rustc_transmute::Assume where it was previously possible" + ); + }; match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable( obligation.cause, diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 9ac1ba0275c..1a9e21c2bea 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -752,14 +752,20 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { // It only make sense when suggesting dereferences for arguments - let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code() - else { return false; }; - let Some(typeck_results) = &self.typeck_results - else { return false; }; - let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id) - else { return false; }; - let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr) - else { return false; }; + let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = + obligation.cause.code() + else { + return false; + }; + let Some(typeck_results) = &self.typeck_results else { + return false; + }; + let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id) else { + return false; + }; + let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr) else { + return false; + }; let span = obligation.cause.span; let mut real_trait_pred = trait_pred; @@ -933,11 +939,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred.self_ty(), ); - let Some((def_id_or_name, output, inputs)) = self.extract_callable_info( - obligation.cause.body_id, - obligation.param_env, - self_ty, - ) else { return false; }; + let Some((def_id_or_name, output, inputs)) = + self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty) + else { + return false; + }; // Remapping bound vars here let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output)); @@ -1035,26 +1041,40 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { span.remove_mark(); } let mut expr_finder = FindExprBySpan::new(span); - let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return; }; + let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { + return; + }; let body = self.tcx.hir().body(body_id); expr_finder.visit_expr(body.value); - let Some(expr) = expr_finder.result else { return; }; - let Some(typeck) = &self.typeck_results else { return; }; - let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; }; + let Some(expr) = expr_finder.result else { + return; + }; + let Some(typeck) = &self.typeck_results else { + return; + }; + let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { + return; + }; if !ty.is_unit() { return; }; - let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; }; - let hir::def::Res::Local(hir_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { + return; + }; + let hir::def::Res::Local(hir_id) = path.res else { + return; + }; let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { return; }; - let Some(hir::Node::Local(hir::Local { - ty: None, - init: Some(init), - .. - })) = self.tcx.hir().find_parent(pat.hir_id) else { return; }; - let hir::ExprKind::Block(block, None) = init.kind else { return; }; + let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = + self.tcx.hir().find_parent(pat.hir_id) + else { + return; + }; + let hir::ExprKind::Block(block, None) = init.kind else { + return; + }; if block.expr.is_some() { return; } @@ -1062,7 +1082,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.span_label(block.span, "this empty block is missing a tail expression"); return; }; - let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; }; + let hir::StmtKind::Semi(tail_expr) = stmt.kind else { + return; + }; let Some(ty) = typeck.expr_ty_opt(tail_expr) else { err.span_label(block.span, "this block is missing a tail expression"); return; @@ -1092,12 +1114,18 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); let ty = self.instantiate_binder_with_placeholders(self_ty); - let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false }; + let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { + return false; + }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; - let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false }; + let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = + obligation.cause.code() + else { + return false; + }; let arg_node = self.tcx.hir().get(*arg_hir_id); - let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false }; + let Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) = arg_node else { return false }; let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None); let has_clone = |ty| { @@ -1143,21 +1171,30 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { found: Ty<'tcx>, ) -> Option<(DefIdOrName, Ty<'tcx>, Vec>)> { // Autoderef is useful here because sometimes we box callables, etc. - let Some((def_id_or_name, output, inputs)) = (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| { - match *found.kind() { - ty::FnPtr(fn_sig) => - Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())), - ty::FnDef(def_id, _) => { - let fn_sig = found.fn_sig(self.tcx); - Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs())) - } - ty::Closure(def_id, substs) => { - let fn_sig = substs.as_closure().sig(); - Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..]))) - } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - self.tcx.item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| { - if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() + let Some((def_id_or_name, output, inputs)) = + (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| { + match *found.kind() { + ty::FnPtr(fn_sig) => Some(( + DefIdOrName::Name("function pointer"), + fn_sig.output(), + fn_sig.inputs(), + )), + ty::FnDef(def_id, _) => { + let fn_sig = found.fn_sig(self.tcx); + Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs())) + } + ty::Closure(def_id, substs) => { + let fn_sig = substs.as_closure().sig(); + Some(( + DefIdOrName::DefId(def_id), + fn_sig.output(), + fn_sig.inputs().map_bound(|inputs| &inputs[1..]), + )) + } + ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + self.tcx.item_bounds(def_id).subst(self.tcx, substs).iter().find_map( + |pred| { + if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() // args tuple will always be substs[1] && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind() @@ -1170,11 +1207,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) - } - ty::Dynamic(data, _, ty::Dyn) => { - data.iter().find_map(|pred| { - if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder() + }, + ) + } + ty::Dynamic(data, _, ty::Dyn) => { + data.iter().find_map(|pred| { + if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder() && Some(proj.def_id) == self.tcx.lang_items().fn_once_output() // for existential projection, substs are shifted over by 1 && let ty::Tuple(args) = proj.substs.type_at(0).kind() @@ -1187,11 +1225,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) - } - ty::Param(param) => { - let generics = self.tcx.generics_of(body_id); - let name = if generics.count() > param.index as usize + }) + } + ty::Param(param) => { + let generics = self.tcx.generics_of(body_id); + let name = if generics.count() > param.index as usize && let def = generics.param_at(param.index as usize, self.tcx) && matches!(def.kind, ty::GenericParamDefKind::Type { .. }) && def.name == param.name @@ -1200,8 +1238,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { DefIdOrName::Name("type parameter") }; - param_env.caller_bounds().iter().find_map(|pred| { - if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() + param_env.caller_bounds().iter().find_map(|pred| { + if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() && proj.projection_ty.self_ty() == found // args tuple will always be substs[1] @@ -1215,11 +1253,14 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) + }) + } + _ => None, } - _ => None, - } - }) else { return None; }; + }) + else { + return None; + }; let output = self.instantiate_binder_with_fresh_vars( DUMMY_SP, @@ -1408,11 +1449,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Issue #104961, we need to add parentheses properly for compound expressions // for example, `x.starts_with("hi".to_string() + "you")` // should be `x.starts_with(&("hi".to_string() + "you"))` - let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return false; }; + let Some(body_id) = + self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) + else { + return false; + }; let body = self.tcx.hir().body(body_id); let mut expr_finder = FindExprBySpan::new(span); expr_finder.visit_expr(body.value); - let Some(expr) = expr_finder.result else { return false; }; + let Some(expr) = expr_finder.result else { + return false; + }; let needs_parens = match expr.kind { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true, @@ -1463,8 +1510,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self_ty: Ty<'tcx>, target_ty: Ty<'tcx>, ) { - let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else { return; }; - let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; }; + let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else { + return; + }; + let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { + return; + }; let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty); for predicate in predicates.iter() { @@ -1566,7 +1617,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`. - let Some(mut expr) = expr_finder.result else { return false; }; + let Some(mut expr) = expr_finder.result else { + return false; + }; let mut count = 0; let mut suggestions = vec![]; // Skipping binder here, remapping below @@ -1798,7 +1851,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option { let hir = self.tcx.hir(); - let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find_by_def_id(obligation.cause.body_id) else { + let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = + hir.find_by_def_id(obligation.cause.body_id) + else { return None; }; @@ -2222,7 +2277,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Only continue if a generator was found. debug!(?generator, ?trait_ref, ?target_ty); - let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else { + let (Some(generator_did), Some(trait_ref), Some(target_ty)) = + (generator, trait_ref, target_ty) + else { return false; }; @@ -3617,7 +3674,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Some(typeck_results) = self.typeck_results.as_ref() else { return }; // Make sure we're dealing with the `Option` type. - let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else { return }; + let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else { + return; + }; if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) { return; } @@ -3749,11 +3808,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { while let Some(assocs_in_method) = assocs.next() { let Some(prev_assoc_in_method) = assocs.peek() else { for entry in assocs_in_method { - let Some((span, (assoc, ty))) = entry else { continue; }; - if primary_spans.is_empty() || type_diffs.iter().any(|diff| { - let Sorts(expected_found) = diff else { return false; }; - self.can_eq(param_env, expected_found.found, ty) - }) { + let Some((span, (assoc, ty))) = entry else { + continue; + }; + if primary_spans.is_empty() + || type_diffs.iter().any(|diff| { + let Sorts(expected_found) = diff else { + return false; + }; + self.can_eq(param_env, expected_found.found, ty) + }) + { // FIXME: this doesn't quite work for `Iterator::collect` // because we have `Vec` and `()`, but we'd want `i32` // to point at the `.into_iter()` call, but as long as we @@ -3781,7 +3846,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc)); if !self.can_eq(param_env, ty, *prev_ty) { if type_diffs.iter().any(|diff| { - let Sorts(expected_found) = diff else { return false; }; + let Sorts(expected_found) = diff else { + return false; + }; self.can_eq(param_env, expected_found.found, ty) }) { primary_spans.push(span); @@ -3829,8 +3896,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let ocx = ObligationCtxt::new(self.infcx); let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len()); for diff in type_diffs { - let Sorts(expected_found) = diff else { continue; }; - let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; }; + let Sorts(expected_found) = diff else { + continue; + }; + let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { + continue; + }; let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }; let trait_def_id = proj.trait_def_id(self.tcx); @@ -3974,7 +4045,9 @@ fn hint_missing_borrow<'tcx>( }; // This could be a variant constructor, for example. - let Some(fn_decl) = found_node.fn_decl() else { return; }; + let Some(fn_decl) = found_node.fn_decl() else { + return; + }; let args = fn_decl.inputs.iter(); diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index bc136695442..f092e821751 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -362,12 +362,9 @@ pub fn normalize_param_env_or_error<'tcx>( "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})", predicates, outlives_predicates ); - let Ok(non_outlives_predicates) = do_normalize_predicates( - tcx, - cause.clone(), - elaborated_env, - predicates, - ) else { + let Ok(non_outlives_predicates) = + do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates) + else { // An unnormalized env is better than nothing. debug!("normalize_param_env_or_error: errored resolving non-outlives predicates"); return elaborated_env; @@ -384,12 +381,9 @@ pub fn normalize_param_env_or_error<'tcx>( unnormalized_env.reveal(), unnormalized_env.constness(), ); - let Ok(outlives_predicates) = do_normalize_predicates( - tcx, - cause, - outlives_env, - outlives_predicates, - ) else { + let Ok(outlives_predicates) = + do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates) + else { // An unnormalized env is better than nothing. debug!("normalize_param_env_or_error: errored resolving outlives predicates"); return elaborated_env; diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index ff55eaf13ad..339baf611f3 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -83,7 +83,8 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { &canonical_var_values, canonical_result, &mut constraints, - ) else { + ) + else { return vec![]; }; assert_eq!(&obligations, &[]); diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index d5f6aaa7fe9..eb603cf3737 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -402,8 +402,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; for &(predicate, _) in self.tcx().predicates_of(impl_def_id).predicates { - let ty::ClauseKind::Trait(pred) - = predicate.kind().skip_binder() else { continue }; + let ty::ClauseKind::Trait(pred) = predicate.kind().skip_binder() else { continue }; if fn_ptr_trait != pred.trait_ref.def_id { continue; } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 7adc29bbba4..01452986f5a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -342,7 +342,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let Some(assume) = rustc_transmute::Assume::from_const( self.infcx.tcx, obligation.param_env, - predicate.trait_ref.substs.const_at(3) + predicate.trait_ref.substs.const_at(3), ) else { return Err(Unimplemented); }; @@ -662,10 +662,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let tcx = self.tcx(); - let Some(self_ty) = self - .infcx - .shallow_resolve(obligation.self_ty().no_bound_vars()) else - { + let Some(self_ty) = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars()) else { // FIXME: Ideally we'd support `for<'a> fn(&'a ()): Fn(&'a ())`, // but we do not currently. Luckily, such a bound is not // particularly useful, so we don't expect users to write diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index 96f1287416f..6d001467b44 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -226,13 +226,11 @@ fn fulfill_implication<'tcx>( util::impl_subject_and_oblig(selcx, param_env, target_impl, target_substs, error_cause); // do the impls unify? If not, no specialization. - let Ok(InferOk { obligations: more_obligations, .. }) = - infcx.at(&ObligationCause::dummy(), param_env).eq(DefineOpaqueTypes::No, source_trait, target_trait) + let Ok(InferOk { obligations: more_obligations, .. }) = infcx + .at(&ObligationCause::dummy(), param_env) + .eq(DefineOpaqueTypes::No, source_trait, target_trait) else { - debug!( - "fulfill_implication: {:?} does not unify with {:?}", - source_trait, target_trait - ); + debug!("fulfill_implication: {:?} does not unify with {:?}", source_trait, target_trait); return Err(()); }; diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 7e22ef89ed3..ed4f6d972c2 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -215,7 +215,9 @@ fn associated_types_for_impl_traits_in_associated_fn( } DefKind::Impl { .. } => { - let Some(trait_fn_def_id) = tcx.associated_item(fn_def_id).trait_item_def_id else { return &[] }; + let Some(trait_fn_def_id) = tcx.associated_item(fn_def_id).trait_item_def_id else { + return &[]; + }; tcx.arena.alloc_from_iter( tcx.associated_types_for_impl_traits_in_associated_fn(trait_fn_def_id).iter().map( diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 1d93a79e591..b5e85e6d65f 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -230,7 +230,8 @@ fn resolve_associated_item<'tcx>( }) } } else if Some(trait_ref.def_id) == lang_items.future_trait() { - let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else { + let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() + else { bug!() }; if Some(trait_item_id) == tcx.lang_items().future_poll_fn() { @@ -243,7 +244,8 @@ fn resolve_associated_item<'tcx>( Some(Instance::new(trait_item_id, rcvr_substs)) } } else if Some(trait_ref.def_id) == lang_items.gen_trait() { - let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else { + let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() + else { bug!() }; if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume { diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index b67cd96a734..1cbbdedde97 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -525,8 +525,13 @@ fn layout_of_uncached<'tcx>( let FieldsShape::Arbitrary { offsets: sized_offsets, .. } = &layout.fields else { bug!("unexpected FieldsShape for sized layout of {ty:?}: {:?}", layout.fields); }; - let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } = &unsized_layout.fields else { - bug!("unexpected FieldsShape for unsized layout of {ty:?}: {:?}", unsized_layout.fields); + let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } = + &unsized_layout.fields + else { + bug!( + "unexpected FieldsShape for unsized layout of {ty:?}: {:?}", + unsized_layout.fields + ); }; let (sized_tail, sized_fields) = sized_offsets.raw.split_last().unwrap(); diff --git a/compiler/rustc_ty_utils/src/layout_sanity_check.rs b/compiler/rustc_ty_utils/src/layout_sanity_check.rs index c4a4cda6801..8633334381a 100644 --- a/compiler/rustc_ty_utils/src/layout_sanity_check.rs +++ b/compiler/rustc_ty_utils/src/layout_sanity_check.rs @@ -52,7 +52,7 @@ pub(super) fn sanity_check_layout<'tcx>( let mut fields = non_zst_fields(cx, layout); let Some(first) = fields.next() else { // No fields here, so this could be a primitive or enum -- either way it's not a newtype around a thing - return *layout + return *layout; }; if fields.next().is_none() { let (offset, first) = first; @@ -77,7 +77,7 @@ pub(super) fn sanity_check_layout<'tcx>( Abi::Uninhabited | Abi::Aggregate { .. }, "ABI unexpectedly missing alignment and/or size in {layout:#?}" ); - return + return; }; assert_eq!( layout.layout.align().abi, diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 76b3589b9e4..ebd4a8c05fe 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -925,7 +925,7 @@ fn iter_next_chunk_erased( // so we need to defuse the guard instead of using `?`. let initialized = guard.initialized; mem::forget(guard); - return Err(initialized) + return Err(initialized); }; // SAFETY: The loop condition ensures we have space to push the item diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 91ee2903aab..d5d6d60acf6 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -1750,7 +1750,9 @@ fn simd_contains(needle: &str, haystack: &str) -> Option { 1 } else { // try a few bytes in case first and last byte of the needle are the same - let Some(second_probe_offset) = (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe) else { + let Some(second_probe_offset) = + (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe) + else { // fall back to other search methods if we can't find any different bytes // since we could otherwise hit some degenerate cases return None; diff --git a/src/bootstrap/clean.rs b/src/bootstrap/clean.rs index c1d867a0bd1..ea8334eaeb6 100644 --- a/src/bootstrap/clean.rs +++ b/src/bootstrap/clean.rs @@ -26,7 +26,9 @@ impl Step for CleanAll { } fn run(self, builder: &Builder<'_>) -> Self::Output { - let Subcommand::Clean { all, .. } = builder.config.cmd else { unreachable!("wrong subcommand?") }; + let Subcommand::Clean { all, .. } = builder.config.cmd else { + unreachable!("wrong subcommand?") + }; clean_default(builder.build, all) } diff --git a/src/bootstrap/format.rs b/src/bootstrap/format.rs index ebf068b2cb1..4330e126398 100644 --- a/src/bootstrap/format.rs +++ b/src/bootstrap/format.rs @@ -66,13 +66,17 @@ fn get_rustfmt_version(build: &Builder<'_>) -> Option<(String, PathBuf)> { /// Return whether the format cache can be reused. fn verify_rustfmt_version(build: &Builder<'_>) -> bool { - let Some((version, stamp_file)) = get_rustfmt_version(build) else {return false;}; + let Some((version, stamp_file)) = get_rustfmt_version(build) else { + return false; + }; !program_out_of_date(&stamp_file, &version) } /// Updates the last rustfmt version used fn update_rustfmt_version(build: &Builder<'_>) { - let Some((version, stamp_file)) = get_rustfmt_version(build) else {return;}; + let Some((version, stamp_file)) = get_rustfmt_version(build) else { + return; + }; t!(std::fs::write(stamp_file, version)) } diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index a3604158851..c4ac5466164 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -47,9 +47,13 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { // Require the type the impl is implemented on to match // our type, and ignore the impl if there was a mismatch. - let Ok(eq_result) = infcx.at(&traits::ObligationCause::dummy(), param_env).eq(DefineOpaqueTypes::No, impl_trait_ref.self_ty(), impl_ty) else { - continue - }; + let Ok(eq_result) = infcx.at(&traits::ObligationCause::dummy(), param_env).eq( + DefineOpaqueTypes::No, + impl_trait_ref.self_ty(), + impl_ty, + ) else { + continue; + }; let InferOk { value: (), obligations } = eq_result; // FIXME(eddyb) ignoring `obligations` might cause false positives. drop(obligations); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0182d50773d..d26de77a78d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -167,8 +167,7 @@ fn clean_generic_bound<'tcx>( let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(cx.tcx, def_id)); let generic_args = clean_generic_args(generic_args, cx); - let GenericArgs::AngleBracketed { bindings, .. } = generic_args - else { + let GenericArgs::AngleBracketed { bindings, .. } = generic_args else { bug!("clean: parenthesized `GenericBound::LangItemTrait`"); }; diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 65b1b72adc1..d53b038019b 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -47,7 +47,9 @@ pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec) -> ThinVec) -> Vec { use crate::html::format::{href, link_tooltip}; - let Some(links) = cx.cache() - .intra_doc_links - .get(&self.item_id) else { - return vec![] - }; + let Some(links) = cx.cache().intra_doc_links.get(&self.item_id) else { return vec![] }; links .iter() .filter_map(|ItemLink { link: s, link_text, page_id: id, ref fragment }| { @@ -484,11 +480,9 @@ impl Item { /// the link text, but does need to know which `[]`-bracketed names /// are actually links. pub(crate) fn link_names(&self, cache: &Cache) -> Vec { - let Some(links) = cache - .intra_doc_links - .get(&self.item_id) else { - return vec![]; - }; + let Some(links) = cache.intra_doc_links.get(&self.item_id) else { + return vec![]; + }; links .iter() .map(|ItemLink { link: s, link_text, .. }| RenderedLink { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index f375f0efbd1..d6a970fba39 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -54,8 +54,7 @@ pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate { let primitives = local_crate.primitives(cx.tcx); let keywords = local_crate.keywords(cx.tcx); { - let ItemKind::ModuleItem(ref mut m) = *module.kind - else { unreachable!() }; + let ItemKind::ModuleItem(ref mut m) = *module.kind else { unreachable!() }; m.items.extend(primitives.iter().map(|&(def_id, prim)| { Item::from_def_id_and_parts( def_id, diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 217257316c8..6047cf23350 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -653,8 +653,7 @@ pub(crate) fn make_test( (found_main, found_extern_crate, found_macro) }) }); - let Ok((already_has_main, already_has_extern_crate, found_macro)) = result - else { + let Ok((already_has_main, already_has_extern_crate, found_macro)) = result else { // If the parser panicked due to a fatal error, pass the test code through unchanged. // The error will be reported during compilation. return (s.to_owned(), 0, false); diff --git a/src/librustdoc/formats/renderer.rs b/src/librustdoc/formats/renderer.rs index 6f9cc026675..c49f1a4d37e 100644 --- a/src/librustdoc/formats/renderer.rs +++ b/src/librustdoc/formats/renderer.rs @@ -77,8 +77,11 @@ pub(crate) fn run_format<'tcx, T: FormatRenderer<'tcx>>( prof.generic_activity_with_arg("render_mod_item", item.name.unwrap().to_string()); cx.mod_item_in(&item)?; - let (clean::StrippedItem(box clean::ModuleItem(module)) | clean::ModuleItem(module)) = *item.kind - else { unreachable!() }; + let (clean::StrippedItem(box clean::ModuleItem(module)) | clean::ModuleItem(module)) = + *item.kind + else { + unreachable!() + }; for it in module.items { debug!("Adding {:?} to worklist", it.name); work.push((cx.make_child_renderer(), it)); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 54c0cd2ef7f..1099c68b004 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -771,9 +771,10 @@ pub(crate) fn href_relative_parts<'fqp>( pub(crate) fn link_tooltip(did: DefId, fragment: &Option, cx: &Context<'_>) -> String { let cache = cx.cache(); - let Some((fqp, shortty)) = cache.paths.get(&did) - .or_else(|| cache.external_paths.get(&did)) - else { return String::new() }; + let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did)) + else { + return String::new(); + }; let mut buf = Buffer::new(); let fqp = if *shortty == ItemType::Primitive { // primitives are documented in a crate, but not actually part of it diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index c94968b4817..0aee79a6947 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -928,13 +928,11 @@ fn string_without_closing_tag( href_context: &Option>, open_tag: bool, ) -> Option<&'static str> { - let Some(klass) = klass - else { + let Some(klass) = klass else { write!(out, "{}", text).unwrap(); return None; }; - let Some(def_span) = klass.get_span() - else { + let Some(def_span) = klass.get_span() else { if !open_tag { write!(out, "{}", text).unwrap(); return None; diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 4c476263635..aa72af001df 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -805,8 +805,11 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { // Render sidebar-items.js used throughout this module. if !self.render_redirect_pages { - let (clean::StrippedItem(box clean::ModuleItem(ref module)) | clean::ModuleItem(ref module)) = *item.kind - else { unreachable!() }; + let (clean::StrippedItem(box clean::ModuleItem(ref module)) + | clean::ModuleItem(ref module)) = *item.kind + else { + unreachable!() + }; let items = self.build_sidebar_items(module); let js_dst = self.dst.join(&format!("sidebar-items{}.js", self.shared.resource_suffix)); let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap()); diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index f923f905451..8a1ce9fb135 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1988,7 +1988,9 @@ pub(crate) fn get_filtered_impls_for_reference<'a>( ) -> (Vec<&'a Impl>, Vec<&'a Impl>, Vec<&'a Impl>) { let def_id = it.item_id.expect_def_id(); // If the reference primitive is somehow not defined, exit early. - let Some(v) = shared.cache.impls.get(&def_id) else { return (Vec::new(), Vec::new(), Vec::new()) }; + let Some(v) = shared.cache.impls.get(&def_id) else { + return (Vec::new(), Vec::new(), Vec::new()); + }; // Since there is no "direct implementation" on the reference primitive type, we filter out // every implementation which isn't a trait implementation. let traits = v.iter().filter(|i| i.inner_impl().trait_.is_some()); diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index b6cd897d317..1aa12e3ced2 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -106,8 +106,7 @@ pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) - } pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) { - let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) - else { + let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else { // If non-local, no need to check anything. return; }; diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index ca511d956b9..6df2b973551 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1610,8 +1610,7 @@ fn report_diagnostic( DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>, decorate: impl FnOnce(&mut Diagnostic, Option, MarkdownLinkRange), ) { - let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) - else { + let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else { // If non-local, no need to check anything. info!("ignoring warning from parent crate: {}", msg); return; diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs index e9cee92d22b..5658b31d9bb 100644 --- a/src/librustdoc/passes/lint/bare_urls.rs +++ b/src/librustdoc/passes/lint/bare_urls.rs @@ -13,11 +13,10 @@ use std::mem; use std::sync::LazyLock; pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) { - let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) - else { - // If non-local, no need to check anything. - return; - }; + let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else { + // If non-local, no need to check anything. + return; + }; let dox = item.doc_value(); if !dox.is_empty() { let report_diag = diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index f489f5081da..369a8069593 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -67,12 +67,11 @@ fn check_rust_syntax( return; } - let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) - else { - // We don't need to check the syntax for other crates so returning - // without doing anything should not be a problem. - return; - }; + let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) else { + // We don't need to check the syntax for other crates so returning + // without doing anything should not be a problem. + return; + }; let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced; let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None; diff --git a/src/librustdoc/passes/lint/html_tags.rs b/src/librustdoc/passes/lint/html_tags.rs index 5273f52bc6f..24f452b216c 100644 --- a/src/librustdoc/passes/lint/html_tags.rs +++ b/src/librustdoc/passes/lint/html_tags.rs @@ -14,7 +14,9 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) { let tcx = cx.tcx; let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) // If non-local, no need to check anything. - else { return }; + else { + return; + }; let dox = item.doc_value(); if !dox.is_empty() { let report_diag = |msg: String, range: &Range, is_open_tag: bool| { diff --git a/src/librustdoc/passes/propagate_doc_cfg.rs b/src/librustdoc/passes/propagate_doc_cfg.rs index 8a33e51b3be..95273a225a9 100644 --- a/src/librustdoc/passes/propagate_doc_cfg.rs +++ b/src/librustdoc/passes/propagate_doc_cfg.rs @@ -38,8 +38,9 @@ impl<'a, 'tcx> CfgPropagator<'a, 'tcx> { _ => return, }; - let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) - else { return }; + let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) else { + return; + }; if check_parent { let expected_parent = self.cx.tcx.opt_local_parent(def_id); diff --git a/src/tools/build_helper/src/git.rs b/src/tools/build_helper/src/git.rs index 168633c8f63..66876e02c19 100644 --- a/src/tools/build_helper/src/git.rs +++ b/src/tools/build_helper/src/git.rs @@ -94,7 +94,9 @@ pub fn get_git_modified_files( git_dir: Option<&Path>, extensions: &Vec<&str>, ) -> Result>, String> { - let Ok(updated_master) = updated_master_branch(git_dir) else { return Ok(None); }; + let Ok(updated_master) = updated_master_branch(git_dir) else { + return Ok(None); + }; let git = || { let mut git = Command::new("git"); @@ -119,7 +121,9 @@ pub fn get_git_modified_files( /// Returns the files that haven't been added to git yet. pub fn get_git_untracked_files(git_dir: Option<&Path>) -> Result>, String> { - let Ok(_updated_master) = updated_master_branch(git_dir) else { return Ok(None); }; + let Ok(_updated_master) = updated_master_branch(git_dir) else { + return Ok(None); + }; let mut git = Command::new("git"); if let Some(git_dir) = git_dir { git.current_dir(git_dir); diff --git a/src/tools/collect-license-metadata/src/path_tree.rs b/src/tools/collect-license-metadata/src/path_tree.rs index 68b6cef6432..709d91897e6 100644 --- a/src/tools/collect-license-metadata/src/path_tree.rs +++ b/src/tools/collect-license-metadata/src/path_tree.rs @@ -155,7 +155,10 @@ impl Node { name: child_name, children: child_children, license: child_license, - } = child else { continue }; + } = child + else { + continue; + }; if child_license != license { continue; diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index ad10c3e07ce..1779b26c422 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -599,7 +599,10 @@ pub fn line_directive<'line>( if ln.starts_with('[') { // A comment like `//[foo]` is specific to revision `foo` let Some(close_brace) = ln.find(']') else { - panic!("malformed condition directive: expected `{}[foo]`, found `{}`", comment, ln); + panic!( + "malformed condition directive: expected `{}[foo]`, found `{}`", + comment, ln + ); }; let lncfg = &ln[1..close_brace];