Skip to content

Commit 47c0792

Browse files
committed
Auto merge of #108079 - WaffleLapkin:if_not_now_then_when, r=<try>
`if $c:expr { Some($r:expr) } else { None }` =>> `$c.then(|| $r)` TL;DR: turn ```rust if condition { Some(expression) } else { None } ``` into ```rust condition.then(|| expression) ``` This is part one of many of refactoring compiler to use `.then` where it makes code cleaner. This PR does only changes that are simple & clear wins (in my opinion anyway).
2 parents 999ac5f + 7319f5c commit 47c0792

File tree

55 files changed

+161
-286
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+161
-286
lines changed

compiler/rustc_ast_passes/src/ast_validation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ impl<'a> AstValidator<'a> {
271271

272272
self.session.emit_err(InvalidVisibility {
273273
span: vis.span,
274-
implied: if vis.kind.is_pub() { Some(vis.span) } else { None },
274+
implied: vis.kind.is_pub().then(|| vis.span),
275275
note,
276276
});
277277
}

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -1186,11 +1186,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11861186
return None;
11871187
};
11881188
debug!("checking call args for uses of inner_param: {:?}", args);
1189-
if args.contains(&Operand::Move(inner_param)) {
1190-
Some((loc, term))
1191-
} else {
1192-
None
1193-
}
1189+
args.contains(&Operand::Move(inner_param)).then(|| (loc, term))
11941190
}) else {
11951191
debug!("no uses of inner_param found as a by-move call arg");
11961192
return;

compiler/rustc_borrowck/src/diagnostics/region_name.rs

+4-11
Original file line numberDiff line numberDiff line change
@@ -280,17 +280,10 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
280280

281281
debug!("give_region_a_name: error_region = {:?}", error_region);
282282
match *error_region {
283-
ty::ReEarlyBound(ebr) => {
284-
if ebr.has_name() {
285-
let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
286-
Some(RegionName {
287-
name: ebr.name,
288-
source: RegionNameSource::NamedEarlyBoundRegion(span),
289-
})
290-
} else {
291-
None
292-
}
293-
}
283+
ty::ReEarlyBound(ebr) => ebr.has_name().then(|| {
284+
let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
285+
RegionName { name: ebr.name, source: RegionNameSource::NamedEarlyBoundRegion(span) }
286+
}),
294287

295288
ty::ReStatic => {
296289
Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })

compiler/rustc_borrowck/src/type_check/liveness/mod.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,11 @@ pub(super) fn generate<'mir, 'tcx>(
5050
compute_relevant_live_locals(typeck.tcx(), &free_regions, &body);
5151
let facts_enabled = use_polonius || AllFacts::enabled(typeck.tcx());
5252

53-
let polonius_drop_used = if facts_enabled {
53+
let polonius_drop_used = facts_enabled.then(|| {
5454
let mut drop_used = Vec::new();
5555
polonius::populate_access_facts(typeck, body, location_table, move_data, &mut drop_used);
56-
Some(drop_used)
57-
} else {
58-
None
59-
};
56+
drop_used
57+
});
6058

6159
trace::trace(
6260
typeck,

compiler/rustc_builtin_macros/src/deriving/debug.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -135,19 +135,17 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>
135135
}
136136

137137
// `let names: &'static _ = &["field1", "field2"];`
138-
let names_let = if is_struct {
138+
let names_let = is_struct.then(|| {
139139
let lt_static = Some(cx.lifetime_static(span));
140140
let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not);
141-
Some(cx.stmt_let_ty(
141+
cx.stmt_let_ty(
142142
span,
143143
false,
144144
Ident::new(sym::names, span),
145145
Some(ty_static_ref),
146146
cx.expr_array_ref(span, name_exprs),
147-
))
148-
} else {
149-
None
150-
};
147+
)
148+
});
151149

152150
// `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];`
153151
let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug]));

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -942,13 +942,11 @@ impl<'a> MethodDef<'a> {
942942
let mut nonself_arg_tys = Vec::new();
943943
let span = trait_.span;
944944

945-
let explicit_self = if self.explicit_self {
945+
let explicit_self = self.explicit_self.then(|| {
946946
let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
947947
selflike_args.push(self_expr);
948-
Some(explicit_self)
949-
} else {
950-
None
951-
};
948+
explicit_self
949+
});
952950

953951
for (ty, name) in self.nonself_args.iter() {
954952
let ast_ty = ty.to_ty(cx, span, type_ident, generics);

compiler/rustc_codegen_cranelift/src/driver/aot.rs

+7-11
Original file line numberDiff line numberDiff line change
@@ -248,17 +248,13 @@ fn reuse_workproduct_for_cgu(
248248
dwarf_object: None,
249249
bytecode: None,
250250
},
251-
module_global_asm: if has_global_asm {
252-
Some(CompiledModule {
253-
name: cgu.name().to_string(),
254-
kind: ModuleKind::Regular,
255-
object: Some(obj_out_global_asm),
256-
dwarf_object: None,
257-
bytecode: None,
258-
})
259-
} else {
260-
None
261-
},
251+
module_global_asm: has_global_asm.then(|| CompiledModule {
252+
name: cgu.name().to_string(),
253+
kind: ModuleKind::Regular,
254+
object: Some(obj_out_global_asm),
255+
dwarf_object: None,
256+
bytecode: None,
257+
}),
262258
existing_work_product: Some((cgu.work_product_id(), work_product)),
263259
})
264260
}

