if $c:expr { Some($r:expr) } else { None } =>> $c.then(|| $r)

This commit is contained in:
Maybe Waffle 2023-02-15 11:43:41 +00:00
parent af3c8b2726
commit 8751fa1a9a
54 changed files with 159 additions and 281 deletions

View file

@ -271,7 +271,7 @@ fn invalid_visibility(&self, vis: &Visibility, note: Option<InvalidVisibilityNot
self.session.emit_err(InvalidVisibility { self.session.emit_err(InvalidVisibility {
span: vis.span, span: vis.span,
implied: if vis.kind.is_pub() { Some(vis.span) } else { None }, implied: vis.kind.is_pub().then(|| vis.span),
note, note,
}); });
} }

View file

@ -1186,11 +1186,7 @@ fn suggest_using_local_if_applicable(
return None; return None;
}; };
debug!("checking call args for uses of inner_param: {:?}", args); debug!("checking call args for uses of inner_param: {:?}", args);
if args.contains(&Operand::Move(inner_param)) { args.contains(&Operand::Move(inner_param)).then(|| (loc, term))
Some((loc, term))
} else {
None
}
}) else { }) else {
debug!("no uses of inner_param found as a by-move call arg"); debug!("no uses of inner_param found as a by-move call arg");
return; return;

View file

@ -280,17 +280,10 @@ fn give_name_from_error_region(&self, fr: RegionVid) -> Option<RegionName> {
debug!("give_region_a_name: error_region = {:?}", error_region); debug!("give_region_a_name: error_region = {:?}", error_region);
match *error_region { match *error_region {
ty::ReEarlyBound(ebr) => { ty::ReEarlyBound(ebr) => ebr.has_name().then(|| {
if ebr.has_name() { let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP); RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyBoundRegion(span) }
Some(RegionName { }),
name: ebr.name,
source: RegionNameSource::NamedEarlyBoundRegion(span),
})
} else {
None
}
}
ty::ReStatic => { ty::ReStatic => {
Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static }) Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })

View file

@ -50,13 +50,11 @@ pub(super) fn generate<'mir, 'tcx>(
compute_relevant_live_locals(typeck.tcx(), &free_regions, &body); compute_relevant_live_locals(typeck.tcx(), &free_regions, &body);
let facts_enabled = use_polonius || AllFacts::enabled(typeck.tcx()); 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(); let mut drop_used = Vec::new();
polonius::populate_access_facts(typeck, body, location_table, move_data, &mut drop_used); polonius::populate_access_facts(typeck, body, location_table, move_data, &mut drop_used);
Some(drop_used) drop_used
} else { });
None
};
trace::trace( trace::trace(
typeck, typeck,

View file

@ -135,19 +135,17 @@ fn expr_for_field(
} }
// `let names: &'static _ = &["field1", "field2"];` // `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 lt_static = Some(cx.lifetime_static(span));
let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not); 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, span,
false, false,
Ident::new(sym::names, span), Ident::new(sym::names, span),
Some(ty_static_ref), Some(ty_static_ref),
cx.expr_array_ref(span, name_exprs), cx.expr_array_ref(span, name_exprs),
)) )
} else { });
None
};
// `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];` // `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];`
let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug])); let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug]));

View file

@ -942,13 +942,11 @@ fn extract_arg_details(
let mut nonself_arg_tys = Vec::new(); let mut nonself_arg_tys = Vec::new();
let span = trait_.span; 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); let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
selflike_args.push(self_expr); selflike_args.push(self_expr);
Some(explicit_self) explicit_self
} else { });
None
};
for (ty, name) in self.nonself_args.iter() { for (ty, name) in self.nonself_args.iter() {
let ast_ty = ty.to_ty(cx, span, type_ident, generics); let ast_ty = ty.to_ty(cx, span, type_ident, generics);

View file

@ -248,17 +248,13 @@ fn reuse_workproduct_for_cgu(
dwarf_object: None, dwarf_object: None,
bytecode: None, bytecode: None,
}, },
module_global_asm: if has_global_asm { module_global_asm: has_global_asm.then(|| CompiledModule {
Some(CompiledModule { name: cgu.name().to_string(),
name: cgu.name().to_string(), kind: ModuleKind::Regular,
kind: ModuleKind::Regular, object: Some(obj_out_global_asm),
object: Some(obj_out_global_asm), dwarf_object: None,
dwarf_object: None, bytecode: None,
bytecode: None, }),
})
} else {
None
},
existing_work_product: Some((cgu.work_product_id(), work_product)), existing_work_product: Some((cgu.work_product_id(), work_product)),
}) })
} }

