diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 902b4b1a1ec..a83287c99b5 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -271,7 +271,7 @@ fn invalid_visibility(&self, vis: &Visibility, note: Option Option { debug!("give_region_a_name: error_region = {:?}", error_region); match *error_region { - ty::ReEarlyBound(ebr) => { - if ebr.has_name() { - let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP); - Some(RegionName { - name: ebr.name, - source: RegionNameSource::NamedEarlyBoundRegion(span), - }) - } else { - None - } - } + ty::ReEarlyBound(ebr) => ebr.has_name().then(|| { + let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP); + RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyBoundRegion(span) } + }), ty::ReStatic => { Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static }) diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index d5c401ae1c6..a411aec518e 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -50,13 +50,11 @@ pub(super) fn generate<'mir, 'tcx>( compute_relevant_live_locals(typeck.tcx(), &free_regions, &body); let facts_enabled = use_polonius || AllFacts::enabled(typeck.tcx()); - let polonius_drop_used = if facts_enabled { + let polonius_drop_used = facts_enabled.then(|| { let mut drop_used = Vec::new(); polonius::populate_access_facts(typeck, body, location_table, move_data, &mut drop_used); - Some(drop_used) - } else { - None - }; + drop_used + }); trace::trace( typeck, diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index e8a353b1c8f..d30e8ba4b93 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -135,19 +135,17 @@ fn expr_for_field( } // `let names: &'static _ = &["field1", "field2"];` - let names_let = if is_struct { + let names_let = is_struct.then(|| { let lt_static = Some(cx.lifetime_static(span)); let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not); - Some(cx.stmt_let_ty( + cx.stmt_let_ty( span, false, Ident::new(sym::names, span), Some(ty_static_ref), cx.expr_array_ref(span, name_exprs), - )) - } else { - None - }; + ) + }); // `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];` let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug])); diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 970b9115d8d..7fc735dbafa 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -942,13 +942,11 @@ fn extract_arg_details( let mut nonself_arg_tys = Vec::new(); let span = trait_.span; - let explicit_self = if self.explicit_self { + let explicit_self = self.explicit_self.then(|| { let (self_expr, explicit_self) = ty::get_explicit_self(cx, span); selflike_args.push(self_expr); - Some(explicit_self) - } else { - None - }; + explicit_self + }); for (ty, name) in self.nonself_args.iter() { let ast_ty = ty.to_ty(cx, span, type_ident, generics); diff --git a/compiler/rustc_codegen_cranelift/src/driver/aot.rs b/compiler/rustc_codegen_cranelift/src/driver/aot.rs index 58b01dfb5b0..7c6fd9f6f1e 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/aot.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/aot.rs @@ -248,17 +248,13 @@ fn reuse_workproduct_for_cgu( dwarf_object: None, bytecode: None, }, - module_global_asm: if has_global_asm { - Some(CompiledModule { - name: cgu.name().to_string(), - kind: ModuleKind::Regular, - object: Some(obj_out_global_asm), - dwarf_object: None, - bytecode: None, - }) - } else { - None - }, + module_global_asm: has_global_asm.then(|| CompiledModule { + name: cgu.name().to_string(), + kind: ModuleKind::Regular, + object: Some(obj_out_global_asm), + dwarf_object: None, + bytecode: None, + }), existing_work_product: Some((cgu.work_product_id(), work_product)), }) } diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 38f8733763d..fb160669436 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -412,11 +412,7 @@ fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option { } fn get_instr_profile_output_path(config: &ModuleConfig) -> Option { - if config.instrument_coverage { - Some(CString::new("default_%m_%p.profraw").unwrap()) - } else { - None - } + config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap()) } pub(crate) unsafe fn llvm_optimize( @@ -451,11 +447,10 @@ pub(crate) unsafe fn llvm_optimize( None }; - let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() { - Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap())) - } else { - None - }; + let mut llvm_profiler = cgcx + .prof + .llvm_recording_enabled() + .then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap())); let llvm_selfprofiler = llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut()); diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 120dc59dfb3..8848ea3bb9a 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -402,12 +402,8 @@ pub(crate) fn new( let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod()); - let coverage_cx = if tcx.sess.instrument_coverage() { - let covctx = coverageinfo::CrateCoverageContext::new(); - Some(covctx) - } else { - None - }; + let coverage_cx = + tcx.sess.instrument_coverage().then(coverageinfo::CrateCoverageContext::new); let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None { let dctx = debuginfo::CodegenUnitDebugContext::new(llmod); diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 0cb4bc806a1..b45b76e36dd 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -154,7 +154,7 @@ fn struct_llfields<'a, 'tcx>( } else { debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size); } - let field_remapping = if padding_used { Some(field_remapping) } else { None }; + let field_remapping = padding_used.then(|| field_remapping); (result, packed, field_remapping) } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 6e136db3895..023d38e9312 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -579,7 +579,7 @@ pub fn codegen_crate( } } - let metadata_module = if need_metadata_module { + let metadata_module = need_metadata_module.then(|| { // Emit compressed metadata object. let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string(); @@ -594,17 +594,15 @@ pub fn codegen_crate( if let Err(error) = std::fs::write(&file_name, data) { tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error }); } - Some(CompiledModule { + CompiledModule { name: metadata_cgu_name, kind: ModuleKind::Metadata, object: Some(file_name), dwarf_object: None, bytecode: None, - }) + } }) - } else { - None - }; + }); let ongoing_codegen = start_async_codegen( backend.clone(), diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index de1734332d4..eec91ffa44a 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -167,8 +167,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( start_bx.set_personality_fn(cx.eh_personality()); } - let cleanup_kinds = - if base::wants_msvc_seh(cx.tcx().sess) { Some(analyze::cleanup_kinds(&mir)) } else { None }; + let cleanup_kinds = base::wants_msvc_seh(cx.tcx().sess).then(|| analyze::cleanup_kinds(&mir)); let cached_llbbs: IndexVec> = mir.basic_blocks diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index 3aca03f6e5c..44331683694 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -207,8 +207,7 @@ fn cold_call(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_> /// a measureme event, "verbose" generic activities also print a timing entry to /// stderr if the compiler is invoked with -Ztime-passes. pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> { - let message = - if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None }; + let message = self.print_verbose_generic_activities.then(|| event_label.to_owned()); VerboseTimingGuard::start(message, self.generic_activity(event_label)) } @@ -222,11 +221,9 @@ pub fn verbose_generic_activity_with_arg( where A: Borrow + Into, { - let message = if self.print_verbose_generic_activities { - Some(format!("{}({})", event_label, event_arg.borrow())) - } else { - None - }; + let message = self + .print_verbose_generic_activities + .then(|| format!("{}({})", event_label, event_arg.borrow())); VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg)) } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 83b733d4c06..4b3c0c055ad 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1066,29 +1066,26 @@ pub fn err_count(&self) -> usize { } pub fn has_errors(&self) -> Option { - if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None } + self.inner.borrow().has_errors().then(ErrorGuaranteed::unchecked_claim_error_was_emitted) } pub fn has_errors_or_lint_errors(&self) -> Option { - if self.inner.borrow().has_errors_or_lint_errors() { - Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) - } else { - None - } + self.inner + .borrow() + .has_errors_or_lint_errors() + .then(ErrorGuaranteed::unchecked_claim_error_was_emitted) } pub fn has_errors_or_delayed_span_bugs(&self) -> Option { - if self.inner.borrow().has_errors_or_delayed_span_bugs() { - Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) - } else { - None - } + self.inner + .borrow() + .has_errors_or_delayed_span_bugs() + .then(ErrorGuaranteed::unchecked_claim_error_was_emitted) } pub fn is_compilation_going_to_fail(&self) -> Option { - if self.inner.borrow().is_compilation_going_to_fail() { - Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) - } else { - None - } + self.inner + .borrow() + .is_compilation_going_to_fail() + .then(ErrorGuaranteed::unchecked_claim_error_was_emitted) } pub fn print_error_count(&self, registry: &Registry) { diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 1fcbdfd9be5..0da4731489d 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -238,12 +238,10 @@ macro_rules! configure { impl<'a> StripUnconfigured<'a> { pub fn configure(&self, mut node: T) -> Option { self.process_cfg_attrs(&mut node); - if self.in_cfg(node.attrs()) { + self.in_cfg(node.attrs()).then(|| { self.try_configure_tokens(&mut node); - Some(node) - } else { - None - } + node + }) } fn try_configure_tokens(&self, node: &mut T) { @@ -257,7 +255,7 @@ fn try_configure_tokens(&self, node: &mut T) { fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option { attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); - if self.in_cfg(&attrs) { Some(attrs) } else { None } + self.in_cfg(&attrs).then(|| attrs) } /// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`. diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 7cb3b6e1525..80ec1caf521 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -574,14 +574,11 @@ pub fn span_for_lifetime_suggestion(&self) -> Option { /// If there are generic parameters, return where to introduce a new one. pub fn span_for_param_suggestion(&self) -> Option { - if self.params.iter().any(|p| self.span.contains(p.span)) { + self.params.iter().any(|p| self.span.contains(p.span)).then(|| { // `fn foo(t: impl Trait)` // ^ suggest `, T: Trait` here - let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo(); - Some(span) - } else { - None - } + self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo() + }) } /// `Span` where further predicates would be suggested, accounting for trailing commas, like @@ -639,7 +636,7 @@ pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option, def_id: DefId) -> Ty<'_> { } TraitItemKind::Const(ty, body_id) => body_id .and_then(|body_id| { - if is_suggestable_infer_ty(ty) { - Some(infer_placeholder_type( - tcx, def_id, body_id, ty.span, item.ident, "constant", - )) - } else { - None - } + is_suggestable_infer_ty(ty) + .then(|| infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant",)) }) .unwrap_or_else(|| icx.to_ty(ty)), TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty), diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 05f6d8e6072..dbd0c5abeac 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -74,15 +74,13 @@ pub(super) fn check_fn<'a, 'tcx>( // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). - let maybe_va_list = if fn_sig.c_variadic { + let maybe_va_list = fn_sig.c_variadic.then(|| { let span = body.params.last().unwrap().span; let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); - Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()])) - } else { - None - }; + tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]) + }); // Add formal parameters. let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs); diff --git a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs index 29ed9a24ecf..015a2f3bdbe 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs @@ -274,12 +274,10 @@ pub fn resolve_interior<'a, 'tcx>( let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br)); r }); - if captured_tys.insert(ty) { + captured_tys.insert(ty).then(|| { cause.ty = ty; - Some(cause) - } else { - None - } + cause + }) }) .collect(); diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index 4c0f457b46a..5643d1d9f74 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -90,20 +90,18 @@ pub fn find_param_with_region<'tcx>( r } }); - if found_anon_region { + found_anon_region.then(|| { let ty_hir_id = fn_decl.inputs[index].hir_id; let param_ty_span = hir.span(ty_hir_id); let is_first = index == 0; - Some(AnonymousParamInfo { + AnonymousParamInfo { param, param_ty: new_param_ty, param_ty_span, bound_region, is_first, - }) - } else { - None - } + } + }) }) } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index f18c0aa377f..ad0a207413e 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2308,11 +2308,7 @@ fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { .for_each(|(&name, &span)| { let note = rustc_feature::find_feature_issue(name, GateIssue::Language) .map(|n| BuiltinIncompleteFeaturesNote { n }); - let help = if HAS_MIN_FEATURES.contains(&name) { - Some(BuiltinIncompleteFeaturesHelp) - } else { - None - }; + let help = HAS_MIN_FEATURES.contains(&name).then(|| BuiltinIncompleteFeaturesHelp); cx.emit_spanned_lint( INCOMPLETE_FEATURES, span, diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 972240f42cf..f8e4b246487 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -487,7 +487,7 @@ fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> { let mut groups: Vec<_> = self .lint_groups .iter() - .filter_map(|(k, LintGroup { depr, .. })| if depr.is_none() { Some(k) } else { None }) + .filter_map(|(k, LintGroup { depr, .. })| depr.is_none().then(|| k)) .collect(); groups.sort(); let groups = groups.iter().map(|k| Symbol::intern(k)); @@ -1112,11 +1112,9 @@ pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { .maybe_typeck_results() .filter(|typeck_results| typeck_results.hir_owner == id.owner) .or_else(|| { - if self.tcx.has_typeck_results(id.owner.to_def_id()) { - Some(self.tcx.typeck(id.owner.def_id)) - } else { - None - } + self.tcx + .has_typeck_results(id.owner.to_def_id()) + .then(|| self.tcx.typeck(id.owner.def_id)) }) .and_then(|typeck_results| typeck_results.type_dependent_def(id)) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index 1add352e0c4..a3367ae4a9f 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -65,11 +65,8 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { } else { ForLoopsOverFalliblesLoopSub::UseWhileLet { start_span: expr.span.with_hi(pat.span.lo()), end_span: pat.span.between(arg.span), var } } ; - let question_mark = if suggest_question_mark(cx, adt, substs, expr.span) { - Some(ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() }) - } else { - None - }; + let question_mark = suggest_question_mark(cx, adt, substs, expr.span) + .then(|| ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() }); let suggestion = ForLoopsOverFalliblesSuggestion { var, start_span: expr.span.with_hi(pat.span.lo()), diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index ba93330d581..2eafc356dc3 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1062,7 +1062,7 @@ pub fn span_with_body(self, hir_id: HirId) -> Span { } pub fn span_if_local(self, id: DefId) -> Option { - if id.is_local() { Some(self.tcx.def_span(id)) } else { None } + id.is_local().then(|| self.tcx.def_span(id)) } pub fn res_span(self, res: Res) -> Option { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 4aef071cd98..ba8b58e4480 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1113,13 +1113,11 @@ pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx ty::FnDef(_, _) => { let sig = ret_ty.fn_sig(self); let output = self.erase_late_bound_regions(sig.output()); - if output.is_impl_trait() { + output.is_impl_trait().then(|| { let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id); let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap(); - Some((output, fn_decl.output.span())) - } else { - None - } + (output, fn_decl.output.span()) + }) } _ => None, } @@ -1225,13 +1223,12 @@ macro_rules! nop_lift { impl<'a, 'tcx> Lift<'tcx> for $ty { type Lifted = $lifted; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { - if tcx.interners.$set.contains_pointer_to(&InternedInSet(&*self.0.0)) { + tcx.interners + .$set + .contains_pointer_to(&InternedInSet(&*self.0.0)) // SAFETY: `self` is interned and therefore valid // for the entire lifetime of the `TyCtxt`. - Some(unsafe { mem::transmute(self) }) - } else { - None - } + .then(|| unsafe { mem::transmute(self) }) } } }; @@ -1246,13 +1243,13 @@ fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { if self.is_empty() { return Some(List::empty()); } - if tcx.interners.substs.contains_pointer_to(&InternedInSet(self.as_substs())) { + + tcx.interners + .substs + .contains_pointer_to(&InternedInSet(self.as_substs())) // SAFETY: `self` is interned and therefore valid // for the entire lifetime of the `TyCtxt`. - Some(unsafe { mem::transmute::<&'a List>, &'tcx List>>(self) }) - } else { - None - } + .then(|| unsafe { mem::transmute::<&'a List>, &'tcx List>>(self) }) } } @@ -1264,11 +1261,10 @@ fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { if self.is_empty() { return Some(List::empty()); } - if tcx.interners.$set.contains_pointer_to(&InternedInSet(self)) { - Some(unsafe { mem::transmute(self) }) - } else { - None - } + tcx.interners + .$set + .contains_pointer_to(&InternedInSet(self)) + .then(|| unsafe { mem::transmute(self) }) } } }; diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 55f2395e531..1464199a60a 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -584,7 +584,7 @@ pub fn fn_once_adapter_instance( /// this function returns `None`, then the MIR body does not require substitution during /// codegen. fn substs_for_mir_body(&self) -> Option> { - if self.def.has_polymorphic_mir_body() { Some(self.substs) } else { None } + self.def.has_polymorphic_mir_body().then(|| self.substs) } pub fn subst_mir(&self, tcx: TyCtxt<'tcx>, v: &T) -> T diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index a6ab7440c8e..6b4a6a17aef 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -267,13 +267,11 @@ fn decode(d: &mut D) -> GenericArg<'tcx> { impl<'tcx> InternalSubsts<'tcx> { /// Checks whether all elements of this list are types, if so, transmute. pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List>> { - if self.iter().all(|arg| matches!(arg.unpack(), GenericArgKind::Type(_))) { + self.iter().all(|arg| matches!(arg.unpack(), GenericArgKind::Type(_))).then(|| { assert_eq!(TYPE_TAG, 0); // SAFETY: All elements are types, see `List>::as_substs`. - Some(unsafe { &*(self as *const List> as *const List>) }) - } else { - None - } + unsafe { &*(self as *const List> as *const List>) } + }) } /// Interpret these substitutions as the substitutions of a closure type. diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 38b1fa91d0a..dac9bf0a883 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -319,7 +319,7 @@ pub(crate) fn expr_into_dest( // See the notes for `ExprKind::Array` in `as_rvalue` and for // `ExprKind::Borrow` above. let is_union = adt_def.is_union(); - let active_field_index = if is_union { Some(fields[0].name.index()) } else { None }; + let active_field_index = is_union.then(|| fields[0].name.index()); let scope = this.local_scope(); diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index ad7a568a231..8859f5002e4 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -563,14 +563,11 @@ pub(super) fn sort_candidate<'pat>( let not_contained = self.values_not_contained_in_range(&*range, options).unwrap_or(false); - if not_contained { + not_contained.then(|| { // No switch values are contained in the pattern range, // so the pattern can be matched only if this test fails. - let otherwise = options.len(); - Some(otherwise) - } else { - None - } + options.len() + }) } (&TestKind::SwitchInt { .. }, _) => None, diff --git a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs index 977c4b4ae6c..e5b7d685c49 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs @@ -172,7 +172,7 @@ fn from_range<'tcx>( ty: Ty<'tcx>, end: &RangeEnd, ) -> Option { - if Self::is_integral(ty) { + Self::is_integral(ty).then(|| { // Perform a shift if the underlying types are signed, // which makes the interval arithmetic simpler. let bias = IntRange::signed_bias(tcx, ty); @@ -182,10 +182,8 @@ fn from_range<'tcx>( // This should have been caught earlier by E0030. bug!("malformed range pattern: {}..={}", lo, (hi - offset)); } - Some(IntRange { range: lo..=(hi - offset), bias }) - } else { - None - } + IntRange { range: lo..=(hi - offset), bias } + }) } // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it. diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 47ca0a87fcc..57090e12243 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -203,11 +203,7 @@ fn lower_pattern_range( if !lower_overflow && !higher_overflow { self.tcx.sess.emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper { span, - teach: if self.tcx.sess.teach(&error_code!(E0030)) { - Some(()) - } else { - None - }, + teach: self.tcx.sess.teach(&error_code!(E0030)).then(|| ()), }); } PatKind::Wild diff --git a/compiler/rustc_mir_dataflow/src/impls/liveness.rs b/compiler/rustc_mir_dataflow/src/impls/liveness.rs index 2890fa32cc9..fce2ae01edd 100644 --- a/compiler/rustc_mir_dataflow/src/impls/liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/liveness.rs @@ -254,13 +254,7 @@ fn apply_statement_effect( ) { // Compute the place that we are storing to, if any let destination = match &statement.kind { - StatementKind::Assign(assign) => { - if assign.1.is_safe_to_remove() { - Some(assign.0) - } else { - None - } - } + StatementKind::Assign(assign) => assign.1.is_safe_to_remove().then(|| assign.0), StatementKind::SetDiscriminant { place, .. } | StatementKind::Deinit(place) => { Some(**place) } diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index aa19b1fdb5e..66d32b954e4 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -111,11 +111,9 @@ fn check_bound_args( /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option> { if let ty::PredicateKind::Clause(ty::Clause::Trait(predicate)) = bound { - if self.tcx.is_diagnostic_item(sym::Pointer, predicate.def_id()) { - Some(predicate.trait_ref.self_ty()) - } else { - None - } + self.tcx + .is_diagnostic_item(sym::Pointer, predicate.def_id()) + .then(|| predicate.trait_ref.self_ty()) } else { None } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 0cb88f3c3a9..a74f408d774 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1283,22 +1283,16 @@ fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> { } fn parse_delim_args_inner(&mut self) -> Option { - if self.check(&token::OpenDelim(Delimiter::Parenthesis)) + let delimited = self.check(&token::OpenDelim(Delimiter::Parenthesis)) || self.check(&token::OpenDelim(Delimiter::Bracket)) - || self.check(&token::OpenDelim(Delimiter::Brace)) - { - match self.parse_token_tree() { - // We've confirmed above that there is a delimiter so unwrapping is OK. - TokenTree::Delimited(dspan, delim, tokens) => Some(DelimArgs { - dspan, - delim: MacDelimiter::from_token(delim).unwrap(), - tokens, - }), - _ => unreachable!(), - } - } else { - None - } + || self.check(&token::OpenDelim(Delimiter::Brace)); + + 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!() }; + + DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens } + }) } fn parse_or_use_outer_attributes( diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 2e706a00cf7..49959a8981c 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -404,7 +404,7 @@ fn parse_angle_args_with_leading_angle_bracket_recovery( let is_first_invocation = style == PathStyle::Expr; // Take a snapshot before attempting to parse - we can restore this later. - let snapshot = if is_first_invocation { Some(self.clone()) } else { None }; + let snapshot = is_first_invocation.then(|| self.clone()); debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)"); match self.parse_angle_args(ty_generics) { diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 5b92563fc35..46f9c910abd 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -450,8 +450,7 @@ fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> { fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { let and_span = self.prev_token.span; - let mut opt_lifetime = - if self.check_lifetime() { Some(self.expect_lifetime()) } else { None }; + let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime()); let mut mutbl = self.parse_mutability(); if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() { // A lifetime is invalid here: it would be part of a bare trait bound, which requires @@ -871,7 +870,7 @@ fn parse_ty_bound_modifiers(&mut self) -> PResult<'a, BoundModifiers> { None }; - let maybe = if self.eat(&token::Question) { Some(self.prev_token.span) } else { None }; + let maybe = self.eat(&token::Question).then(|| self.prev_token.span); Ok(BoundModifiers { maybe, maybe_const }) } diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index 34a4fd02ea6..2a86738b528 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -835,7 +835,7 @@ fn integer(&mut self) -> Option { ); } - if found { Some(cur) } else { None } + found.then(|| cur) } fn suggest_format(&mut self) { diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index 10ffa87efe3..0ae7096642c 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -32,11 +32,8 @@ fn collect_item(tcx: TyCtxt<'_>, items: &mut DiagnosticItems, name: Symbol, item if let Some(original_def_id) = items.name_to_id.insert(name, item_def_id) { if original_def_id != item_def_id { let orig_span = tcx.hir().span_if_local(original_def_id); - let orig_crate_name = if orig_span.is_some() { - None - } else { - Some(tcx.crate_name(original_def_id.krate)) - }; + let orig_crate_name = + orig_span.is_none().then(|| tcx.crate_name(original_def_id.krate)); match tcx.hir().span_if_local(item_def_id) { Some(span) => tcx.sess.emit_err(DuplicateDiagnosticItem { span, name }), None => tcx.sess.emit_err(DuplicateDiagnosticItemInCrate { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 7299fc9705c..aca6120fa0d 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -281,7 +281,7 @@ fn annotate( self.recurse_with_stability_attrs( depr.map(|(d, _)| DeprecationEntry::local(d, def_id)), stab, - if inherit_const_stability.yes() { const_stab } else { None }, + inherit_const_stability.yes().then(|| const_stab).flatten(), visit_children, ); } diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index a81595b2420..29513df460f 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -242,8 +242,7 @@ pub fn new( record_graph: bool, record_stats: bool, ) -> Self { - let record_graph = - if record_graph { Some(Lock::new(DepGraphQuery::new(prev_node_count))) } else { None }; + let record_graph = record_graph.then(|| Lock::new(DepGraphQuery::new(prev_node_count))); let status = Lock::new(EncoderState::new(encoder, record_stats)); GraphEncoder { status, record_graph } } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index a3195a64366..5205d055cf9 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1700,11 +1700,9 @@ fn lookup_typo_candidate( let crate_mod = Res::Def(DefKind::Mod, crate_id.as_def_id()); - if filter_fn(crate_mod) { - Some(TypoSuggestion::typo_from_ident(*ident, crate_mod)) - } else { - None - } + filter_fn(crate_mod).then(|| { + TypoSuggestion::typo_from_ident(*ident, crate_mod) + }) }) })); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index e8bc19f88e3..b0bc199c832 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2544,7 +2544,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { } // Only use this directory if it has a file we can expect to always find. - if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None } + candidate.join("library/std/src/lib.rs").is_file().then(|| candidate) }; let working_dir = std::env::current_dir().unwrap_or_else(|e| { diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index c851145440b..093698f3b35 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -322,11 +322,7 @@ fn fix_base_capitalisation(prefix: &str, suffix: &str) -> Option { .take_while(|c| *c != 'i' && *c != 'u') .all(|c| c.to_digit(base).is_some()); - if valid { - Some(format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..])) - } else { - None - } + valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..])) } let token::Lit { kind, symbol, suffix, .. } = lit; diff --git a/compiler/rustc_session/src/filesearch.rs b/compiler/rustc_session/src/filesearch.rs index b6a328908ce..855dde0a614 100644 --- a/compiler/rustc_session/src/filesearch.rs +++ b/compiler/rustc_session/src/filesearch.rs @@ -217,7 +217,7 @@ fn from_env_args_next() -> Option { // Look for the target rustlib directory in the suspected sysroot. let mut rustlib_path = rustc_target::target_rustlib_path(&p, "dummy"); rustlib_path.pop(); // pop off the dummy target. - if rustlib_path.exists() { Some(p) } else { None } + rustlib_path.exists().then(|| p) } None => None, } diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index d9e68320f8f..03e9c95e132 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -809,7 +809,7 @@ pub(crate) fn parse_mir_spanview(slot: &mut Option, v: Option<&str> if v.is_some() { let mut bool_arg = None; if parse_opt_bool(&mut bool_arg, v) { - *slot = if bool_arg.unwrap() { Some(MirSpanview::Statement) } else { None }; + *slot = bool_arg.unwrap().then(|| MirSpanview::Statement); return true; } } @@ -850,7 +850,7 @@ pub(crate) fn parse_instrument_coverage( if v.is_some() { let mut bool_arg = None; if parse_opt_bool(&mut bool_arg, v) { - *slot = if bool_arg.unwrap() { Some(InstrumentCoverage::All) } else { None }; + *slot = bool_arg.unwrap().then(|| InstrumentCoverage::All); return true; } } diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index cdda052f529..bcd35066cda 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -299,7 +299,7 @@ pub fn is_local(self) -> bool { #[inline] pub fn as_local(self) -> Option { - if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None } + self.is_local().then(|| LocalDefId { local_def_index: self.index }) } #[inline] @@ -320,7 +320,7 @@ pub fn is_crate_root(self) -> bool { #[inline] pub fn as_crate_root(self) -> Option { - if self.is_crate_root() { Some(self.krate) } else { None } + self.is_crate_root().then(|| self.krate) } #[inline] diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs index 547a5907660..d81722e59a6 100644 --- a/compiler/rustc_symbol_mangling/src/lib.rs +++ b/compiler/rustc_symbol_mangling/src/lib.rs @@ -244,8 +244,7 @@ fn compute_symbol_name<'tcx>( // project. let avoid_cross_crate_conflicts = is_generic(substs) || is_globally_shared_function; - let instantiating_crate = - if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None }; + let instantiating_crate = avoid_cross_crate_conflicts.then(compute_instantiating_crate); // Pick the crate responsible for the symbol mangling version, which has to: // 1. be stable for each instance, whether it's being defined or imported 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 135232d1b20..24feb8b0625 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -82,11 +82,8 @@ fn try_get_upvar_span( upvars.iter().find_map(|(upvar_id, upvar)| { let upvar_ty = typeck_results.node_type(*upvar_id); let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty); - if ty_matches(ty::Binder::dummy(upvar_ty)) { - Some(GeneratorInteriorOrUpvar::Upvar(upvar.span)) - } else { - None - } + ty_matches(ty::Binder::dummy(upvar_ty)) + .then(|| GeneratorInteriorOrUpvar::Upvar(upvar.span)) }) }) } @@ -770,15 +767,13 @@ fn suggest_dereferences( obligation.param_env, real_trait_pred_and_ty, ); - if obligations + let may_hold = obligations .iter() .chain([&obligation]) .all(|obligation| self.predicate_may_hold(obligation)) - { - Some(steps) - } else { - None - } + .then(|| steps); + + may_hold }) { if steps > 0 { diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 41ee8cd9d3f..2d299486ee6 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -523,16 +523,14 @@ fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow { let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id }; let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| { - if pred.visit_with(&mut visitor).is_continue() { - Some(Obligation::new( + pred.visit_with(&mut visitor).is_continue().then(|| { + Obligation::new( tcx, ObligationCause::dummy_with_span(*span), param_env, ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs), - )) - } else { - None - } + ) + }) }); let infcx = tcx.infer_ctxt().ignoring_regions().build(); diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 7ef39b20107..8ddff157249 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -307,7 +307,7 @@ fn predicate_references_self<'tcx>( match predicate.kind().skip_binder() { ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => { // In the case of a trait predicate, we can skip the "self" type. - if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } + data.trait_ref.substs[1..].iter().any(has_self_ty).then(|| sp) } ty::PredicateKind::Clause(ty::Clause::Projection(ref data)) => { // And similarly for projections. This should be redundant with @@ -325,7 +325,7 @@ fn predicate_references_self<'tcx>( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } + data.projection_ty.substs[1..].iter().any(has_self_ty).then(|| sp) } ty::PredicateKind::AliasEq(..) => bug!("`AliasEq` not allowed as assumption"), diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs index 0d42cd8250a..21ef4e24fdb 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs @@ -21,11 +21,7 @@ fn try_fast_path( tcx: TyCtxt<'tcx>, key: &ParamEnvAnd<'tcx, Self>, ) -> Option { - if trivial_dropck_outlives(tcx, key.value.dropped_ty) { - Some(DropckOutlivesResult::default()) - } else { - None - } + trivial_dropck_outlives(tcx, key.value.dropped_ty).then(DropckOutlivesResult::default) } fn perform_query( diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index fc9678233c3..1c651ff1d15 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -378,11 +378,8 @@ fn candidate_from_obligation_no_cache<'o>( let self_ty = trait_ref.self_ty(); let (trait_desc, self_desc) = with_no_trimmed_paths!({ let trait_desc = trait_ref.print_only_trait_path().to_string(); - let self_desc = if self_ty.has_concrete_skeleton() { - Some(self_ty.to_string()) - } else { - None - }; + let self_desc = + self_ty.has_concrete_skeleton().then(|| self_ty.to_string()); (trait_desc, self_desc) }); let cause = if let Conflict::Upstream = conflict { diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index 0f9196de4fb..b4d314dc04a 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -113,7 +113,7 @@ fn insert( // Only report the `Self` type if it has at least // some outer concrete shell; otherwise, it's // not adding much information. - self_ty: if self_ty.has_concrete_skeleton() { Some(self_ty) } else { None }, + self_ty: self_ty.has_concrete_skeleton().then(|| self_ty), intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes, involves_placeholder: overlap.involves_placeholder, } diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index ad5527f5a77..6a0bfe88c63 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -207,11 +207,8 @@ fn fn_abi_of_instance<'tcx>( let sig = fn_sig_for_fn_abi(tcx, instance, param_env); - let caller_location = if instance.def.requires_caller_location(tcx) { - Some(tcx.caller_location_ty()) - } else { - None - }; + let caller_location = + instance.def.requires_caller_location(tcx).then(|| tcx.caller_location_ty()); fn_abi_new_uncached( &LayoutCx { tcx, param_env },