compiler/rustc_codegen_llvm/src/back/write.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -412,11 +412,7 @@ fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
412412
}
413413

414414
fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
415-
if config.instrument_coverage {
416-
Some(CString::new("default_%m_%p.profraw").unwrap())
417-
} else {
418-
None
419-
}
415+
config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
420416
}
421417

422418
pub(crate) unsafe fn llvm_optimize(
@@ -451,11 +447,10 @@ pub(crate) unsafe fn llvm_optimize(
451447
None
452448
};
453449

454-
let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
455-
Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
456-
} else {
457-
None
458-
};
450+
let mut llvm_profiler = cgcx
451+
.prof
452+
.llvm_recording_enabled()
453+
.then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
459454

460455
let llvm_selfprofiler =
461456
llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());

compiler/rustc_codegen_llvm/src/context.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -402,12 +402,8 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
402402

403403
let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
404404

405-
let coverage_cx = if tcx.sess.instrument_coverage() {
406-
let covctx = coverageinfo::CrateCoverageContext::new();
407-
Some(covctx)
408-
} else {
409-
None
410-
};
405+
let coverage_cx =
406+
tcx.sess.instrument_coverage().then(coverageinfo::CrateCoverageContext::new);
411407

412408
let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
413409
let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);

compiler/rustc_codegen_llvm/src/type_of.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ fn struct_llfields<'a, 'tcx>(
154154
} else {
155155
debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
156156
}
157-
let field_remapping = if padding_used { Some(field_remapping) } else { None };
157+
let field_remapping = padding_used.then(|| field_remapping);
158158
(result, packed, field_remapping)
159159
}
160160

compiler/rustc_codegen_ssa/src/base.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
579579
}
580580
}
581581

582-
let metadata_module = if need_metadata_module {
582+
let metadata_module = need_metadata_module.then(|| {
583583
// Emit compressed metadata object.
584584
let metadata_cgu_name =
585585
cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
@@ -594,17 +594,15 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
594594
if let Err(error) = std::fs::write(&file_name, data) {
595595
tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error });
596596
}
597-
Some(CompiledModule {
597+
CompiledModule {
598598
name: metadata_cgu_name,
599599
kind: ModuleKind::Metadata,
600600
object: Some(file_name),
601601
dwarf_object: None,
602602
bytecode: None,
603-
})
603+
}
604604
})
605-
} else {
606-
None
607-
};
605+
});
608606

609607
let ongoing_codegen = start_async_codegen(
610608
backend.clone(),

compiler/rustc_codegen_ssa/src/mir/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
167167
start_bx.set_personality_fn(cx.eh_personality());
168168
}
169169

170-
let cleanup_kinds =
171-
if base::wants_msvc_seh(cx.tcx().sess) { Some(analyze::cleanup_kinds(&mir)) } else { None };
170+
let cleanup_kinds = base::wants_msvc_seh(cx.tcx().sess).then(|| analyze::cleanup_kinds(&mir));
172171

173172
let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
174173
mir.basic_blocks

compiler/rustc_data_structures/src/profiling.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,7 @@ impl SelfProfilerRef {
207207
/// a measureme event, "verbose" generic activities also print a timing entry to
208208
/// stderr if the compiler is invoked with -Ztime-passes.
209209
pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> {
210-
let message =
211-
if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
210+
let message = self.print_verbose_generic_activities.then(|| event_label.to_owned());
212211

213212
VerboseTimingGuard::start(message, self.generic_activity(event_label))
214213
}
@@ -222,11 +221,9 @@ impl SelfProfilerRef {
222221
where
223222
A: Borrow<str> + Into<String>,
224223
{
225-
let message = if self.print_verbose_generic_activities {
226-
Some(format!("{}({})", event_label, event_arg.borrow()))
227-
} else {
228-
None
229-
};
224+
let message = self
225+
.print_verbose_generic_activities
226+
.then(|| format!("{}({})", event_label, event_arg.borrow()));
230227

231228
VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
232229
}

compiler/rustc_errors/src/lib.rs

+13-16
Original file line numberDiff line numberDiff line change
@@ -1066,29 +1066,26 @@ impl Handler {
10661066
}
10671067

10681068
pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1069-
if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1069+
self.inner.borrow().has_errors().then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
10701070
}
10711071

10721072
pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1073-
if self.inner.borrow().has_errors_or_lint_errors() {
1074-
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1075-
} else {
1076-
None
1077-
}
1073+
self.inner
1074+
.borrow()
1075+
.has_errors_or_lint_errors()
1076+
.then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
10781077
}
10791078
pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
1080-
if self.inner.borrow().has_errors_or_delayed_span_bugs() {
1081-
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1082-
} else {
1083-
None
1084-
}
1079+
self.inner
1080+
.borrow()
1081+
.has_errors_or_delayed_span_bugs()
1082+
.then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
10851083
}
10861084
pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
1087-
if self.inner.borrow().is_compilation_going_to_fail() {
1088-
Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1089-
} else {
1090-
None
1091-
}
1085+
self.inner
1086+
.borrow()
1087+
.is_compilation_going_to_fail()
1088+
.then(ErrorGuaranteed::unchecked_claim_error_was_emitted)
10921089
}
10931090