View file

@ -412,11 +412,7 @@ fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
} }
fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> { fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
if config.instrument_coverage { config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
Some(CString::new("default_%m_%p.profraw").unwrap())
} else {
None
}
} }
pub(crate) unsafe fn llvm_optimize( pub(crate) unsafe fn llvm_optimize(
@ -451,11 +447,10 @@ pub(crate) unsafe fn llvm_optimize(
None None
}; };
let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() { let mut llvm_profiler = cgcx
Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap())) .prof
} else { .llvm_recording_enabled()
None .then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
};
let llvm_selfprofiler = let llvm_selfprofiler =
llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut()); llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());

View file

@ -402,12 +402,8 @@ pub(crate) fn new(
let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod()); let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
let coverage_cx = if tcx.sess.instrument_coverage() { let coverage_cx =
let covctx = coverageinfo::CrateCoverageContext::new(); tcx.sess.instrument_coverage().then(coverageinfo::CrateCoverageContext::new);
Some(covctx)
} else {
None
};
let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None { let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
let dctx = debuginfo::CodegenUnitDebugContext::new(llmod); let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);

View file

@ -154,7 +154,7 @@ fn struct_llfields<'a, 'tcx>(
} else { } else {
debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size); 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) (result, packed, field_remapping)
} }

View file

@ -579,7 +579,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
} }
} }
let metadata_module = if need_metadata_module { let metadata_module = need_metadata_module.then(|| {
// Emit compressed metadata object. // Emit compressed metadata object.
let metadata_cgu_name = let metadata_cgu_name =
cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string(); cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
@ -594,17 +594,15 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
if let Err(error) = std::fs::write(&file_name, data) { if let Err(error) = std::fs::write(&file_name, data) {
tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error }); tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error });
} }
Some(CompiledModule { CompiledModule {
name: metadata_cgu_name, name: metadata_cgu_name,
kind: ModuleKind::Metadata, kind: ModuleKind::Metadata,
object: Some(file_name), object: Some(file_name),
dwarf_object: None, dwarf_object: None,
bytecode: None, bytecode: None,
}) }
}) })
} else { });
None
};
let ongoing_codegen = start_async_codegen( let ongoing_codegen = start_async_codegen(
backend.clone(), backend.clone(),

View file

@ -167,8 +167,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
start_bx.set_personality_fn(cx.eh_personality()); start_bx.set_personality_fn(cx.eh_personality());
} }
let cleanup_kinds = let cleanup_kinds = base::wants_msvc_seh(cx.tcx().sess).then(|| analyze::cleanup_kinds(&mir));
if base::wants_msvc_seh(cx.tcx().sess) { Some(analyze::cleanup_kinds(&mir)) } else { None };
let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> = let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
mir.basic_blocks mir.basic_blocks

View file

@ -207,8 +207,7 @@ fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
/// a measureme event, "verbose" generic activities also print a timing entry to /// a measureme event, "verbose" generic activities also print a timing entry to
/// stderr if the compiler is invoked with -Ztime-passes. /// stderr if the compiler is invoked with -Ztime-passes.
pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> { pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> {
let message = let message = self.print_verbose_generic_activities.then(|| event_label.to_owned());
if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
VerboseTimingGuard::start(message, self.generic_activity(event_label)) VerboseTimingGuard::start(message, self.generic_activity(event_label))
} }
@ -222,11 +221,9 @@ pub fn verbose_generic_activity_with_arg<A>(
where where
A: Borrow<str> + Into<String>, A: Borrow<str> + Into<String>,
{ {
let message = if self.print_verbose_generic_activities { let message = self
Some(format!("{}({})", event_label, event_arg.borrow())) .print_verbose_generic_activities
} else { .then(|| format!("{}({})", event_label, event_arg.borrow()));
None
};
VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg)) VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
} }

View file

