Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ impl<'a> AstValidator<'a> {

self.session.emit_err(InvalidVisibility {
span: vis.span,
implied: if vis.kind.is_pub() { Some(vis.span) } else { None },
implied: vis.kind.is_pub().then(|| vis.span),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These cases may be simpler as then_some (even if longer 🙃 ). I don't have a strong opinion on then_some usage, beyond it generating less code

note,
});
}
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1186,11 +1186,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
return None;
};
debug!("checking call args for uses of inner_param: {:?}", args);
if args.contains(&Operand::Move(inner_param)) {
Some((loc, term))
} else {
None
}
args.contains(&Operand::Move(inner_param)).then(|| (loc, term))
}) else {
debug!("no uses of inner_param found as a by-move call arg");
return;
Expand Down
15 changes: 4 additions & 11 deletions compiler/rustc_borrowck/src/diagnostics/region_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,17 +280,10 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {

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 })
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_borrowck/src/type_check/liveness/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_builtin_macros/src/deriving/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,17 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>
}

// `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]));
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -942,13 +942,11 @@ impl<'a> MethodDef<'a> {
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);
Expand Down
18 changes: 7 additions & 11 deletions compiler/rustc_codegen_cranelift/src/driver/aot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
})
}
Expand Down
15 changes: 5 additions & 10 deletions compiler/rustc_codegen_llvm/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,11 +412,7 @@ fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
}

fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
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(
Expand Down Expand Up @@ -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());
Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,12 +402,8 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {

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);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
let metadata_cgu_name =
cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
Expand All @@ -594,17 +594,15 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
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(),
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_ssa/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
mir.basic_blocks
Expand Down
11 changes: 4 additions & 7 deletions compiler/rustc_data_structures/src/profiling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,7 @@ impl SelfProfilerRef {
/// 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))
}
Expand All @@ -222,11 +221,9 @@ impl SelfProfilerRef {
where
A: Borrow<str> + Into<String>,
{
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))
}
Expand Down
29 changes: 13 additions & 16 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1066,29 +1066,26 @@ impl Handler {
}

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> {
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<ErrorGuaranteed> {
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<ErrorGuaranteed> {
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) {
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,10 @@ macro_rules! configure {
impl<'a> StripUnconfigured<'a> {
pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
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<T: HasTokens>(&self, node: &mut T) {
Expand All @@ -257,7 +255,7 @@ impl<'a> StripUnconfigured<'a> {

fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option<ast::AttrVec> {
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`.
Expand Down
11 changes: 4 additions & 7 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -574,14 +574,11 @@ impl<'hir> Generics<'hir> {

/// If there are generic parameters, return where to introduce a new one.
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)`
// ^ 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
Expand Down Expand Up @@ -639,7 +636,7 @@ impl<'hir> Generics<'hir> {
// 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.
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())
},
)
}
Expand Down
9 changes: 2 additions & 7 deletions compiler/rustc_hir_analysis/src/collect/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, 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),
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_hir_typeck/src/generator_interior/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
Loading