10941091
pub fn print_error_count(&self, registry: &Registry) {

compiler/rustc_expand/src/config.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,10 @@ macro_rules! configure {
238238
impl<'a> StripUnconfigured<'a> {
239239
pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
240240
self.process_cfg_attrs(&mut node);
241-
if self.in_cfg(node.attrs()) {
241+
self.in_cfg(node.attrs()).then(|| {
242242
self.try_configure_tokens(&mut node);
243-
Some(node)
244-
} else {
245-
None
246-
}
243+
node
244+
})
247245
}
248246

249247
fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
@@ -257,7 +255,7 @@ impl<'a> StripUnconfigured<'a> {
257255

258256
fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option<ast::AttrVec> {
259257
attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
260-
if self.in_cfg(&attrs) { Some(attrs) } else { None }
258+
self.in_cfg(&attrs).then(|| attrs)
261259
}
262260

263261
/// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`.

compiler/rustc_hir/src/hir.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -574,14 +574,11 @@ impl<'hir> Generics<'hir> {
574574

575575
/// If there are generic parameters, return where to introduce a new one.
576576
pub fn span_for_param_suggestion(&self) -> Option<Span> {
577-
if self.params.iter().any(|p| self.span.contains(p.span)) {
577+
self.params.iter().any(|p| self.span.contains(p.span)).then(|| {
578578
// `fn foo<A>(t: impl Trait)`
579579
// ^ suggest `, T: Trait` here
580-
let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
581-
Some(span)
582-
} else {
583-
None
584-
}
580+
self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo()
581+
})
585582
}
586583

587584
/// `Span` where further predicates would be suggested, accounting for trailing commas, like
@@ -639,7 +636,7 @@ impl<'hir> Generics<'hir> {
639636
// We include bounds that come from a `#[derive(_)]` but point at the user's code,
640637
// as we use this method to get a span appropriate for suggestions.
641638
let bs = bound.span();
642-
if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
639+
bs.can_be_used_for_suggestions().then(|| bs.shrink_to_hi())
643640
},
644641
)
645642
}

compiler/rustc_hir_analysis/src/collect/type_of.rs

+2-7
Original file line numberDiff line numberDiff line change
@@ -259,13 +259,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
259259
}
260260
TraitItemKind::Const(ty, body_id) => body_id
261261
.and_then(|body_id| {
262-
if is_suggestable_infer_ty(ty) {
263-
Some(infer_placeholder_type(
264-
tcx, def_id, body_id, ty.span, item.ident, "constant",
265-
))
266-
} else {
267-
None
268-
}
262+
is_suggestable_infer_ty(ty)
263+
.then(|| infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant",))
269264
})
270265
.unwrap_or_else(|| icx.to_ty(ty)),
271266
TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),

compiler/rustc_hir_typeck/src/check.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,13 @@ pub(super) fn check_fn<'a, 'tcx>(
7474

7575
// C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
7676
// (as it's created inside the body itself, not passed in from outside).
77-
let maybe_va_list = if fn_sig.c_variadic {
77+
let maybe_va_list = fn_sig.c_variadic.then(|| {
7878
let span = body.params.last().unwrap().span;
7979
let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
8080
let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
8181

82-
Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
83-
} else {
84-
None
85-
};
82+
tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()])
83+
});
8684

8785
// Add formal parameters.
8886
let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);

compiler/rustc_hir_typeck/src/generator_interior/mod.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -274,12 +274,10 @@ pub fn resolve_interior<'a, 'tcx>(
274274
let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
275275
r
276276
});
277-
if captured_tys.insert(ty) {
277+
captured_tys.insert(ty).then(|| {
278278
cause.ty = ty;
279-
Some(cause)
280-
} else {
281-
None
282-
}
279+
cause
280+
})
283281
})
284282
.collect();
285283

0 commit comments

Comments
 (0)