Skip to content

Commit

Permalink
Rollup merge of #111912 - WaffleLapkin:is_some_and_in_the_compiler, r…
Browse files Browse the repository at this point in the history
…=petrochenkov

Use `Option::is_some_and` and `Result::is_ok_and` in the compiler

`.is_some_and(..)`/`.is_ok_and(..)` replace `.map_or(false, ..)` and `.map(..).unwrap_or(false)`, making the code more readable.

This PR is a sibling of #111873 (comment)
  • Loading branch information
Manishearth authored May 24, 2023
2 parents 33ded73 + 307799a commit d0b3ebe
Show file tree
Hide file tree
Showing 97 changed files with 201 additions and 246 deletions.
4 changes: 2 additions & 2 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2391,10 +2391,10 @@ pub struct FnDecl {

impl FnDecl {
pub fn has_self(&self) -> bool {
self.inputs.get(0).map_or(false, Param::is_self)
self.inputs.get(0).is_some_and(Param::is_self)
}
pub fn c_variadic(&self) -> bool {
self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
self.inputs.last().is_some_and(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
}
}

Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl Attribute {
}

pub fn may_have_doc_links(&self) -> bool {
self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
self.doc_str().is_some_and(|s| comments::may_have_doc_links(s.as_str()))
}

pub fn is_proc_macro_attr(&self) -> bool {
Expand Down Expand Up @@ -441,12 +441,12 @@ impl NestedMetaItem {

/// Returns `true` if this list item is a MetaItem with a name of `name`.
pub fn has_name(&self, name: Symbol) -> bool {
self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
self.meta_item().is_some_and(|meta_item| meta_item.has_name(name))
}

/// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
pub fn is_word(&self) -> bool {
self.meta_item().map_or(false, |meta_item| meta_item.is_word())
self.meta_item().is_some_and(|meta_item| meta_item.is_word())
}

/// Gets a list of inner meta items from a list `MetaItem` type.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_ast/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ impl Token {
/// Returns `true` if the token is an identifier whose name is the given
/// string slice.
pub fn is_ident_named(&self, name: Symbol) -> bool {
self.ident().map_or(false, |(ident, _)| ident.name == name)
self.ident().is_some_and(|(ident, _)| ident.name == name)
}

/// Returns `true` if the token is an interpolated path.
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_ast/src/util/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,8 +392,7 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitErr
// Small bases are lexed as if they were base 10, e.g, the string
// might be `0b10201`. This will cause the conversion above to fail,
// but these kinds of errors are already reported by the lexer.
let from_lexer =
base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
let from_lexer = base < 10 && s.chars().any(|c| c.to_digit(10).is_some_and(|d| d >= base));
if from_lexer { LitError::LexerError } else { LitError::IntTooLarge(base) }
})
}
2 changes: 1 addition & 1 deletion compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ impl<'a> AstValidator<'a> {
let source_map = self.session.source_map();
let end = source_map.end_point(sp);

if source_map.span_to_snippet(end).map(|s| s == ";").unwrap_or(false) {
if source_map.span_to_snippet(end).is_ok_and(|s| s == ";") {
end
} else {
sp.shrink_to_hi()
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_ast_passes/src/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
match i.kind {
ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
let links_to_llvm =
link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
let links_to_llvm = link_name.is_some_and(|val| val.as_str().starts_with("llvm."));
if links_to_llvm {
gate_feature_post!(
&self,
Expand Down
11 changes: 4 additions & 7 deletions compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
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_or(false, |sp| sp.overlaps(var_or_use_span)) {
if !borrow_span.is_some_and(|sp| sp.overlaps(var_or_use_span)) {
let path_label = "used here by closure";
let capture_kind_label = message;
err.span_label(
Expand Down Expand Up @@ -224,12 +224,9 @@ impl<'tcx> BorrowExplanation<'tcx> {
if info.tail_result_is_ignored {
// #85581: If the first mutable borrow's scope contains
// the second borrow, this suggestion isn't helpful.
if !multiple_borrow_span
.map(|(old, new)| {
old.to(info.span.shrink_to_hi()).contains(new)
})
.unwrap_or(false)
{
if !multiple_borrow_span.is_some_and(|(old, new)| {
old.to(info.span.shrink_to_hi()).contains(new)
}) {
err.span_suggestion_verbose(
info.span.shrink_to_hi(),
"consider adding semicolon after the expression so its \
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/diagnostics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,7 +1156,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
ty::Adt(def, ..) => Some(def.did()),
_ => None,
});
let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
});
if is_option_or_result && maybe_reinitialized_locations_is_empty {
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
.body
.local_decls
.get(local)
.map(|l| mut_borrow_of_mutable_ref(l, self.local_names[local]))
.unwrap_or(false) =>
.is_some_and(|l| mut_borrow_of_mutable_ref(l, self.local_names[local])) =>
{
let decl = &self.body.local_decls[local];
err.span_label(span, format!("cannot {act}"));
Expand Down Expand Up @@ -443,7 +442,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
.sess
.source_map()
.span_to_snippet(span)
.map_or(false, |snippet| snippet.starts_with("&mut ")) =>
.is_ok_and(|snippet| snippet.starts_with("&mut ")) =>
{
err.span_label(span, format!("cannot {act}"));
err.span_suggestion(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ impl OutlivesSuggestionBuilder {
|(r, _)| {
self.constraints_to_add
.get(r)
.map(|r_outlived| r_outlived.as_slice().contains(fr))
.unwrap_or(false)
.is_some_and(|r_outlived| r_outlived.as_slice().contains(fr))
},
);

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/region_infer/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl<N: Idx> LivenessValues<N> {
/// Returns `true` if the region `r` contains the given element.
pub(crate) fn contains(&self, row: N, location: Location) -> bool {
let index = self.elements.point_from_location(location);
self.points.row(row).map_or(false, |r| r.contains(index))
self.points.row(row).is_some_and(|r| r.contains(index))
}

/// Returns an iterator of all the elements contained by the region `r`
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/cfg_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl<'ast> visit::Visitor<'ast> for CfgFinder {
self.has_cfg_or_cfg_attr = self.has_cfg_or_cfg_attr
|| attr
.ident()
.map_or(false, |ident| ident.name == sym::cfg || ident.name == sym::cfg_attr);
.is_some_and(|ident| ident.name == sym::cfg || ident.name == sym::cfg_attr);
}
}

Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_codegen_cranelift/src/abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,11 +432,9 @@ pub(crate) fn codegen_terminator_call<'tcx>(
let is_cold = if fn_sig.abi() == Abi::RustCold {
true
} else {
instance
.map(|inst| {
fx.tcx.codegen_fn_attrs(inst.def_id()).flags.contains(CodegenFnAttrFlags::COLD)
})
.unwrap_or(false)
instance.is_some_and(|inst| {
fx.tcx.codegen_fn_attrs(inst.def_id()).flags.contains(CodegenFnAttrFlags::COLD)
})
};
if is_cold {
fx.bcx.set_cold_block(fx.bcx.current_block().unwrap());
Expand Down Expand Up @@ -470,7 +468,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
};

// Pass the caller location for `#[track_caller]`.
if instance.map(|inst| inst.def.requires_caller_location(fx.tcx)).unwrap_or(false) {
if instance.is_some_and(|inst| inst.def.requires_caller_location(fx.tcx)) {
let caller_location = fx.get_caller_location(source_info);
args.push(CallArgument { value: caller_location, is_owned: false });
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_codegen_cranelift/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,11 +630,11 @@ fn codegen_stmt<'tcx>(
let to_ty = fx.monomorphize(to_ty);

fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
ty.builtin_deref(true)
.map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
ty.builtin_deref(true).is_some_and(
|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
has_ptr_meta(fx.tcx, pointee_ty)
})
.unwrap_or(false)
},
)
}

if is_fat_ptr(fx, from_ty) {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl CoverageMapGenerator {
counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
for (counter, region) in counter_regions {
let CodeRegion { file_name, start_line, start_col, end_line, end_col } = *region;
let same_file = current_file_name.map_or(false, |p| p == file_name);
let same_file = current_file_name.is_some_and(|p| p == file_name);
if !same_file {
if current_file_name.is_some() {
current_file_id += 1;
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_llvm/src/mono_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ impl CodegenCx<'_, '_> {

// Thread-local variables generally don't support copy relocations.
let is_thread_local_var = llvm::LLVMIsAGlobalVariable(llval)
.map(|v| llvm::LLVMIsThreadLocal(v) == llvm::True)
.unwrap_or(false);
.is_some_and(|v| llvm::LLVMIsThreadLocal(v) == llvm::True);
if is_thread_local_var {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/mir/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
});

let needs_location =
instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
if needs_location {
let mir_args = if let Some(num_untupled) = num_untupled {
first_args.len() + num_untupled
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_const_eval/src/transform/check_consts/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,7 +944,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == gate)
};
let feature_gate_declared = gate_declared(gate);
let implied_gate_declared = implied_by.map(gate_declared).unwrap_or(false);
let implied_gate_declared = implied_by.is_some_and(gate_declared);
if !feature_gate_declared && !implied_gate_declared {
self.check_op(ops::FnCallUnstable(callee, Some(gate)));
return;
Expand All @@ -971,7 +971,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
// have no `rustc_const_stable` attributes to be const-unstable as well. This
// should be fixed later.
let callee_is_unstable_unmarked = tcx.lookup_const_stability(callee).is_none()
&& tcx.lookup_stability(callee).map_or(false, |s| s.is_unstable());
&& tcx.lookup_stability(callee).is_some_and(|s| s.is_unstable());
if callee_is_unstable_unmarked {
trace!("callee_is_unstable_unmarked");
// We do not use `const` modifiers for intrinsic "functions", as intrinsics are
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,5 @@ fn is_parent_const_stable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
return false;
}

tcx.lookup_const_stability(parent.owner).map_or(false, |stab| stab.is_const_stable())
tcx.lookup_const_stability(parent.owner).is_some_and(|stab| stab.is_const_stable())
}
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ impl<O: ForestObligation> ObligationForest<O> {
&& self
.error_cache
.get(&obligation_tree_id)
.map_or(false, |errors| errors.contains(v.key()));
.is_some_and(|errors| errors.contains(v.key()));

if already_failed {
Err(())
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1315,7 +1315,7 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str, extra_info:
}

// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");

let num_frames = if backtrace { None } else { Some(2) };

Expand Down
14 changes: 5 additions & 9 deletions compiler/rustc_errors/src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,15 +285,11 @@ pub trait Emitter: Translate {
format!(
"help: {}{}: `{}`",
&msg,
if self
.source_map()
.map(|sm| is_case_difference(
sm,
substitution,
sugg.substitutions[0].parts[0].span,
))
.unwrap_or(false)
{
if self.source_map().is_some_and(|sm| is_case_difference(
sm,
substitution,
sugg.substitutions[0].parts[0].span,
)) {
" (notice the capitalization)"
} else {
""
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1437,7 +1437,7 @@ impl HandlerInner {
}

fn treat_err_as_bug(&self) -> bool {
self.flags.treat_err_as_bug.map_or(false, |c| {
self.flags.treat_err_as_bug.is_some_and(|c| {
self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
})
}
Expand Down Expand Up @@ -1603,7 +1603,7 @@ impl HandlerInner {
// This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
// incrementing `err_count` by one, so we need to +1 the comparing.
// FIXME: Would be nice to increment err_count in a more coherent way.
if self.flags.treat_err_as_bug.map_or(false, |c| {
if self.flags.treat_err_as_bug.is_some_and(|c| {
self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
}) {
// FIXME: don't abort here if report_delayed_bugs is off
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_expand/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,7 @@ impl SyntaxExtension {
let allow_internal_unsafe = attr::contains_name(attrs, sym::allow_internal_unsafe);
let local_inner_macros = attr::find_by_name(attrs, sym::macro_export)
.and_then(|macro_export| macro_export.meta_item_list())
.map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
.is_some_and(|l| attr::list_contains_name(&l, sym::local_inner_macros));
let collapse_debuginfo = attr::contains_name(attrs, sym::collapse_debuginfo);
tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);

Expand Down Expand Up @@ -1449,7 +1449,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
&& version
.next()
.and_then(|c| c.parse::<u32>().ok())
.map_or(false, |v| v < 6)
.is_some_and(|v| v < 6)
};

if crate_matches {
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
cfg_pos = Some(pos); // a cfg attr found, no need to search anymore
break;
} else if attr_pos.is_none()
&& !name.map_or(false, rustc_feature::is_builtin_attr_name)
&& !name.is_some_and(rustc_feature::is_builtin_attr_name)
{
attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr
}
Expand Down Expand Up @@ -1647,7 +1647,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
span = Some(current_span);

if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
if attrs.peek().is_some_and(|next_attr| next_attr.doc_str().is_some()) {
continue;
}

Expand Down Expand Up @@ -1950,6 +1950,6 @@ impl<'feat> ExpansionConfig<'feat> {
}

fn proc_macro_hygiene(&self) -> bool {
self.features.map_or(false, |features| features.proc_macro_hygiene)
self.features.is_some_and(|features| features.proc_macro_hygiene)
}
}
4 changes: 2 additions & 2 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,11 +861,11 @@ pub fn is_builtin_attr_name(name: Symbol) -> bool {
/// Whether this builtin attribute is only used in the local crate.
/// If so, it is not encoded in the crate metadata.
pub fn is_builtin_only_local(name: Symbol) -> bool {
BUILTIN_ATTRIBUTE_MAP.get(&name).map_or(false, |attr| attr.only_local)
BUILTIN_ATTRIBUTE_MAP.get(&name).is_some_and(|attr| attr.only_local)
}

pub fn is_valid_for_get_attr(name: Symbol) -> bool {
BUILTIN_ATTRIBUTE_MAP.get(&name).map_or(false, |attr| match attr.duplicates {
BUILTIN_ATTRIBUTE_MAP.get(&name).is_some_and(|attr| match attr.duplicates {
WarnFollowing | ErrorFollowing | ErrorPreceding | FutureWarnFollowing
| FutureWarnPreceding => true,
DuplicatesOk | WarnFollowingWordOnly => false,
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_feature/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,13 @@ impl UnstableFeatures {
pub fn from_environment(krate: Option<&str>) -> Self {
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features =
option_env!("CFG_DISABLE_UNSTABLE_FEATURES").map(|s| s != "0").unwrap_or(false);
option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some_and(|s| s != "0");
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map_or(false, |name| var.split(',').any(|new_krate| new_krate == name))
};
let is_unstable_crate =
|var: &str| krate.is_some_and(|name| var.split(',').any(|new_krate| new_krate == name));
// `true` if we should enable unstable features for bootstrapping.
let bootstrap = std::env::var("RUSTC_BOOTSTRAP")
.map_or(false, |var| var == "1" || is_unstable_crate(&var));
let bootstrap =
std::env::var("RUSTC_BOOTSTRAP").is_ok_and(|var| var == "1" || is_unstable_crate(&var));
match (disable_unstable_features, bootstrap) {
(_, true) => UnstableFeatures::Cheat,
(true, _) => UnstableFeatures::Disallow,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -787,7 +787,7 @@ pub struct WhereBoundPredicate<'hir> {
impl<'hir> WhereBoundPredicate<'hir> {
/// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
self.bounded_ty.as_generic_param().is_some_and(|(def_id, _)| def_id == param_def_id)
}
}

Expand Down
Loading

0 comments on commit d0b3ebe

Please sign in to comment.