@ -1066,29 +1066,26 @@ pub fn err_count(&self) -> usize {
} }
pub fn has_errors(&self) -> Option<ErrorGuaranteed> { pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
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<ErrorGuaranteed> { pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
if self.inner.borrow().has_errors_or_lint_errors() { self.inner
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) .borrow()
} else { .has_errors_or_lint_errors()
None .then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
}
} }
pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> { pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
if self.inner.borrow().has_errors_or_delayed_span_bugs() { self.inner
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) .borrow()
} else { .has_errors_or_delayed_span_bugs()
None .then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
}
} }
pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> { pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
if self.inner.borrow().is_compilation_going_to_fail() { self.inner
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()) .borrow()
} else { .is_compilation_going_to_fail()
None .then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
}
} }
pub fn print_error_count(&self, registry: &Registry) { pub fn print_error_count(&self, registry: &Registry) {

View file

@ -238,12 +238,10 @@ macro_rules! configure {
impl<'a> StripUnconfigured<'a> { impl<'a> StripUnconfigured<'a> {
pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> { pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
self.process_cfg_attrs(&mut node); self.process_cfg_attrs(&mut node);
if self.in_cfg(node.attrs()) { self.in_cfg(node.attrs()).then(|| {
self.try_configure_tokens(&mut node); self.try_configure_tokens(&mut node);
Some(node) node
} else { })
None
}
} }
fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) { fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
@ -257,7 +255,7 @@ fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option<ast::AttrVec> { fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option<ast::AttrVec> {
attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); 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`. /// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`.

View file

@ -574,14 +574,11 @@ pub fn span_for_lifetime_suggestion(&self) -> Option<Span> {
/// If there are generic parameters, return where to introduce a new one. /// If there are generic parameters, return where to introduce a new one.
pub fn span_for_param_suggestion(&self) -> Option<Span> { pub fn span_for_param_suggestion(&self) -> Option<Span> {
if self.params.iter().any(|p| self.span.contains(p.span)) { self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
// `fn foo<A>(t: impl Trait)` // `fn foo<A>(t: impl Trait)`
// ^ suggest `, T: Trait` here // ^ suggest `, T: Trait` here
let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo(); self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
Some(span) })
} else {
None
}
} }
/// `Span` where further predicates would be suggested, accounting for trailing commas, like /// `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<Sp
// We include bounds that come from a `#[derive(_)]` but point at the user's code, // We include bounds that come from a `#[derive(_)]` but point at the user's code,
// as we use this method to get a span appropriate for suggestions. // as we use this method to get a span appropriate for suggestions.
let bs = bound.span(); let bs = bound.span();
if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None } bs.can_be_used_for_suggestions().then(|| bs.shrink_to_hi())
}, },
) )
} }

View file

@ -259,13 +259,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
} }
TraitItemKind::Const(ty, body_id) => body_id TraitItemKind::Const(ty, body_id) => body_id
.and_then(|body_id| { .and_then(|body_id| {
if is_suggestable_infer_ty(ty) { is_suggestable_infer_ty(ty)
Some(infer_placeholder_type( .then(|| infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant",))
tcx, def_id, body_id, ty.span, item.ident, "constant",
))
} else {
None
}
}) })
.unwrap_or_else(|| icx.to_ty(ty)), .unwrap_or_else(|| icx.to_ty(ty)),
TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty), TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),

View file

