Skip to content

Commit ca2639e

Browse files
committed
Auto merge of #55014 - ljedrz:lazyboye_unwraps, r=matthewjasper
Prefer unwrap_or_else to unwrap_or in case of function calls/allocations The contents of `unwrap_or` are evaluated eagerly, so it's not a good pick in case of function calls and allocations. This PR also changes a few `unwrap_or`s with `unwrap_or_default`. An added bonus is that in some cases this change also reveals if the object it's called on is an `Option` or a `Result` (based on whether the closure takes an argument).
2 parents 94273f4 + d28aed6 commit ca2639e

File tree

35 files changed

+57
-54
lines changed

35 files changed

+57
-54
lines changed

src/bootstrap/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ impl Config {
430430
}
431431
}).unwrap_or_else(|| TomlConfig::default());
432432

433-
let build = toml.build.clone().unwrap_or(Build::default());
433+
let build = toml.build.clone().unwrap_or_default();
434434
// set by bootstrap.py
435435
config.hosts.push(config.build.clone());
436436
for host in build.host.iter() {
@@ -524,7 +524,7 @@ impl Config {
524524
set(&mut config.llvm_link_shared, llvm.link_shared);
525525
config.llvm_targets = llvm.targets.clone();
526526
config.llvm_experimental_targets = llvm.experimental_targets.clone()
527-
.unwrap_or("WebAssembly;RISCV".to_string());
527+
.unwrap_or_else(|| "WebAssembly;RISCV".to_string());
528528
config.llvm_link_jobs = llvm.link_jobs;
529529
config.llvm_version_suffix = llvm.version_suffix.clone();
530530
config.llvm_clang_cl = llvm.clang_cl.clone();

src/build_helper/lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ pub fn native_lib_boilerplate(
233233
let src_dir = current_dir.join("..").join(src_name);
234234
rerun_if_changed_anything_in_dir(&src_dir);
235235

236-
let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or(env::var_os("OUT_DIR").unwrap());
236+
let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or_else(||
237+
env::var_os("OUT_DIR").unwrap());
237238
let out_dir = PathBuf::from(out_dir).join(out_name);
238239
t!(fs::create_dir_all(&out_dir));
239240
if link_name.contains('=') {

src/librustc/hir/lowering.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1598,7 +1598,7 @@ impl<'a> LoweringContext<'a> {
15981598

15991599
let resolution = self.resolver
16001600
.get_resolution(id)
1601-
.unwrap_or(PathResolution::new(Def::Err));
1601+
.unwrap_or_else(|| PathResolution::new(Def::Err));
16021602

16031603
let proj_start = p.segments.len() - resolution.unresolved_segments();
16041604
let path = P(hir::Path {

src/librustc/lint/levels.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ impl LintLevelSets {
9797

9898
// If `level` is none then we actually assume the default level for this
9999
// lint.
100-
let mut level = level.unwrap_or(lint.default_level(sess));
100+
let mut level = level.unwrap_or_else(|| lint.default_level(sess));
101101

102102
// If we're about to issue a warning, check at the last minute for any
103103
// directives against the warnings "lint". If, for example, there's an

src/librustc/lint/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ impl LintBuffer {
519519
}
520520

521521
pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
522-
self.map.remove(&id).unwrap_or(Vec::new())
522+
self.map.remove(&id).unwrap_or_default()
523523
}
524524

525525
pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {

src/librustc/traits/auto_trait.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -498,8 +498,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
498498
panic!("Missing lifetime with name {:?} for {:?}", name, region)
499499
)
500500
)
501-
.unwrap_or(&"'static".to_owned())
502-
.clone()
501+
.cloned()
502+
.unwrap_or_else(|| "'static".to_owned())
503503
}
504504

505505
// This is very similar to handle_lifetimes. However, instead of matching ty::Region's

src/librustc/traits/error_reporting.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
352352
obligation: &PredicateObligation<'tcx>,
353353
) -> OnUnimplementedNote {
354354
let def_id = self.impl_similar_to(trait_ref, obligation)
355-
.unwrap_or(trait_ref.def_id());
355+
.unwrap_or_else(|| trait_ref.def_id());
356356
let trait_ref = *trait_ref.skip_binder();
357357

358358
let mut flags = vec![];
@@ -639,7 +639,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
639639
let (post_message, pre_message) =
640640
self.get_parent_trait_ref(&obligation.cause.code)
641641
.map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
642-
.unwrap_or((String::new(), String::new()));
642+
.unwrap_or_default();
643643

644644
let OnUnimplementedNote { message, label, note }
645645
= self.on_unimplemented_note(trait_ref, obligation);

src/librustc/ty/context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ impl<'tcx> TypeckTables<'tcx> {
551551

552552
pub fn node_substs(&self, id: hir::HirId) -> &'tcx Substs<'tcx> {
553553
validate_hir_id_for_typeck_tables(self.local_id_root, id, false);
554-
self.node_substs.get(&id.local_id).cloned().unwrap_or(Substs::empty())
554+
self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| Substs::empty())
555555
}
556556

557557
pub fn node_substs_opt(&self, id: hir::HirId) -> Option<&'tcx Substs<'tcx>> {

src/librustc/ty/query/on_disk_cache.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ impl<'sess> OnDiskCache<'sess> {
342342
&self.prev_diagnostics_index,
343343
"diagnostics");
344344

345-
diagnostics.unwrap_or(Vec::new())
345+
diagnostics.unwrap_or_default()
346346
}
347347

348348
/// Store a diagnostic emitted during the current compilation session.

src/librustc_codegen_llvm/attributes.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ pub fn from_fn_attrs(
154154
id: Option<DefId>,
155155
) {
156156
let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
157-
.unwrap_or(CodegenFnAttrs::new());
157+
.unwrap_or_else(|| CodegenFnAttrs::new());
158158

159159
inline(cx, llfn, codegen_fn_attrs.inline);
160160

src/librustc_codegen_llvm/back/rpath.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String
109109
};
110110

111111
let cwd = env::current_dir().unwrap();
112-
let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or(cwd.join(lib));
112+
let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or_else(|_| cwd.join(lib));
113113
lib.pop();
114114
let mut output = cwd.join(&config.out_filename);
115115
output.pop();

src/librustc_codegen_llvm/llvm/archive_ro.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ impl ArchiveRO {
4040
return unsafe {
4141
let s = path2cstr(dst);
4242
let ar = super::LLVMRustOpenArchive(s.as_ptr()).ok_or_else(|| {
43-
super::last_error().unwrap_or("failed to open archive".to_owned())
43+
super::last_error().unwrap_or_else(|| "failed to open archive".to_owned())
4444
})?;
4545
Ok(ArchiveRO { raw: ar })
4646
};

src/librustc_codegen_llvm/llvm/diagnostic.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ impl OptimizationDiagnostic<'ll> {
7777
).ok()
7878
).ok();
7979

80-
let mut filename = filename.unwrap_or(String::new());
80+
let mut filename = filename.unwrap_or_default();
8181
if filename.is_empty() {
8282
filename.push_str("<unknown file>");
8383
}

src/librustc_codegen_utils/link.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ pub fn filename_for_metadata(sess: &Session,
103103
let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
104104

105105
let out_filename = outputs.single_output_file.clone()
106-
.unwrap_or(outputs.out_directory.join(&format!("lib{}.rmeta", libname)));
106+
.unwrap_or_else(|| outputs.out_directory.join(&format!("lib{}.rmeta", libname)));
107107

108108
check_file_is_writeable(&out_filename, sess);
109109

src/librustc_driver/driver.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,7 @@ where
882882
)
883883
});
884884

885-
let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
885+
let mut registry = registry.unwrap_or_else(|| Registry::new(sess, krate.span));
886886

887887
time(sess, "plugin registration", || {
888888
if sess.features_untracked().rustc_diagnostic_macros {

src/librustc_errors/diagnostic_builder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ impl<'a> DiagnosticBuilder<'a> {
128128
message: &str,
129129
span: Option<S>,
130130
) -> &mut Self {
131-
let span = span.map(|s| s.into()).unwrap_or(MultiSpan::new());
131+
let span = span.map(|s| s.into()).unwrap_or_else(|| MultiSpan::new());
132132
self.diagnostic.sub(level, message, span, None);
133133
self
134134
}

src/librustc_metadata/locator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ impl<'a> Context<'a> {
678678
if let Some((ref prev, _)) = ret {
679679
let sysroot = self.sess.sysroot();
680680
let sysroot = sysroot.canonicalize()
681-
.unwrap_or(sysroot.to_path_buf());
681+
.unwrap_or_else(|_| sysroot.to_path_buf());
682682
if prev.starts_with(&sysroot) {
683683
continue
684684
}

src/librustc_mir/borrow_check/error_reporting.rs

+10-9
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
9696
span,
9797
desired_action.as_noun(),
9898
&self.describe_place_with_options(moved_place, IncludingDowncast(true))
99-
.unwrap_or("_".to_owned()),
99+
.unwrap_or_else(|| "_".to_owned()),
100100
Origin::Mir,
101101
);
102102
err.span_label(span, format!("use of possibly uninitialized {}", item_msg));
@@ -260,7 +260,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
260260

261261
let mut err = tcx.cannot_move_when_borrowed(
262262
span,
263-
&self.describe_place(place).unwrap_or("_".to_owned()),
263+
&self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
264264
Origin::Mir,
265265
);
266266
err.span_label(borrow_span, format!("borrow of {} occurs here", borrow_msg));
@@ -299,16 +299,16 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
299299

300300
let mut err = tcx.cannot_use_when_mutably_borrowed(
301301
span,
302-
&self.describe_place(place).unwrap_or("_".to_owned()),
302+
&self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
303303
borrow_span,
304304
&self.describe_place(&borrow.borrowed_place)
305-
.unwrap_or("_".to_owned()),
305+
.unwrap_or_else(|| "_".to_owned()),
306306
Origin::Mir,
307307
);
308308

309309
borrow_spans.var_span_label(&mut err, {
310310
let place = &borrow.borrowed_place;
311-
let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
311+
let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
312312

313313
format!("borrow occurs due to use of `{}`{}", desc_place, borrow_spans.describe())
314314
});
@@ -337,7 +337,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
337337
"closure"
338338
};
339339

340-
let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
340+
let desc_place = self.describe_place(place).unwrap_or_else(|| "_".to_owned());
341341
let tcx = self.infcx.tcx;
342342

343343
let first_borrow_desc;
@@ -490,7 +490,8 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
490490
);
491491
} else {
492492
let borrow_place = &issued_borrow.borrowed_place;
493-
let borrow_place_desc = self.describe_place(borrow_place).unwrap_or("_".to_owned());
493+
let borrow_place_desc = self.describe_place(borrow_place)
494+
.unwrap_or_else(|| "_".to_owned());
494495
issued_spans.var_span_label(
495496
&mut err,
496497
format!(
@@ -943,15 +944,15 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
943944
tcx.cannot_mutate_in_match_guard(
944945
span,
945946
loan_span,
946-
&self.describe_place(place).unwrap_or("_".to_owned()),
947+
&self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
947948
"assign",
948949
Origin::Mir,
949950
)
950951
} else {
951952
tcx.cannot_assign_to_borrowed(
952953
span,
953954
loan_span,
954-
&self.describe_place(place).unwrap_or("_".to_owned()),
955+
&self.describe_place(place).unwrap_or_else(|| "_".to_owned()),
955956
Origin::Mir,
956957
)
957958
};

src/librustc_mir/borrow_check/mutability_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
208208
format!(
209209
"mutable borrow occurs due to use of `{}` in closure",
210210
// always Some() if the message is printed.
211-
self.describe_place(access_place).unwrap_or(String::new()),
211+
self.describe_place(access_place).unwrap_or_default(),
212212
)
213213
);
214214
borrow_span

src/librustc_mir/borrow_check/nll/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
184184

185185
if infcx.tcx.sess.opts.debugging_opts.polonius {
186186
let algorithm = env::var("POLONIUS_ALGORITHM")
187-
.unwrap_or(String::from("DatafrogOpt"));
187+
.unwrap_or_else(|_| String::from("DatafrogOpt"));
188188
let algorithm = Algorithm::from_str(&algorithm).unwrap();
189189
debug!("compute_regions: using polonius algorithm {:?}", algorithm);
190190
Some(Rc::new(Output::compute(

src/librustc_mir/interpret/cast.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M>
245245
match dest_ty.sty {
246246
// float -> uint
247247
Uint(t) => {
248-
let width = t.bit_width().unwrap_or(self.pointer_size().bits() as usize);
248+
let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
249249
let v = match fty {
250250
FloatTy::F32 => Single::from_bits(bits).to_u128(width).value,
251251
FloatTy::F64 => Double::from_bits(bits).to_u128(width).value,
@@ -255,7 +255,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M>
255255
},
256256
// float -> int
257257
Int(t) => {
258-
let width = t.bit_width().unwrap_or(self.pointer_size().bits() as usize);
258+
let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
259259
let v = match fty {
260260
FloatTy::F32 => Single::from_bits(bits).to_i128(width).value,
261261
FloatTy::F64 => Double::from_bits(bits).to_i128(width).value,

src/librustc_mir/transform/elaborate_drops.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
482482
source_info: terminator.source_info
483483
};
484484

485-
let unwind = unwind.unwrap_or(self.patch.resume_block());
485+
let unwind = unwind.unwrap_or_else(|| self.patch.resume_block());
486486
let unwind = self.patch.new_block(BasicBlockData {
487487
statements: vec![assign.clone()],
488488
terminator: Some(Terminator {

src/librustc_mir/util/borrowck_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ pub trait BorrowckErrors<'cx>: Sized + Copy {
476476
) -> DiagnosticBuilder<'cx> {
477477
let moved_path = moved_path
478478
.map(|mp| format!(": `{}`", mp))
479-
.unwrap_or(String::new());
479+
.unwrap_or_default();
480480

481481
let err = struct_span_err!(
482482
self,

src/librustc_resolve/resolve_imports.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
847847
fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
848848
debug!("(resolving import for module) resolving import `{}::...` in `{}`",
849849
names_to_string(&directive.module_path[..]),
850-
module_to_string(self.current_module).unwrap_or("???".to_string()));
850+
module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
851851

852852
self.current_module = directive.parent;
853853

src/librustc_save_analysis/dump_visitor.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
163163
.to_fingerprint()
164164
.as_value(),
165165
},
166-
crate_root: crate_root.unwrap_or("<no source>".to_owned()),
166+
crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
167167
external_crates: self.save_ctxt.get_external_crates(),
168168
span: self.span_from_span(krate.span),
169169
};
@@ -650,7 +650,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
650650
.iter()
651651
.enumerate()
652652
.map(|(i, f)| {
653-
f.ident.map(|i| i.to_string()).unwrap_or(i.to_string())
653+
f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
654654
})
655655
.collect::<Vec<_>>()
656656
.join(", ");
@@ -1030,7 +1030,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
10301030
.tables
10311031
.node_id_to_type_opt(hir_id)
10321032
.map(|t| t.to_string())
1033-
.unwrap_or(String::new());
1033+
.unwrap_or_default();
10341034
value.push_str(": ");
10351035
value.push_str(&typ);
10361036

@@ -1737,7 +1737,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc
17371737
let value = l.init
17381738
.as_ref()
17391739
.map(|i| self.span.snippet(i.span))
1740-
.unwrap_or(String::new());
1740+
.unwrap_or_default();
17411741
self.process_var_decl(&l.pat, value);
17421742

17431743
// Just walk the initialiser and type (don't want to walk the pattern again).

src/librustc_save_analysis/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
367367
.as_ref()
368368
.and_then(|t| self.lookup_ref_id(t.ref_id))
369369
.map(id_from_def_id)
370-
.unwrap_or(null_id()),
370+
.unwrap_or_else(|| null_id()),
371371
},
372372
Impl {
373373
id: impl_id,
@@ -632,7 +632,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
632632
ref_id: def_id
633633
.or(decl_id)
634634
.map(|id| id_from_def_id(id))
635-
.unwrap_or(null_id()),
635+
.unwrap_or_else(|| null_id()),
636636
}))
637637
}
638638
ast::ExprKind::Path(_, ref path) => {

src/librustc_typeck/check/method/suggest.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
174174
.map(|arg| print::to_string(print::NO_ANN,
175175
|s| s.print_expr(arg)))
176176
.collect::<Vec<_>>()
177-
.join(", ")).unwrap_or("...".to_owned())));
177+
.join(", ")).unwrap_or_else(|| "...".to_owned())));
178178
}
179179
}
180180
}
@@ -249,7 +249,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
249249
match expr.node {
250250
hir::ExprKind::Lit(ref lit) => { // numeric literal
251251
let snippet = tcx.sess.source_map().span_to_snippet(lit.span)
252-
.unwrap_or("<numeric literal>".to_owned());
252+
.unwrap_or_else(|_| "<numeric literal>".to_owned());
253253

254254
err.span_suggestion_with_applicability(
255255
lit.span,

0 commit comments

Comments
 (0)