Changed unwrap_or to unwrap_or_else in some places.

The discussion seems to have resolved that this lint is a bit "noisy" in
that applying it in all places would result in a reduction in
readability.

A few of the trivial functions (like `Path::new`) are fine to leave
outside of closures.

The general rule seems to be that anything that is obviously an
allocation (`Box`, `Vec`, `vec![]`) should be in a closure, even if it
is a 0-sized allocation.
This commit is contained in:
Nicholas-Baron 2020-11-06 13:24:55 -08:00
parent 38030ffb4e
commit 261ca04c92
14 changed files with 31 additions and 30 deletions

View File

@ -66,7 +66,7 @@ impl NestedMetaItem {
self.meta_item().and_then(|meta_item| meta_item.ident())
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(Ident::invalid()).name
self.ident().unwrap_or_else(Ident::invalid).name
}
/// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
@ -139,7 +139,7 @@ impl Attribute {
}
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(Ident::invalid()).name
self.ident().unwrap_or_else(Ident::invalid).name
}
pub fn value_str(&self) -> Option<Symbol> {
@ -183,7 +183,7 @@ impl MetaItem {
if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
}
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(Ident::invalid()).name
self.ident().unwrap_or_else(Ident::invalid).name
}
// Example:

View File

@ -282,7 +282,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
let mut test_runner = cx
.test_runner
.clone()
.unwrap_or(ecx.path(sp, vec![test_id, Ident::from_str_and_span(runner_name, sp)]));
.unwrap_or_else(|| ecx.path(sp, vec![test_id, Ident::from_str_and_span(runner_name, sp)]));
test_runner.span = sp;

View File

@ -27,8 +27,8 @@ impl rustc_driver::Callbacks for CraneliftPassesCallbacks {
config.opts.cg.panic = Some(PanicStrategy::Abort);
config.opts.debugging_opts.panic_abort_tests = true;
config.opts.maybe_sysroot = Some(
config.opts.maybe_sysroot.clone().unwrap_or(
std::env::current_exe()
config.opts.maybe_sysroot.clone().unwrap_or_else(
|| std::env::current_exe()
.unwrap()
.parent()
.unwrap()

View File

@ -979,12 +979,14 @@ fn generic_simd_intrinsic(
// Integer vector <i{in_bitwidth} x in_len>:
let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
ty::Int(i) => {
(args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
}
ty::Uint(i) => {
(args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
}
ty::Int(i) => (
args[0].immediate(),
i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
),
ty::Uint(i) => (
args[0].immediate(),
i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
),
_ => return_error!(
"vector argument `{}`'s element type `{}`, expected integer element type",
in_ty,

View File

@ -409,7 +409,7 @@ impl Definitions {
}
pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
self.expansions_that_defined.get(&id).copied().unwrap_or(ExpnId::root())
self.expansions_that_defined.get(&id).copied().unwrap_or_else(ExpnId::root)
}
pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {

View File

@ -856,7 +856,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.children
.get(self, index)
.unwrap_or(Lazy::empty())
.unwrap_or_else(Lazy::empty)
.decode(self)
.map(|index| ty::FieldDef {
did: self.local_def_id(index),
@ -888,7 +888,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.children
.get(self, item_id)
.unwrap_or(Lazy::empty())
.unwrap_or_else(Lazy::empty)
.decode(self)
.map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess))
.collect()
@ -1075,7 +1075,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
// Iterate over all children.
let macros_only = self.dep_kind.lock().macros_only();
let children = self.root.tables.children.get(self, id).unwrap_or(Lazy::empty());
let children = self.root.tables.children.get(self, id).unwrap_or_else(Lazy::empty);
for child_index in children.decode((self, sess)) {
if macros_only {
continue;
@ -1098,7 +1098,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.children
.get(self, child_index)
.unwrap_or(Lazy::empty());
.unwrap_or_else(Lazy::empty);
for child_index in child_children.decode((self, sess)) {
let kind = self.def_kind(child_index);
callback(Export {
@ -1284,7 +1284,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
}
fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
self.root.tables.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self).collect()
}
fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
@ -1323,7 +1323,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.attributes
.get(self, item_id)
.unwrap_or(Lazy::empty())
.unwrap_or_else(Lazy::empty)
.decode((self, sess))
.collect::<Vec<_>>()
}
@ -1333,7 +1333,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.children
.get(self, id)
.unwrap_or(Lazy::empty())
.unwrap_or_else(Lazy::empty)
.decode(self)
.map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
.collect()
@ -1349,7 +1349,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.inherent_impls
.get(self, id)
.unwrap_or(Lazy::empty())
.unwrap_or_else(Lazy::empty)
.decode(self)
.map(|index| self.local_def_id(index)),
)

View File

@ -582,7 +582,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
self.check_member_constraints(infcx, &mut errors_buffer);
}
let outlives_requirements = outlives_requirements.unwrap_or(vec![]);
let outlives_requirements = outlives_requirements.unwrap_or_default();
if outlives_requirements.is_empty() {
(None, errors_buffer)

View File

@ -1305,7 +1305,7 @@ pub fn build_session(
early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
});
let loader = file_loader.unwrap_or(Box::new(RealFileLoader));
let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
if target_cfg.is_like_msvc {
SourceFileHashAlgorithm::Sha1

View File

@ -279,7 +279,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
/// tracking is not enabled, just returns an empty vector.
pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
assert!(self.intercrate);
self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
self.intercrate_ambiguity_causes.take().unwrap_or_default()
}
pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {

View File

@ -118,7 +118,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
closure_def_id: DefId,
) -> Vec<DeferredCallResolution<'tcx>> {
let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![])
deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
}
pub fn tag(&self) -> String {

View File

@ -244,7 +244,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ProbeScope::AllTraits,
|probe_cx| Ok(probe_cx.candidate_method_names()),
)
.unwrap_or(vec![]);
.unwrap_or_default();
method_names
.iter()
.flat_map(|&method_name| {

View File

@ -322,7 +322,7 @@ impl Instant {
/// ```
#[stable(feature = "checked_duration_since", since = "1.39.0")]
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
self.checked_duration_since(earlier).unwrap_or_default()
}
/// Returns the amount of time elapsed since this instant was created.

View File

@ -935,8 +935,7 @@ impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
.iter()
.enumerate()
.map(|(i, ty)| {
let mut name =
self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default();
if name.is_empty() {
name = "_".to_string();
}

View File

@ -128,7 +128,7 @@ pub fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
.module
.as_ref()
.map(|module| shorten(plain_text_summary(module.doc_value())))
.unwrap_or(String::new());
.unwrap_or_default();
#[derive(Serialize)]
struct CrateData<'a> {