@ -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` // 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). // (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 span = body.params.last().unwrap().span;
let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()])) tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()])
} else { });
None
};
// Add formal parameters. // Add formal parameters.
let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs); let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);

View file

@ -274,12 +274,10 @@ pub fn resolve_interior<'a, 'tcx>(
let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br)); let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
r r
}); });
if captured_tys.insert(ty) { captured_tys.insert(ty).then(|| {
cause.ty = ty; cause.ty = ty;
Some(cause) cause
} else { })
None
}
}) })
.collect(); .collect();

View file

@ -90,20 +90,18 @@ pub fn find_param_with_region<'tcx>(
r r
} }
}); });
if found_anon_region { found_anon_region.then(|| {
let ty_hir_id = fn_decl.inputs[index].hir_id; let ty_hir_id = fn_decl.inputs[index].hir_id;
let param_ty_span = hir.span(ty_hir_id); let param_ty_span = hir.span(ty_hir_id);
let is_first = index == 0; let is_first = index == 0;
Some(AnonymousParamInfo { AnonymousParamInfo {
param, param,
param_ty: new_param_ty, param_ty: new_param_ty,
param_ty_span, param_ty_span,
bound_region, bound_region,
is_first, is_first,
}) }
} else { })
None
}
}) })
} }

View file

@ -2308,11 +2308,7 @@ fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
.for_each(|(&name, &span)| { .for_each(|(&name, &span)| {
let note = rustc_feature::find_feature_issue(name, GateIssue::Language) let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
.map(|n| BuiltinIncompleteFeaturesNote { n }); .map(|n| BuiltinIncompleteFeaturesNote { n });
let help = if HAS_MIN_FEATURES.contains(&name) { let help = HAS_MIN_FEATURES.contains(&name).then(|| BuiltinIncompleteFeaturesHelp);
Some(BuiltinIncompleteFeaturesHelp)
} else {
None
};
cx.emit_spanned_lint( cx.emit_spanned_lint(
INCOMPLETE_FEATURES, INCOMPLETE_FEATURES,
span, span,

View file

@ -487,7 +487,7 @@ fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
let mut groups: Vec<_> = self let mut groups: Vec<_> = self
.lint_groups .lint_groups
.iter() .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(); .collect();
groups.sort(); groups.sort();
let groups = groups.iter().map(|k| Symbol::intern(k)); 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() .maybe_typeck_results()
.filter(|typeck_results| typeck_results.hir_owner == id.owner) .filter(|typeck_results| typeck_results.hir_owner == id.owner)
.or_else(|| { .or_else(|| {
if self.tcx.has_typeck_results(id.owner.to_def_id()) { self.tcx
Some(self.tcx.typeck(id.owner.def_id)) .has_typeck_results(id.owner.to_def_id())
} else { .then(|| self.tcx.typeck(id.owner.def_id))
None
}
}) })
.and_then(|typeck_results| typeck_results.type_dependent_def(id)) .and_then(|typeck_results| typeck_results.type_dependent_def(id))
.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),

View file

@ -65,11 +65,8 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
} else { } else {
ForLoopsOverFalliblesLoopSub::UseWhileLet { start_span: expr.span.with_hi(pat.span.lo()), end_span: pat.span.between(arg.span), var } 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) { let question_mark = suggest_question_mark(cx, adt, substs, expr.span)
Some(ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() }) .then(|| ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() });
} else {
None
};
let suggestion = ForLoopsOverFalliblesSuggestion { let suggestion = ForLoopsOverFalliblesSuggestion {
var, var,
start_span: expr.span.with_hi(pat.span.lo()), start_span: expr.span.with_hi(pat.span.lo()),

View file

@ -1062,7 +1062,7 @@ pub fn span_with_body(self, hir_id: HirId) -> Span {
} }
pub fn span_if_local(self, id: DefId) -> Option<Span> { pub fn span_if_local(self, id: DefId) -> Option<Span> {
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<Span> { pub fn res_span(self, res: Res) -> Option<Span> {

View file

@ -1113,13 +1113,11 @@ pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx
ty::FnDef(_, _) => { ty::FnDef(_, _) => {
let sig = ret_ty.fn_sig(self); let sig = ret_ty.fn_sig(self);
let output = self.erase_late_bound_regions(sig.output()); 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 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(); let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap();
Some((output, fn_decl.output.span())) (output, fn_decl.output.span())
} else { })
None
}
} }
_ => None, _ => None,
} }
@ -1225,13 +1223,12 @@ macro_rules! nop_lift {
impl<'a, 'tcx> Lift<'tcx> for $ty { impl<'a, 'tcx> Lift<'tcx> for $ty {
type Lifted = $lifted; type Lifted = $lifted;
fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
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 // SAFETY: `self` is interned and therefore valid
// for the entire lifetime of the `TyCtxt`. // for the entire lifetime of the `TyCtxt`.
Some(unsafe { mem::transmute(self) }) .then(|| unsafe { mem::transmute(self) })
} else {
None
}
} }
} }
}; };
@ -1246,13 +1243,13 @@ fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
if self.is_empty() { if self.is_empty() {
return Some(List::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 // SAFETY: `self` is interned and therefore valid
// for the entire lifetime of the `TyCtxt`. // for the entire lifetime of the `TyCtxt`.
Some(unsafe { mem::transmute::<&'a List<Ty<'a>>, &'tcx List<Ty<'tcx>>>(self) }) .then(|| unsafe { mem::transmute::<&'a List<Ty<'a>>, &'tcx List<Ty<'tcx>>>(self) })
} else {
None
}
} }
} }
@ -1264,11 +1261,10 @@ fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
if self.is_empty() { if self.is_empty() {
return Some(List::empty()); return Some(List::empty());
} }
if tcx.interners.$set.contains_pointer_to(&InternedInSet(self)) { tcx.interners
Some(unsafe { mem::transmute(self) }) .$set
} else { .contains_pointer_to(&InternedInSet(self))
None .then(|| unsafe { mem::transmute(self) })
}
} }
} }
}; };

View file

@ -584,7 +584,7 @@ pub fn fn_once_adapter_instance(
/// this function returns `None`, then the MIR body does not require substitution during /// this function returns `None`, then the MIR body does not require substitution during
/// codegen. /// codegen.
fn substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>> { fn substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>> {
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<T>(&self, tcx: TyCtxt<'tcx>, v: &T) -> T pub fn subst_mir<T>(&self, tcx: TyCtxt<'tcx>, v: &T) -> T

View file

@ -267,13 +267,11 @@ fn decode(d: &mut D) -> GenericArg<'tcx> {
impl<'tcx> InternalSubsts<'tcx> { impl<'tcx> InternalSubsts<'tcx> {
/// Checks whether all elements of this list are types, if so, transmute. /// Checks whether all elements of this list are types, if so, transmute.
pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List<Ty<'tcx>>> { pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List<Ty<'tcx>>> {
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); assert_eq!(TYPE_TAG, 0);
// SAFETY: All elements are types, see `List<Ty<'tcx>>::as_substs`. // SAFETY: All elements are types, see `List<Ty<'tcx>>::as_substs`.
Some(unsafe { &*(self as *const List<GenericArg<'tcx>> as *const List<Ty<'tcx>>) }) unsafe { &*(self as *const List<GenericArg<'tcx>> as *const List<Ty<'tcx>>) }
} else { })
None
}
} }
/// Interpret these substitutions as the substitutions of a closure type. /// Interpret these substitutions as the substitutions of a closure type.

View file

@ -319,7 +319,7 @@ pub(crate) fn expr_into_dest(
// See the notes for `ExprKind::Array` in `as_rvalue` and for // See the notes for `ExprKind::Array` in `as_rvalue` and for
// `ExprKind::Borrow` above. // `ExprKind::Borrow` above.
let is_union = adt_def.is_union(); 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(); let scope = this.local_scope();

View file

@ -563,14 +563,11 @@ pub(super) fn sort_candidate<'pat>(
let not_contained = let not_contained =
self.values_not_contained_in_range(&*range, options).unwrap_or(false); 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, // No switch values are contained in the pattern range,
// so the pattern can be matched only if this test fails. // so the pattern can be matched only if this test fails.
let otherwise = options.len(); options.len()
Some(otherwise) })
} else {
None
}
} }
(&TestKind::SwitchInt { .. }, _) => None, (&TestKind::SwitchInt { .. }, _) => None,

View file

@ -172,7 +172,7 @@ fn from_range<'tcx>(
ty: Ty<'tcx>, ty: Ty<'tcx>,
end: &RangeEnd, end: &RangeEnd,
) -> Option<IntRange> { ) -> Option<IntRange> {
if Self::is_integral(ty) { Self::is_integral(ty).then(|| {
// Perform a shift if the underlying types are signed, // Perform a shift if the underlying types are signed,
// which makes the interval arithmetic simpler. // which makes the interval arithmetic simpler.
let bias = IntRange::signed_bias(tcx, ty); let bias = IntRange::signed_bias(tcx, ty);
@ -182,10 +182,8 @@ fn from_range<'tcx>(
// This should have been caught earlier by E0030. // This should have been caught earlier by E0030.
bug!("malformed range pattern: {}..={}", lo, (hi - offset)); bug!("malformed range pattern: {}..={}", lo, (hi - offset));
} }
Some(IntRange { range: lo..=(hi - offset), bias }) IntRange { range: lo..=(hi - offset), bias }
} else { })
None
}
} }
// The return value of `signed_bias` should be XORed with an endpoint to encode/decode it. // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.

View file

@ -203,11 +203,7 @@ fn lower_pattern_range(
if !lower_overflow && !higher_overflow { if !lower_overflow && !higher_overflow {
self.tcx.sess.emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper { self.tcx.sess.emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper {
span, span,
teach: if self.tcx.sess.teach(&error_code!(E0030)) { teach: self.tcx.sess.teach(&error_code!(E0030)).then(|| ()),
Some(())
} else {
None
},
}); });
} }
PatKind::Wild PatKind::Wild

View file

@ -254,13 +254,7 @@ fn apply_statement_effect(
) { ) {
// Compute the place that we are storing to, if any // Compute the place that we are storing to, if any
let destination = match &statement.kind { let destination = match &statement.kind {
StatementKind::Assign(assign) => { StatementKind::Assign(assign) => assign.1.is_safe_to_remove().then(|| assign.0),
if assign.1.is_safe_to_remove() {
Some(assign.0)
} else {
None
}
}
StatementKind::SetDiscriminant { place, .. } | StatementKind::Deinit(place) => { StatementKind::SetDiscriminant { place, .. } | StatementKind::Deinit(place) => {
Some(**place) Some(**place)
} }

View file

@ -111,11 +111,9 @@ fn check_bound_args(
/// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type.
fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option<Ty<'tcx>> { fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option<Ty<'tcx>> {
if let ty::PredicateKind::Clause(ty::Clause::Trait(predicate)) = bound { if let ty::PredicateKind::Clause(ty::Clause::Trait(predicate)) = bound {
if self.tcx.is_diagnostic_item(sym::Pointer, predicate.def_id()) { self.tcx
Some(predicate.trait_ref.self_ty()) .is_diagnostic_item(sym::Pointer, predicate.def_id())
} else { .then(|| predicate.trait_ref.self_ty())
None
}
} else { } else {
None None
} }

View file

@ -1283,22 +1283,16 @@ fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
} }
fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> { fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
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::Bracket))
|| self.check(&token::OpenDelim(Delimiter::Brace)) || self.check(&token::OpenDelim(Delimiter::Brace));
{
match self.parse_token_tree() { delimited.then(|| {
// We've confirmed above that there is a delimiter so unwrapping is OK. // We've confirmed above that there is a delimiter so unwrapping is OK.
TokenTree::Delimited(dspan, delim, tokens) => Some(DelimArgs { let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { unreachable!() };
dspan,
delim: MacDelimiter::from_token(delim).unwrap(), DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens }
tokens, })
}),
_ => unreachable!(),
}
} else {
None
}
} }
fn parse_or_use_outer_attributes( fn parse_or_use_outer_attributes(

View file

@ -404,7 +404,7 @@ fn parse_angle_args_with_leading_angle_bracket_recovery(
let is_first_invocation = style == PathStyle::Expr; let is_first_invocation = style == PathStyle::Expr;
// Take a snapshot before attempting to parse - we can restore this later. // 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)"); debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
match self.parse_angle_args(ty_generics) { match self.parse_angle_args(ty_generics) {

View file

@ -450,8 +450,7 @@ fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
let and_span = self.prev_token.span; let and_span = self.prev_token.span;
let mut opt_lifetime = let mut opt_lifetime = self.check_lifetime().then(|| self.expect_lifetime());
if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
let mut mutbl = self.parse_mutability(); let mut mutbl = self.parse_mutability();
if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() { 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 // 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 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 }) Ok(BoundModifiers { maybe, maybe_const })
} }

View file

@ -835,7 +835,7 @@ fn integer(&mut self) -> Option<usize> {
); );
} }
if found { Some(cur) } else { None } found.then(|| cur)
} }
fn suggest_format(&mut self) { fn suggest_format(&mut self) {

View file

@ -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 let Some(original_def_id) = items.name_to_id.insert(name, item_def_id) {
if original_def_id != item_def_id { if original_def_id != item_def_id {
let orig_span = tcx.hir().span_if_local(original_def_id); let orig_span = tcx.hir().span_if_local(original_def_id);
let orig_crate_name = if orig_span.is_some() { let orig_crate_name =
None orig_span.is_none().then(|| tcx.crate_name(original_def_id.krate));
} else {
Some(tcx.crate_name(original_def_id.krate))
};
match tcx.hir().span_if_local(item_def_id) { match tcx.hir().span_if_local(item_def_id) {
Some(span) => tcx.sess.emit_err(DuplicateDiagnosticItem { span, name }), Some(span) => tcx.sess.emit_err(DuplicateDiagnosticItem { span, name }),
None => tcx.sess.emit_err(DuplicateDiagnosticItemInCrate { None => tcx.sess.emit_err(DuplicateDiagnosticItemInCrate {

View file

@ -281,7 +281,7 @@ fn annotate<F>(
self.recurse_with_stability_attrs( self.recurse_with_stability_attrs(
depr.map(|(d, _)| DeprecationEntry::local(d, def_id)), depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
stab, stab,
if inherit_const_stability.yes() { const_stab } else { None }, inherit_const_stability.yes().then(|| const_stab).flatten(),
visit_children, visit_children,
); );
} }

View file

@ -242,8 +242,7 @@ pub fn new(
record_graph: bool, record_graph: bool,
record_stats: bool, record_stats: bool,
) -> Self { ) -> Self {
let record_graph = let record_graph = record_graph.then(|| Lock::new(DepGraphQuery::new(prev_node_count)));
if record_graph { Some(Lock::new(DepGraphQuery::new(prev_node_count))) } else { None };
let status = Lock::new(EncoderState::new(encoder, record_stats)); let status = Lock::new(EncoderState::new(encoder, record_stats));
GraphEncoder { status, record_graph } GraphEncoder { status, record_graph }
} }

View file

@ -1700,11 +1700,9 @@ fn lookup_typo_candidate(
let crate_mod = let crate_mod =
Res::Def(DefKind::Mod, crate_id.as_def_id()); Res::Def(DefKind::Mod, crate_id.as_def_id());
if filter_fn(crate_mod) { filter_fn(crate_mod).then(|| {
Some(TypoSuggestion::typo_from_ident(*ident, crate_mod)) TypoSuggestion::typo_from_ident(*ident, crate_mod)
} else { })
None
}
}) })
})); }));

View file

@ -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. // 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| { let working_dir = std::env::current_dir().unwrap_or_else(|e| {

View file

@ -322,11 +322,7 @@ fn fix_base_capitalisation(prefix: &str, suffix: &str) -> Option<String> {
.take_while(|c| *c != 'i' && *c != 'u') .take_while(|c| *c != 'i' && *c != 'u')
.all(|c| c.to_digit(base).is_some()); .all(|c| c.to_digit(base).is_some());
if valid { valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
Some(format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
} else {
None
}
} }
let token::Lit { kind, symbol, suffix, .. } = lit; let token::Lit { kind, symbol, suffix, .. } = lit;

View file

@ -217,7 +217,7 @@ fn from_env_args_next() -> Option<PathBuf> {
// Look for the target rustlib directory in the suspected sysroot. // Look for the target rustlib directory in the suspected sysroot.
let mut rustlib_path = rustc_target::target_rustlib_path(&p, "dummy"); let mut rustlib_path = rustc_target::target_rustlib_path(&p, "dummy");
rustlib_path.pop(); // pop off the dummy target. rustlib_path.pop(); // pop off the dummy target.
if rustlib_path.exists() { Some(p) } else { None } rustlib_path.exists().then(|| p)
} }
None => None, None => None,
} }

View file

@ -809,7 +809,7 @@ pub(crate) fn parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>
if v.is_some() { if v.is_some() {
let mut bool_arg = None; let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) { 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; return true;
} }
} }
@ -850,7 +850,7 @@ pub(crate) fn parse_instrument_coverage(
if v.is_some() { if v.is_some() {
let mut bool_arg = None; let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) { 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; return true;
} }
} }

View file

@ -299,7 +299,7 @@ pub fn is_local(self) -> bool {
#[inline] #[inline]
pub fn as_local(self) -> Option<LocalDefId> { pub fn as_local(self) -> Option<LocalDefId> {
if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None } self.is_local().then(|| LocalDefId { local_def_index: self.index })
} }
#[inline] #[inline]
@ -320,7 +320,7 @@ pub fn is_crate_root(self) -> bool {
#[inline] #[inline]
pub fn as_crate_root(self) -> Option<CrateNum> { pub fn as_crate_root(self) -> Option<CrateNum> {
if self.is_crate_root() { Some(self.krate) } else { None } self.is_crate_root().then(|| self.krate)
} }
#[inline] #[inline]

View file

@ -244,8 +244,7 @@ fn compute_symbol_name<'tcx>(
// project. // project.
let avoid_cross_crate_conflicts = is_generic(substs) || is_globally_shared_function; let avoid_cross_crate_conflicts = is_generic(substs) || is_globally_shared_function;
let instantiating_crate = let instantiating_crate = avoid_cross_crate_conflicts.then(compute_instantiating_crate);
if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None };
// Pick the crate responsible for the symbol mangling version, which has to: // 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 // 1. be stable for each instance, whether it's being defined or imported

View file

@ -82,11 +82,8 @@ fn try_get_upvar_span<F>(
upvars.iter().find_map(|(upvar_id, upvar)| { upvars.iter().find_map(|(upvar_id, upvar)| {
let upvar_ty = typeck_results.node_type(*upvar_id); let upvar_ty = typeck_results.node_type(*upvar_id);
let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty); let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
if ty_matches(ty::Binder::dummy(upvar_ty)) { ty_matches(ty::Binder::dummy(upvar_ty))
Some(GeneratorInteriorOrUpvar::Upvar(upvar.span)) .then(|| GeneratorInteriorOrUpvar::Upvar(upvar.span))
} else {
None
}
}) })
}) })
} }
@ -770,15 +767,13 @@ fn suggest_dereferences(
obligation.param_env, obligation.param_env,
real_trait_pred_and_ty, real_trait_pred_and_ty,
); );
if obligations let may_hold = obligations
.iter() .iter()
.chain([&obligation]) .chain([&obligation])
.all(|obligation| self.predicate_may_hold(obligation)) .all(|obligation| self.predicate_may_hold(obligation))
{ .then(|| steps);
Some(steps)
} else { may_hold
None
}
}) })
{ {
if steps > 0 { if steps > 0 {

View file

@ -523,16 +523,14 @@ fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id }; let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| { let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
if pred.visit_with(&mut visitor).is_continue() { pred.visit_with(&mut visitor).is_continue().then(|| {
Some(Obligation::new( Obligation::new(
tcx, tcx,
ObligationCause::dummy_with_span(*span), ObligationCause::dummy_with_span(*span),
param_env, param_env,
ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs), ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
)) )
} else { })
None
}
}); });
let infcx = tcx.infer_ctxt().ignoring_regions().build(); let infcx = tcx.infer_ctxt().ignoring_regions().build();

View file

@ -307,7 +307,7 @@ fn predicate_references_self<'tcx>(
match predicate.kind().skip_binder() { match predicate.kind().skip_binder() {
ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => { ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => {
// In the case of a trait predicate, we can skip the "self" type. // 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)) => { ty::PredicateKind::Clause(ty::Clause::Projection(ref data)) => {
// And similarly for projections. This should be redundant with // 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 // This is ALT2 in issue #56288, see that for discussion of the
// possible alternatives. // 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"), ty::PredicateKind::AliasEq(..) => bug!("`AliasEq` not allowed as assumption"),

View file

@ -21,11 +21,7 @@ fn try_fast_path(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
key: &ParamEnvAnd<'tcx, Self>, key: &ParamEnvAnd<'tcx, Self>,
) -> Option<Self::QueryResponse> { ) -> Option<Self::QueryResponse> {
if trivial_dropck_outlives(tcx, key.value.dropped_ty) { trivial_dropck_outlives(tcx, key.value.dropped_ty).then(DropckOutlivesResult::default)
Some(DropckOutlivesResult::default())
} else {
None
}
} }
fn perform_query( fn perform_query(

View file

@ -378,11 +378,8 @@ fn candidate_from_obligation_no_cache<'o>(
let self_ty = trait_ref.self_ty(); let self_ty = trait_ref.self_ty();
let (trait_desc, self_desc) = with_no_trimmed_paths!({ let (trait_desc, self_desc) = with_no_trimmed_paths!({
let trait_desc = trait_ref.print_only_trait_path().to_string(); let trait_desc = trait_ref.print_only_trait_path().to_string();
let self_desc = if self_ty.has_concrete_skeleton() { let self_desc =
Some(self_ty.to_string()) self_ty.has_concrete_skeleton().then(|| self_ty.to_string());
} else {
None
};
(trait_desc, self_desc) (trait_desc, self_desc)
}); });
let cause = if let Conflict::Upstream = conflict { let cause = if let Conflict::Upstream = conflict {

View file

@ -113,7 +113,7 @@ fn insert(
// Only report the `Self` type if it has at least // Only report the `Self` type if it has at least
// some outer concrete shell; otherwise, it's // some outer concrete shell; otherwise, it's
// not adding much information. // 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, intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
involves_placeholder: overlap.involves_placeholder, involves_placeholder: overlap.involves_placeholder,
} }

View file

@ -207,11 +207,8 @@ fn fn_abi_of_instance<'tcx>(
let sig = fn_sig_for_fn_abi(tcx, instance, param_env); let sig = fn_sig_for_fn_abi(tcx, instance, param_env);
let caller_location = if instance.def.requires_caller_location(tcx) { let caller_location =
Some(tcx.caller_location_ty()) instance.def.requires_caller_location(tcx).then(|| tcx.caller_location_ty());
} else {
None
};
fn_abi_new_uncached( fn_abi_new_uncached(
&LayoutCx { tcx, param_env }, &LayoutCx { tcx, param_env },