From 8eae198eb6e0e825d0b4f1bef24beae6ab504f5b Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 23 May 2023 13:32:38 +0000 Subject: [PATCH 1/5] Reorder stuff in `rustc_data_structures/lib.rs` --- compiler/rustc_data_structures/src/lib.rs | 57 ++++++++++++----------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 5b9b0e106d254..01db30ceb1167 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -46,61 +46,62 @@ extern crate cfg_if; #[macro_use] extern crate rustc_macros; +pub use ena::snapshot_vec; +pub use ena::undo_log; +pub use ena::unify; pub use rustc_index::static_assert_size; -#[inline(never)] -#[cold] -pub fn cold_path R, R>(f: F) -> R { - f() -} - +#[macro_use] +pub mod stable_hasher; +pub mod aligned; pub mod base_n; pub mod binary_search_util; pub mod captures; +pub mod fingerprint; pub mod flat_map_in_place; pub mod flock; +pub mod frozen; pub mod functor; pub mod fx; pub mod graph; pub mod intern; pub mod jobserver; pub mod macros; +pub mod marker; +pub mod memmap; pub mod obligation_forest; +pub mod owned_slice; +pub mod profiling; +pub mod sharded; pub mod sip128; pub mod small_c_str; pub mod small_str; pub mod snapshot_map; -pub mod svh; -pub use ena::snapshot_vec; -pub mod memmap; pub mod sorted_map; -#[macro_use] -pub mod stable_hasher; -mod atomic_ref; -pub mod fingerprint; -pub mod marker; -pub mod profiling; -pub mod sharded; +pub mod sso; pub mod stack; +pub mod steal; +pub mod svh; pub mod sync; +pub mod tagged_ptr; +pub mod temp_dir; pub mod tiny_list; pub mod transitive_relation; +pub mod unhash; +pub mod unord; pub mod vec_linked_list; pub mod work_queue; -pub use atomic_ref::AtomicRef; -pub mod aligned; -pub mod frozen; + +mod atomic_ref; mod hashes; -pub mod owned_slice; -pub mod sso; -pub mod steal; -pub mod tagged_ptr; -pub mod temp_dir; -pub mod unhash; -pub mod unord; -pub use ena::undo_log; -pub use ena::unify; +pub use atomic_ref::AtomicRef; + +#[inline(never)] +#[cold] +pub fn cold_path R, R>(f: F) -> R { + f() +} pub struct OnDrop(pub F); From 7592c134193b32dd239dd4e7aa0b3661e9df1f3f Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 23 May 2023 14:13:41 +0000 Subject: [PATCH 2/5] Simplify useless `map_or` --- .../src/coherence/inherent_impls_overlap.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index bd6252344b2c2..3bd2931265c73 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -140,7 +140,7 @@ impl<'tcx> InherentOverlapChecker<'tcx> { impl1_def_id: DefId, impl2_def_id: DefId, ) { - traits::overlapping_impls( + let maybe_overlap = traits::overlapping_impls( self.tcx, impl1_def_id, impl2_def_id, @@ -148,11 +148,11 @@ impl<'tcx> InherentOverlapChecker<'tcx> { // inherent impls without warning. SkipLeakCheck::Yes, overlap_mode, - ) - .map_or(true, |overlap| { + ); + + if let Some(overlap) = maybe_overlap { self.check_for_common_items_in_impls(impl1_def_id, impl2_def_id, overlap); - false - }); + } } fn check_item(&mut self, id: hir::ItemId) { From ddc72feaa561ac47a63397ee45daa14f284a7379 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 23 May 2023 14:26:34 +0000 Subject: [PATCH 3/5] Add `OptionExt` with `is_none_or` to `rustc_data_structures` --- compiler/rustc_data_structures/src/lib.rs | 2 ++ .../rustc_data_structures/src/option_ext.rs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 compiler/rustc_data_structures/src/option_ext.rs diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 01db30ceb1167..cffe804c6c92e 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -94,8 +94,10 @@ pub mod work_queue; mod atomic_ref; mod hashes; +mod option_ext; pub use atomic_ref::AtomicRef; +pub use option_ext::OptionExt; #[inline(never)] #[cold] diff --git a/compiler/rustc_data_structures/src/option_ext.rs b/compiler/rustc_data_structures/src/option_ext.rs new file mode 100644 index 0000000000000..52d05d75e3111 --- /dev/null +++ b/compiler/rustc_data_structures/src/option_ext.rs @@ -0,0 +1,18 @@ +/// Extension for [`Option`] that adds handy methods missing from it. +pub trait OptionExt { + type T; + + fn is_none_or(self, f: impl FnOnce(Self::T) -> bool) -> bool; +} + +impl OptionExt for Option { + type T = T; + + /// Returns `true` is `self` is `None` or the value inside matches a predicate `f`. + fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool { + match self { + None => true, + Some(x) => f(x), + } + } +} From 3bd865cf8d1c92cb7ae4f10a9f6cde79d8225dae Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 23 May 2023 14:27:18 +0000 Subject: [PATCH 4/5] Use `OptionExt::is_none_or` in the compiler --- compiler/rustc_ast_passes/src/feature_gate.rs | 3 ++- compiler/rustc_attr/src/builtin.rs | 3 ++- .../rustc_borrowck/src/diagnostics/conflict_errors.rs | 3 ++- compiler/rustc_borrowck/src/type_check/mod.rs | 3 ++- compiler/rustc_const_eval/src/interpret/intern.rs | 3 ++- compiler/rustc_const_eval/src/interpret/memory.rs | 3 ++- compiler/rustc_const_eval/src/interpret/projection.rs | 3 ++- compiler/rustc_data_structures/src/option_ext.rs | 2 +- compiler/rustc_expand/src/config.rs | 5 +++-- compiler/rustc_expand/src/mbe/diagnostics.rs | 3 ++- compiler/rustc_hir/src/def.rs | 3 ++- compiler/rustc_hir_analysis/src/collect/predicates_of.rs | 3 ++- compiler/rustc_hir_typeck/src/_match.rs | 3 ++- compiler/rustc_hir_typeck/src/coercion.rs | 3 ++- compiler/rustc_hir_typeck/src/expr.rs | 3 ++- compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs | 5 +++-- compiler/rustc_hir_typeck/src/generator_interior/mod.rs | 3 ++- compiler/rustc_lint/src/expect.rs | 3 ++- .../src/mir/interpret/allocation/provenance_map.rs | 5 +++-- compiler/rustc_middle/src/ty/instance.rs | 3 ++- compiler/rustc_middle/src/values.rs | 3 ++- compiler/rustc_mir_build/src/check_unsafety.rs | 3 ++- compiler/rustc_mir_dataflow/src/framework/graphviz.rs | 3 ++- compiler/rustc_mir_transform/src/coverage/graph.rs | 3 ++- compiler/rustc_mir_transform/src/coverage/spans.rs | 8 +++++--- compiler/rustc_parse/src/parser/attr.rs | 3 ++- compiler/rustc_parse/src/parser/expr.rs | 3 ++- compiler/rustc_resolve/src/check_unused.rs | 3 ++- compiler/rustc_resolve/src/diagnostics.rs | 5 +++-- compiler/rustc_resolve/src/imports.rs | 3 ++- compiler/rustc_resolve/src/late.rs | 3 ++- compiler/rustc_resolve/src/lib.rs | 3 ++- compiler/rustc_resolve/src/macros.rs | 3 ++- compiler/rustc_resolve/src/rustdoc.rs | 3 ++- compiler/rustc_session/src/parse.rs | 3 ++- compiler/rustc_trait_selection/src/solve/canonicalize.rs | 3 ++- 36 files changed, 78 insertions(+), 42 deletions(-) diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 3d5056d82c56c..b35c05ad835b4 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -2,6 +2,7 @@ use rustc_ast as ast; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; use rustc_ast::{attr, AssocConstraint, AssocConstraintKind, NodeId}; use rustc_ast::{PatKind, RangeEnd}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{Applicability, StashKey}; use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP}; use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; @@ -101,7 +102,7 @@ impl<'a> PostExpansionVisitor<'a> { .emit(); } Err(abi::AbiDisabled::Unrecognized) => { - if self.sess.opts.pretty.map_or(true, |ppm| ppm.needs_hir()) { + if self.sess.opts.pretty.is_none_or(|ppm| ppm.needs_hir()) { self.sess.parse_sess.span_diagnostic.delay_span_bug( span, format!( diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 372a58857f3d3..fefbf040ed9e2 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -3,6 +3,7 @@ use rustc_ast::{self as ast, attr}; use rustc_ast::{Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NodeId}; use rustc_ast_pretty::pprust; +use rustc_data_structures::OptionExt as _; use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg}; use rustc_macros::HashStable_Generic; use rustc_session::config::ExpectedValues; @@ -1096,7 +1097,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec { // the `check_mod_attrs` pass, but this pass doesn't always run // (e.g. if we only pretty-print the source), so we have to gate // the `delay_span_bug` call as follows: - if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) { + if sess.opts.pretty.is_none_or(|pp| pp.needs_analysis()) { diagnostic.delay_span_bug(item.span(), "unrecognized representation hint"); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 04b8174079acc..08c78adbbe809 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -3,6 +3,7 @@ use std::iter; use either::Either; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, }; @@ -1328,7 +1329,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && ex.span.contains(self.borrow_span) // To support cases like `|| { v.call(|this| v.get()) }` // FIXME: actually support such cases (need to figure out how to move from the capture place to original local) - && self.res.as_ref().map_or(true, |(prev_res, _)| prev_res.span.contains(ex.span)) + && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span)) { self.res = Some((ex, closure)); } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index fa4bc926f2739..eb932d7fe65a8 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -10,6 +10,7 @@ use either::Either; use hir::OpaqueTyOrigin; use rustc_data_structures::frozen::Frozen; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_data_structures::OptionExt as _; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -1812,7 +1813,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // than 1. // If the length is larger than 1, the repeat expression will need to copy the // element, so we require the `Copy` trait. - if len.try_eval_target_usize(tcx, self.param_env).map_or(true, |len| len > 1) { + if len.try_eval_target_usize(tcx, self.param_env).is_none_or(|len| len > 1) { match operand { Operand::Copy(..) | Operand::Constant(..) => { // These are always okay: direct use of a const, or a value that can evidently be copied. diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index c2b82ba9b0792..44e763d3e0b53 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -16,6 +16,7 @@ use super::validity::RefTracking; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_data_structures::OptionExt as _; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_middle::mir::interpret::InterpResult; @@ -114,7 +115,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx, const_eval: if let InternMode::Static(mutability) = mode { // For this, we need to take into account `UnsafeCell`. When `ty` is `None`, we assume // no interior mutability. - let frozen = ty.map_or(true, |ty| ty.is_freeze(*ecx.tcx, ecx.param_env)); + let frozen = ty.is_none_or(|ty| ty.is_freeze(*ecx.tcx, ecx.param_env)); // For statics, allocation mutability is the combination of place mutability and // type mutability. // The entire allocation needs to be mutable if it contains an `UnsafeCell` anywhere. diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index d5b6a581a79f6..4365e6c7294a1 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -14,6 +14,7 @@ use std::ptr; use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::OptionExt as _; use rustc_middle::mir::display_allocation; use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt}; use rustc_target::abi::{Align, HasDataLayout, Size}; @@ -422,7 +423,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let (alloc_size, alloc_align, ret_val) = alloc_size(alloc_id, offset, prov)?; // Test bounds. This also ensures non-null. // It is sufficient to check this for the end pointer. Also check for overflow! - if offset.checked_add(size, &self.tcx).map_or(true, |end| end > alloc_size) { + if offset.checked_add(size, &self.tcx).is_none_or(|end| end > alloc_size) { throw_ub!(PointerOutOfBounds { alloc_id, alloc_size, diff --git a/compiler/rustc_const_eval/src/interpret/projection.rs b/compiler/rustc_const_eval/src/interpret/projection.rs index 91da930db4fbf..d0c15a64bc844 100644 --- a/compiler/rustc_const_eval/src/interpret/projection.rs +++ b/compiler/rustc_const_eval/src/interpret/projection.rs @@ -9,6 +9,7 @@ use either::{Left, Right}; +use rustc_data_structures::OptionExt as _; use rustc_middle::mir; use rustc_middle::ty; use rustc_middle::ty::layout::LayoutOf; @@ -294,7 +295,7 @@ where ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { let len = base.len(self)?; // also asserts that we have a type where this makes sense let actual_to = if from_end { - if from.checked_add(to).map_or(true, |to| to > len) { + if from.checked_add(to).is_none_or(|to| to > len) { // This can only be reached in ConstProp and non-rustc-MIR. throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) }); } diff --git a/compiler/rustc_data_structures/src/option_ext.rs b/compiler/rustc_data_structures/src/option_ext.rs index 52d05d75e3111..90a00f870a307 100644 --- a/compiler/rustc_data_structures/src/option_ext.rs +++ b/compiler/rustc_data_structures/src/option_ext.rs @@ -2,13 +2,13 @@ pub trait OptionExt { type T; + /// Returns `true` if `self` is `None` or the value inside the `Some` matches a predicate `f`. fn is_none_or(self, f: impl FnOnce(Self::T) -> bool) -> bool; } impl OptionExt for Option { type T = T; - /// Returns `true` is `self` is `None` or the value inside matches a predicate `f`. fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool { match self { None => true, diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 4ff8e409d88e3..da55b5b17bce5 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -14,6 +14,7 @@ use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::OptionExt as _; use rustc_feature::{Feature, Features, State as FeatureState}; use rustc_feature::{ ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES, @@ -427,7 +428,7 @@ impl<'a> StripUnconfigured<'a> { return true; } }; - parse_cfg(&meta_item, &self.sess).map_or(true, |meta_item| { + parse_cfg(&meta_item, &self.sess).is_none_or(|meta_item| { attr::cfg_matches(&meta_item, &self.sess.parse_sess, self.lint_node_id, self.features) }) } @@ -435,7 +436,7 @@ impl<'a> StripUnconfigured<'a> { /// If attributes are not allowed on expressions, emit an error for `attr` #[instrument(level = "trace", skip(self))] pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) { - if !self.features.map_or(true, |features| features.stmt_expr_attributes) { + if !self.features.is_none_or(|features| features.stmt_expr_attributes) { let mut err = feature_err( &self.sess.parse_sess, sym::stmt_expr_attributes, diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index cb8b4899e485c..c3adc6174c736 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -7,6 +7,7 @@ use crate::mbe::{ use rustc_ast::token::{self, Token, TokenKind}; use rustc_ast::tokenstream::TokenStream; use rustc_ast_pretty::pprust; +use rustc_data_structures::OptionExt as _; use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, DiagnosticMessage}; use rustc_parse::parser::{Parser, Recovery}; use rustc_span::source_map::SourceMap; @@ -155,7 +156,7 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, if self .best_failure .as_ref() - .map_or(true, |failure| failure.is_better_position(*approx_position)) + .is_none_or(|failure| failure.is_better_position(*approx_position)) { self.best_failure = Some(BestFailure { token: token.clone(), diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 30bf8c2ad104b..4f004d2f98bff 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -4,6 +4,7 @@ use rustc_ast as ast; use rustc_ast::NodeId; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::ToStableHashKey; +use rustc_data_structures::OptionExt as _; use rustc_macros::HashStable_Generic; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::hygiene::MacroKind; @@ -731,7 +732,7 @@ impl Res { /// Always returns `true` if `self` is `Res::Err` pub fn matches_ns(&self, ns: Namespace) -> bool { - self.ns().map_or(true, |actual_ns| actual_ns == ns) + self.ns().is_none_or(|actual_ns| actual_ns == ns) } /// Returns whether such a resolved path can occur in a tuple struct/variant pattern diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index a33990813b820..ee5ef22c61899 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -4,6 +4,7 @@ use crate::collect::ItemCtxt; use crate::constrained_generic_params as cgp; use hir::{HirId, Node}; use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::OptionExt as _; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -803,7 +804,7 @@ impl<'tcx> ItemCtxt<'tcx> { bound_ty, predicate.bounds.iter().filter(|bound| { assoc_name - .map_or(true, |assoc_name| self.bound_defines_assoc_item(bound, assoc_name)) + .is_none_or(|assoc_name| self.bound_defines_assoc_item(bound, assoc_name)) }), &mut bounds, bound_vars, diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index 7d2f7e876083a..3bf3cb754d80d 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -1,5 +1,6 @@ use crate::coercion::{AsCoercionSite, CoerceMany}; use crate::{Diverges, Expectation, FnCtxt, Needs}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{Applicability, Diagnostic, MultiSpan}; use rustc_hir::{self as hir, ExprKind}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -211,7 +212,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ret_ty = ret_coercion.borrow().expected_ty(); let ret_ty = self.inh.infcx.shallow_resolve(ret_ty); self.can_coerce(arm_ty, ret_ty) - && prior_arm.map_or(true, |(_, ty, _)| self.can_coerce(ty, ret_ty)) + && prior_arm.is_none_or(|(_, ty, _)| self.can_coerce(ty, ret_ty)) // The match arms need to unify for the case of `impl Trait`. && !matches!(ret_ty.kind(), ty::Alias(ty::Opaque, ..)) } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index cfe8d59f737bd..036510ff69c4c 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -36,6 +36,7 @@ //! ``` use crate::FnCtxt; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, }; @@ -917,7 +918,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { if self .tcx .upvars_mentioned(closure_def_id_a.expect_local()) - .map_or(true, |u| u.is_empty()) => + .is_none_or(|u| u.is_empty()) => { // We coerce the closure, which has fn type // `extern "rust-call" fn((arg0,arg1,...)) -> _` diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index adc1b090af675..776fbce1208c2 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -22,6 +22,7 @@ use crate::{ use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stack::ensure_sufficient_stack; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ pluralize, struct_span_err, AddToDiagnostic, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, ErrorGuaranteed, StashKey, @@ -1467,7 +1468,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we // don't copy that one element, we move it. Only check for Copy if the length is larger. - if count.try_eval_target_usize(tcx, self.param_env).map_or(true, |len| len > 1) { + if count.try_eval_target_usize(tcx, self.param_env).is_none_or(|len| len > 1) { let lang_item = self.tcx.require_lang_item(LangItem::Copy, None); let code = traits::ObligationCauseCode::RepeatElementCopy { is_const_fn }; self.require_type_meets(element_ty, element.span, code, lang_item); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index c7011b23a7da7..3f3bff4f816f4 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -10,6 +10,7 @@ use crate::{ }; use rustc_ast as ast; use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ pluralize, Applicability, Diagnostic, DiagnosticId, ErrorGuaranteed, MultiSpan, }; @@ -940,7 +941,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if only_extras_so_far && errors .peek() - .map_or(true, |next_error| !matches!(next_error, Error::Extra(_))) + .is_none_or(|next_error| !matches!(next_error, Error::Extra(_))) { let next = provided_arg_tys .get(arg_idx + 1) @@ -1955,7 +1956,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for (_, param) in params .into_iter() .enumerate() - .filter(|(idx, _)| expected_idx.map_or(true, |expected_idx| expected_idx == *idx)) + .filter(|(idx, _)| expected_idx.is_none_or(|expected_idx| expected_idx == *idx)) { spans.push_span_label(param.span, ""); } diff --git a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs index 019fb86f55c4c..e8015afee4c3c 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs @@ -6,6 +6,7 @@ use self::drop_ranges::DropRanges; use super::FnCtxt; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{pluralize, DelayDm}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; @@ -456,7 +457,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { // doesn't match the behavior of MIR borrowck and causes ICEs. See the FIXME comment in // tests/ui/generator/drop-tracking-parent-expression.rs. let scope = if self.drop_ranges.is_borrowed_temporary(expr) - || ty.map_or(true, |ty| { + || ty.is_none_or(|ty| { // Avoid ICEs in needs_drop. let ty = self.fcx.resolve_vars_if_possible(ty); let ty = self.fcx.tcx.erase_regions(ty); diff --git a/compiler/rustc_lint/src/expect.rs b/compiler/rustc_lint/src/expect.rs index b1266b58a61e7..3d9466403202f 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -1,4 +1,5 @@ use crate::lints::{Expectation, ExpectationNote}; +use rustc_data_structures::OptionExt as _; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::lint::builtin::UNFULFILLED_LINT_EXPECTATIONS; @@ -25,7 +26,7 @@ fn check_expectations(tcx: TyCtxt<'_>, tool_filter: Option) { // holds stable ids if let LintExpectationId::Stable { hir_id, .. } = id { if !fulfilled_expectations.contains(&id) - && tool_filter.map_or(true, |filter| expectation.lint_tool == Some(filter)) + && tool_filter.is_none_or(|filter| expectation.lint_tool == Some(filter)) { let rationale = expectation.reason.map(|rationale| ExpectationNote { rationale }); let note = expectation.is_unfulfilled_lint_expectations.then_some(()); diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs index 318f93e12b582..de3b346cbb521 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs @@ -4,6 +4,7 @@ use std::cmp; use rustc_data_structures::sorted_map::SortedMap; +use rustc_data_structures::OptionExt as _; use rustc_target::abi::{HasDataLayout, Size}; use super::{alloc_range, AllocError, AllocId, AllocRange, AllocResult, Provenance}; @@ -90,7 +91,7 @@ impl ProvenanceMap { debug_assert!(prov.len() <= 1); if let Some(entry) = prov.first() { // If it overlaps with this byte, it is on this byte. - debug_assert!(self.bytes.as_ref().map_or(true, |b| b.get(&offset).is_none())); + debug_assert!(self.bytes.as_ref().is_none_or(|b| b.get(&offset).is_none())); Some(entry.1) } else { // Look up per-byte provenance. @@ -275,7 +276,7 @@ impl ProvenanceMap { // For really small copies, make sure we don't start before `src` does. let entry_start = cmp::max(entry.0, src.start); for offset in entry_start..src.end() { - if bytes.last().map_or(true, |bytes_entry| bytes_entry.0 < offset) { + if bytes.last().is_none_or(|bytes_entry| bytes_entry.0 < offset) { // The last entry, if it exists, has a lower offset than us. bytes.push((offset, entry.1)); } else { diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 8c69894f5ba7e..38173404789e7 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -2,6 +2,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable}; use crate::ty::{EarlyBinder, InternalSubsts, SubstsRef, TypeVisitableExt}; +use rustc_data_structures::OptionExt as _; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::Namespace; use rustc_hir::def_id::{CrateNum, DefId}; @@ -241,7 +242,7 @@ impl<'tcx> InstanceDef<'tcx> { // We include enums without destructors to allow, say, optimizing // drops of `Option::None` before LTO. We also respect the intent of // `#[inline]` on `Drop::drop` implementations. - return ty.ty_adt_def().map_or(true, |adt_def| { + return ty.ty_adt_def().is_none_or(|adt_def| { adt_def.destructor(tcx).map_or_else( || adt_def.is_enum(), |dtor| tcx.codegen_fn_attrs(dtor.did).requests_inline(), diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index c62c33d4dfc18..b68e0a15d44ec 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -1,5 +1,6 @@ use crate::dep_graph::DepKind; use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; @@ -207,7 +208,7 @@ fn find_item_ty_spans( hir::TyKind::Path(hir::QPath::Resolved(_, path)) => { if let Res::Def(kind, def_id) = path.res && kind != DefKind::TyAlias { - let check_params = def_id.as_local().map_or(true, |def_id| { + let check_params = def_id.as_local().is_none_or(|def_id| { if def_id == needle { spans.push(ty.span); } diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 0506f2bf2385c..eb76b098064e7 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -2,6 +2,7 @@ use crate::build::ExprCategory; use crate::errors::*; use rustc_middle::thir::visit::{self, Visitor}; +use rustc_data_structures::OptionExt as _; use rustc_hir as hir; use rustc_middle::mir::BorrowKind; use rustc_middle::thir::*; @@ -164,7 +165,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> { // place, i.e. the expression is a place expression and not a dereference // (since dereferencing something leads us to a different place). ExprKind::Deref { .. } => {} - ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => { + ref kind if ExprCategory::of(kind).is_none_or(|cat| cat == ExprCategory::Place) => { visit::walk_expr(self, expr); } diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index 707729f8f21b7..1c5761b2fcd09 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -5,6 +5,7 @@ use std::sync::OnceLock; use std::{io, ops, str}; use regex::Regex; +use rustc_data_structures::OptionExt as _; use rustc_graphviz as dot; use rustc_index::bit_set::BitSet; use rustc_middle::mir::graphviz_safe_def_name; @@ -421,7 +422,7 @@ where let before = diffs_before.as_mut().map(next_in_dataflow_order); assert!(diffs_after.is_empty()); - assert!(diffs_before.as_ref().map_or(true, ExactSizeIterator::is_empty)); + assert!(diffs_before.as_ref().is_none_or(ExactSizeIterator::is_empty)); let terminator = body[block].terminator(); let mut terminator_str = String::new(); diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 986d2fd190dd7..58bd457aa7e16 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -4,6 +4,7 @@ use itertools::Itertools; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::graph::dominators::{self, Dominators}; use rustc_data_structures::graph::{self, GraphSuccessors, WithNumNodes, WithStartNode}; +use rustc_data_structures::OptionExt as _; use rustc_index::bit_set::BitSet; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::coverage::*; @@ -382,7 +383,7 @@ impl BasicCoverageBlockData { // If the BCB has an edge counter (to be injected into a new `BasicBlock`), it can also // have an expression (to be injected into an existing `BasicBlock` represented by this // `BasicCoverageBlock`). - if !self.counter_kind.as_ref().map_or(true, |c| c.is_expression()) { + if !self.counter_kind.as_ref().is_none_or(|c| c.is_expression()) { return Error::from_string(format!( "attempt to add an incoming edge counter from {:?} when the target BCB already \ has a `Counter`", diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index 14937912cc599..51c52f034c5f2 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -2,6 +2,7 @@ use super::graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph, ST use itertools::Itertools; use rustc_data_structures::graph::WithNumNodes; +use rustc_data_structures::OptionExt as _; use rustc_middle::mir::spanview::source_range_no_file; use rustc_middle::mir::{ self, AggregateKind, BasicBlock, FakeReadCause, Rvalue, Statement, StatementKind, Terminator, @@ -480,9 +481,10 @@ impl<'a, 'tcx> CoverageSpans<'a, 'tcx> { fn check_invoked_macro_name_span(&mut self) { if let Some(visible_macro) = self.curr().visible_macro(self.body_span) { - if self.prev_expn_span.map_or(true, |prev_expn_span| { - self.curr().expn_span.ctxt() != prev_expn_span.ctxt() - }) { + if self + .prev_expn_span + .is_none_or(|prev_expn_span| self.curr().expn_span.ctxt() != prev_expn_span.ctxt()) + { let merged_prefix_len = self.curr_original_span.lo() - self.curr().span.lo(); let after_macro_bang = merged_prefix_len + BytePos(visible_macro.as_str().len() as u32 + 1); diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index e1db19557cfe2..d16b3da9d899f 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -5,6 +5,7 @@ use super::{AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, PathStyle use rustc_ast as ast; use rustc_ast::attr; use rustc_ast::token::{self, Delimiter, Nonterminal}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{error_code, Diagnostic, IntoDiagnostic, PResult}; use rustc_span::{sym, BytePos, Span}; use std::convert::TryInto; @@ -429,7 +430,7 @@ pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool { if attr.is_doc_comment() { return false; } - attr.ident().map_or(true, |ident| { + attr.ident().is_none_or(|ident| { ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name) }) }) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index ee712a8e1b5db..3037d2598dda1 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -22,6 +22,7 @@ use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}; use rustc_ast::{ClosureBinder, MetaItemLit, StmtKind}; use rustc_ast_pretty::pprust; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ AddToDiagnostic, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult, StashKey, @@ -1913,7 +1914,7 @@ impl<'a> Parser<'a> { // point literal here, since there's no use of the exponent // syntax that also constitutes a valid integer, so we need // not check for that. - if suffix.map_or(true, |s| s == sym::f32 || s == sym::f64) + if suffix.is_none_or(|s| s == sym::f32 || s == sym::f64) && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_') && self.token.span.hi() == next_token.span.lo() { diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index 17c4a6be049ed..df7d3d427287d 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -31,6 +31,7 @@ use rustc_ast as ast; use rustc_ast::visit::{self, Visitor}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_data_structures::unord::UnordSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{pluralize, MultiSpan}; use rustc_hir::def::{DefKind, Res}; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS}; @@ -313,7 +314,7 @@ impl Resolver<'_, '_> { } ImportKind::ExternCrate { id, .. } => { let def_id = self.local_def_id(id); - if self.extern_crate_map.get(&def_id).map_or(true, |&cnum| { + if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| { !tcx.is_compiler_builtins(cnum) && !tcx.is_panic_runtime(cnum) && !tcx.has_global_allocator(cnum) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index ed0a792d38763..2453ba930f9ae 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -5,6 +5,7 @@ use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID}; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ pluralize, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, }; @@ -289,7 +290,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id(); let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy(); let from_item = - self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item); + self.extern_prelude.get(&ident).is_none_or(|entry| entry.introduced_by_item); // Only suggest removing an import if both bindings are to the same def, if both spans // aren't dummy spans. Further, if both bindings are imports, then the ident must have // been introduced by an item. @@ -518,7 +519,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { for (key, resolution) in self.resolutions(module).borrow().iter() { if let Some(binding) = resolution.borrow().binding { let res = binding.res(); - if filter_fn(res) && ctxt.map_or(true, |ctxt| ctxt == key.ident.span.ctxt()) { + if filter_fn(res) && ctxt.is_none_or(|ctxt| ctxt == key.ident.span.ctxt()) { names.push(TypoSuggestion::typo_from_ident(key.ident, res)); } } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 7c4c05d4b9452..39762af57dd02 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -14,6 +14,7 @@ use crate::{NameBinding, NameBindingKind, PathResult}; use rustc_ast::NodeId; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; +use rustc_data_structures::OptionExt as _; use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan}; use rustc_hir::def::{self, DefKind, PartialRes}; use rustc_middle::metadata::ModChild; @@ -278,7 +279,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if let ImportKind::Glob { ref max_vis, .. } = import.kind { if vis == import_vis - || max_vis.get().map_or(true, |max_vis| vis.is_at_least(max_vis, self.tcx)) + || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)) { max_vis.set(Some(vis.expect_local())) } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index a1077615d9593..8de6ff4704f7c 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -15,6 +15,7 @@ use rustc_ast::ptr::P; use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; use rustc_ast::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{Applicability, DiagnosticArgValue, DiagnosticId, IntoDiagnosticArg}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS}; @@ -560,7 +561,7 @@ impl MaybeExported<'_> { MaybeExported::Impl(None) => return true, MaybeExported::ImplItem(Err(vis)) => return vis.kind.is_pub(), }; - def_id.map_or(true, |def_id| r.effective_visibilities.is_exported(def_id)) + def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id)) } } diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 3cdc3f0ecf892..223b95f31496f 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -32,6 +32,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::{Lrc, MappedReadGuard}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, SubdiagnosticMessage, }; @@ -1089,7 +1090,7 @@ impl<'a> ResolverArenas<'a> { let module = self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); let def_id = module.opt_def_id(); - if def_id.map_or(true, |def_id| def_id.is_local()) { + if def_id.is_none_or(|def_id| def_id.is_local()) { self.local_modules.borrow_mut().push(module); } if let Some(def_id) = def_id { diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 4da43c6a9a2db..ad2ad2fb46824 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -11,6 +11,7 @@ use rustc_ast_pretty::pprust; use rustc_attr::StabilityLevel; use rustc_data_structures::intern::Interned; use rustc_data_structures::sync::Lrc; +use rustc_data_structures::OptionExt as _; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand}; use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind}; @@ -863,7 +864,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { span: Span, ) { if let Some(Res::NonMacroAttr(kind)) = res { - if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) { + if kind != NonMacroAttrKind::Tool && binding.is_none_or(|b| b.is_import()) { let msg = format!("cannot use {} {} through an import", kind.article(), kind.descr()); let mut err = self.tcx.sess.struct_span_err(span, msg); diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index d433391f272e0..1ea104793e0b9 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -2,6 +2,7 @@ use pulldown_cmark::{BrokenLink, Event, LinkType, Options, Parser, Tag}; use rustc_ast as ast; use rustc_ast::util::comments::beautify_doc_string; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::OptionExt as _; use rustc_span::def_id::DefId; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; @@ -336,7 +337,7 @@ pub fn strip_generics_from_path(path_str: &str) -> Result, MalformedGen //// If there are no doc-comments, return true. /// FIXME(#78591): Support both inner and outer attributes on the same item. pub fn inner_docs(attrs: &[ast::Attribute]) -> bool { - attrs.iter().find(|a| a.doc_str().is_some()).map_or(true, |a| a.style == ast::AttrStyle::Inner) + attrs.iter().find(|a| a.doc_str().is_some()).is_none_or(|a| a.style == ast::AttrStyle::Inner) } /// Has `#[rustc_doc_primitive]` or `#[doc(keyword)]`. diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 7b396dde91ba1..11700bed51ee5 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -9,6 +9,7 @@ use crate::lint::{ use rustc_ast::node_id::NodeId; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::sync::{AppendOnlyVec, AtomicBool, Lock, Lrc}; +use rustc_data_structures::OptionExt as _; use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; use rustc_errors::{ fallback_fluent_bundle, Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, @@ -55,7 +56,7 @@ impl GatedSpans { /// /// Using this is discouraged unless you have a really good reason to. pub fn is_ungated(&self, feature: Symbol) -> bool { - self.spans.borrow().get(&feature).map_or(true, |spans| spans.is_empty()) + self.spans.borrow().get(&feature).is_none_or(|spans| spans.is_empty()) } /// Prepend the given set of `spans` onto the set in `self`. diff --git a/compiler/rustc_trait_selection/src/solve/canonicalize.rs b/compiler/rustc_trait_selection/src/solve/canonicalize.rs index ff4bff10cc8a3..97c25f4c757da 100644 --- a/compiler/rustc_trait_selection/src/solve/canonicalize.rs +++ b/compiler/rustc_trait_selection/src/solve/canonicalize.rs @@ -1,6 +1,7 @@ use std::cmp::Ordering; use crate::infer::InferCtxt; +use rustc_data_structures::OptionExt as _; use rustc_middle::infer::canonical::Canonical; use rustc_middle::infer::canonical::CanonicalTyVarKind; use rustc_middle::infer::canonical::CanonicalVarInfo; @@ -156,7 +157,7 @@ impl<'a, 'tcx> Canonicalizer<'a, 'tcx> { // // For this we set `next_orig_uv` to the next smallest, not yet compressed, // universe of the input. - if next_orig_uv.map_or(true, |curr_next_uv| uv.cannot_name(curr_next_uv)) { + if next_orig_uv.is_none_or(|curr_next_uv| uv.cannot_name(curr_next_uv)) { next_orig_uv = Some(uv); } } From 2fb4550f5e9278641998e8e640ee147d7ef20d95 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 24 May 2023 14:55:41 +0000 Subject: [PATCH 5/5] Use `is_none_or` in less obvious spots --- compiler/rustc_ast_passes/src/ast_validation.rs | 3 +-- .../rustc_borrowck/src/diagnostics/explain_borrow.rs | 9 +++++---- compiler/rustc_codegen_cranelift/src/num.rs | 4 ++-- compiler/rustc_middle/src/lint.rs | 3 ++- compiler/rustc_resolve/src/late/diagnostics.rs | 3 ++- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index bf43bbdbbeeba..796e0a7c36eb3 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -617,8 +617,7 @@ impl<'a> AstValidator<'a> { .session .source_map() .span_to_snippet(span) - .map(|snippet| snippet.starts_with("#[")) - .unwrap_or(true); + .map_or(true, |snippet| snippet.starts_with("#[")); if !is_macro_callsite { self.lint_buffer.buffer_lint_with_diagnostic( MISSING_ABI, diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index d0cb1126f38bb..2fe3bb2a00883 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -1,5 +1,6 @@ //! Print diagnostics to explain why values are borrowed. +use rustc_data_structures::OptionExt as _; use rustc_errors::{Applicability, Diagnostic}; use rustc_hir as hir; use rustc_hir::intravisit::Visitor; @@ -106,8 +107,8 @@ impl<'tcx> BorrowExplanation<'tcx> { LaterUseKind::Other => "used here", }; // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same - if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) { - if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) { + if path_span.is_none_or(|path_span| path_span == var_or_use_span) { + if borrow_span.is_none_or(|sp| !sp.overlaps(var_or_use_span)) { err.span_label( var_or_use_span, format!("{borrow_desc}borrow later {message}"), @@ -142,14 +143,14 @@ impl<'tcx> BorrowExplanation<'tcx> { LaterUseKind::Other => "borrow used here, in later iteration of loop", }; // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same - if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) { + if path_span.is_none_or(|path_span| path_span == var_or_use_span) { err.span_label(var_or_use_span, format!("{borrow_desc}{message}")); } else { // path_span must be `Some` as otherwise the if condition is true let path_span = path_span.unwrap(); // path_span is only present in the case of closure capture assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture)); - if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) { + if borrow_span.is_none_or(|sp| !sp.overlaps(var_or_use_span)) { let path_label = "used here by closure"; let capture_kind_label = message; err.span_label( diff --git a/compiler/rustc_codegen_cranelift/src/num.rs b/compiler/rustc_codegen_cranelift/src/num.rs index ba53e01c7a212..2e2242e82076b 100644 --- a/compiler/rustc_codegen_cranelift/src/num.rs +++ b/compiler/rustc_codegen_cranelift/src/num.rs @@ -1,6 +1,7 @@ //! Various operations on integer and floating-point numbers use crate::prelude::*; +use rustc_data_structures::OptionExt as _; pub(crate) fn bin_op_to_intcc(bin_op: BinOp, signed: bool) -> Option { use BinOp::*; @@ -368,8 +369,7 @@ pub(crate) fn codegen_ptr_binop<'tcx>( .layout() .ty .builtin_deref(true) - .map(|TypeAndMut { ty, mutbl: _ }| !has_ptr_meta(fx.tcx, ty)) - .unwrap_or(true); + .is_none_or(|TypeAndMut { ty, mutbl: _ }| !has_ptr_meta(fx.tcx, ty)); if is_thin_ptr { match bin_op { diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index c266584ac280f..980fb8d08845f 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -2,6 +2,7 @@ use std::cmp; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sorted_map::SortedMap; +use rustc_data_structures::OptionExt as _; use rustc_errors::{Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, MultiSpan}; use rustc_hir::{HirId, ItemLocalId}; use rustc_session::lint::{ @@ -389,7 +390,7 @@ pub fn struct_lint_level( // if this lint occurs in the expansion of a macro from an external crate, // allow individual lints to opt-out from being reported. let not_future_incompatible = - future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true); + future_incompatible.is_none_or(|f| f.reason.edition().is_some()); if not_future_incompatible && !lint.report_in_external_macro { err.cancel(); // Don't continue further, since we don't want to have diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index c9131d8c8a917..be50787681b1e 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -12,6 +12,7 @@ use rustc_ast::{ }; use rustc_ast_pretty::pprust::path_segment_to_string; use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::OptionExt as _; use rustc_errors::{ pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, @@ -2184,7 +2185,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { let deletion_span = deletion_span(); // the give lifetime originates from expanded code so we won't be able to remove it #104432 let lifetime_only_in_expanded_code = - deletion_span.map(|sp| sp.in_derive_expansion()).unwrap_or(true); + deletion_span.is_none_or(|sp| sp.in_derive_expansion()); if !lifetime_only_in_expanded_code { self.r.lint_buffer.buffer_lint_with_diagnostic( lint::builtin::UNUSED_LIFETIMES,