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()) self.meta_item().and_then(|meta_item| meta_item.ident())
} }
pub fn name_or_empty(&self) -> Symbol { 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 /// 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 { 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> { 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 } if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
} }
pub fn name_or_empty(&self) -> Symbol { pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(Ident::invalid()).name self.ident().unwrap_or_else(Ident::invalid).name
} }
// Example: // Example:

View File

@ -282,7 +282,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
let mut test_runner = cx let mut test_runner = cx
.test_runner .test_runner
.clone() .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; 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.cg.panic = Some(PanicStrategy::Abort);
config.opts.debugging_opts.panic_abort_tests = true; config.opts.debugging_opts.panic_abort_tests = true;
config.opts.maybe_sysroot = Some( config.opts.maybe_sysroot = Some(
config.opts.maybe_sysroot.clone().unwrap_or( config.opts.maybe_sysroot.clone().unwrap_or_else(
std::env::current_exe() || std::env::current_exe()
.unwrap() .unwrap()
.parent() .parent()
.unwrap() .unwrap()

View File

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

View File

@ -409,7 +409,7 @@ impl Definitions {
} }
pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId { 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 { pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {

View File

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

View File

@ -1305,7 +1305,7 @@ pub fn build_session(
early_error(sopts.error_format, &format!("Error loading host specification: {}", e)) 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(|| { let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
if target_cfg.is_like_msvc { if target_cfg.is_like_msvc {
SourceFileHashAlgorithm::Sha1 SourceFileHashAlgorithm::Sha1

View File

@ -279,7 +279,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
/// tracking is not enabled, just returns an empty vector. /// tracking is not enabled, just returns an empty vector.
pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> { pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
assert!(self.intercrate); 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> { pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {

View File

@ -118,7 +118,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
closure_def_id: DefId, closure_def_id: DefId,
) -> Vec<DeferredCallResolution<'tcx>> { ) -> Vec<DeferredCallResolution<'tcx>> {
let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); 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 { pub fn tag(&self) -> String {

View File

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

View File

@ -322,7 +322,7 @@ impl Instant {
/// ``` /// ```
#[stable(feature = "checked_duration_since", since = "1.39.0")] #[stable(feature = "checked_duration_since", since = "1.39.0")]
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { 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. /// 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() .iter()
.enumerate() .enumerate()
.map(|(i, ty)| { .map(|(i, ty)| {
let mut name = let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default();
self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
if name.is_empty() { if name.is_empty() {
name = "_".to_string(); name = "_".to_string();
} }

View File

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