Merge pull request #18846 from Veykril/push-kmspklwynynu

minor: New clippy lints
This commit is contained in:
Lukas Wirth 2025-01-06 17:12:14 +00:00 committed by GitHub
commit 72b9427162
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
92 changed files with 180 additions and 201 deletions

View file

@ -205,6 +205,11 @@ useless_asref = "allow"
assigning_clones = "allow"
# Does not work with macros
vec_init_then_push = "allow"
# Our tests have a lot of these
literal_string_with_formatting_args = "allow"
# This lint has been empowered but now also triggers on cases where its invalid to do so
# due to it ignoring move analysis
unnecessary_map_or = "allow"
## Following lints should be tackled at some point
too_many_arguments = "allow"

View file

@ -571,7 +571,7 @@ impl<'attr> AttrQuery<'attr> {
pub fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
let key = self.key;
self.attrs.iter().filter(move |attr| attr.path.as_ident().map_or(false, |s| *s == *key))
self.attrs.iter().filter(move |attr| attr.path.as_ident().is_some_and(|s| *s == *key))
}
/// Find string value for a specific key inside token tree

View file

@ -2216,11 +2216,11 @@ impl ExprCollector<'_> {
};
// This needs to match `Flag` in library/core/src/fmt/rt.rs.
let flags: u32 = ((sign == Some(FormatSign::Plus)) as u32)
| ((sign == Some(FormatSign::Minus)) as u32) << 1
| (alternate as u32) << 2
| (zero_pad as u32) << 3
| ((debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4
| ((debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5;
| (((sign == Some(FormatSign::Minus)) as u32) << 1)
| ((alternate as u32) << 2)
| ((zero_pad as u32) << 3)
| (((debug_hex == Some(FormatDebugHex::Lower)) as u32) << 4)
| (((debug_hex == Some(FormatDebugHex::Upper)) as u32) << 5);
let flags = self.alloc_expr_desugared(Expr::Literal(Literal::Uint(
flags as u128,
Some(BuiltinUint::U32),
@ -2468,7 +2468,7 @@ impl ExprCollector<'_> {
fn comma_follows_token(t: Option<syntax::SyntaxToken>) -> bool {
(|| syntax::algo::skip_trivia_token(t?.next_token()?, syntax::Direction::Next))()
.map_or(false, |it| it.kind() == syntax::T![,])
.is_some_and(|it| it.kind() == syntax::T![,])
}
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]

View file

@ -90,7 +90,7 @@ pub mod keys {
map.map.get::<FxHashMap<AstPtr<AST>, ID>>()?.get(key)
}
fn is_empty(map: &DynMap) -> bool {
map.map.get::<FxHashMap<AstPtr<AST>, ID>>().map_or(true, |it| it.is_empty())
map.map.get::<FxHashMap<AstPtr<AST>, ID>>().is_none_or(|it| it.is_empty())
}
}
}
@ -141,7 +141,7 @@ impl<K: Hash + Eq + 'static, V: 'static> Policy for (K, V) {
map.map.get::<FxHashMap<K, V>>()?.get(key)
}
fn is_empty(map: &DynMap) -> bool {
map.map.get::<FxHashMap<K, V>>().map_or(true, |it| it.is_empty())
map.map.get::<FxHashMap<K, V>>().is_none_or(|it| it.is_empty())
}
}

View file

@ -353,7 +353,7 @@ impl DefCollector<'_> {
let is_cfg_enabled = item_tree
.top_level_attrs(self.db, self.def_map.krate)
.cfg()
.map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false));
.is_none_or(|cfg| self.cfg_options.check(&cfg) != Some(false));
if is_cfg_enabled {
self.inject_prelude();

View file

@ -107,8 +107,8 @@ impl RawAttrs {
.chain(b.slice.iter().map(|it| {
let mut it = it.clone();
it.id.id = (it.id.ast_index() as u32 + last_ast_index)
| (it.id.cfg_attr_index().unwrap_or(0) as u32)
<< AttrId::AST_INDEX_BITS;
| ((it.id.cfg_attr_index().unwrap_or(0) as u32)
<< AttrId::AST_INDEX_BITS);
it
}))
.collect::<Vec<_>>();
@ -122,7 +122,7 @@ impl RawAttrs {
pub fn filter(self, db: &dyn ExpandDatabase, krate: CrateId) -> RawAttrs {
let has_cfg_attrs = self
.iter()
.any(|attr| attr.path.as_ident().map_or(false, |name| *name == sym::cfg_attr.clone()));
.any(|attr| attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr.clone()));
if !has_cfg_attrs {
return self;
}
@ -132,7 +132,7 @@ impl RawAttrs {
self.iter()
.flat_map(|attr| -> SmallVec<[_; 1]> {
let is_cfg_attr =
attr.path.as_ident().map_or(false, |name| *name == sym::cfg_attr.clone());
attr.path.as_ident().is_some_and(|name| *name == sym::cfg_attr.clone());
if !is_cfg_attr {
return smallvec![attr.clone()];
}
@ -202,7 +202,7 @@ impl AttrId {
}
pub fn with_cfg_attr(self, idx: usize) -> AttrId {
AttrId { id: self.id | (idx as u32) << Self::AST_INDEX_BITS | Self::CFG_ATTR_SET_BITS }
AttrId { id: self.id | ((idx as u32) << Self::AST_INDEX_BITS) | Self::CFG_ATTR_SET_BITS }
}
}

View file

@ -109,7 +109,7 @@ pub(crate) fn fixup_syntax(
}
},
ast::ExprStmt(it) => {
let needs_semi = it.semicolon_token().is_none() && it.expr().map_or(false, |e| e.syntax().kind() != SyntaxKind::BLOCK_EXPR);
let needs_semi = it.semicolon_token().is_none() && it.expr().is_some_and(|e| e.syntax().kind() != SyntaxKind::BLOCK_EXPR);
if needs_semi {
append.insert(node.clone().into(), vec![
Leaf::Punct(Punct {

View file

@ -1049,7 +1049,7 @@ impl ExpandTo {
if parent.kind() == MACRO_EXPR
&& parent
.parent()
.map_or(false, |p| matches!(p.kind(), EXPR_STMT | STMT_LIST | MACRO_STMTS))
.is_some_and(|p| matches!(p.kind(), EXPR_STMT | STMT_LIST | MACRO_STMTS))
{
return ExpandTo::Statements;
}

View file

@ -49,7 +49,7 @@ fn is_camel_case(name: &str) -> bool {
let mut fst = None;
// start with a non-lowercase letter rather than non-uppercase
// ones (some scripts don't have a concept of upper/lowercase)
name.chars().next().map_or(true, |c| !c.is_lowercase())
name.chars().next().is_none_or(|c| !c.is_lowercase())
&& !name.contains("__")
&& !name.chars().any(|snd| {
let ret = match fst {

View file

@ -295,7 +295,7 @@ impl ExprValidator {
path,
self.body.expr_path_hygiene(scrutinee_expr),
);
value_or_partial.map_or(true, |v| !matches!(v, ValueNs::StaticId(_)))
value_or_partial.is_none_or(|v| !matches!(v, ValueNs::StaticId(_)))
}
Expr::Field { expr, .. } => match self.infer.type_of_expr[*expr].kind(Interner) {
TyKind::Adt(adt, ..)
@ -447,7 +447,7 @@ impl ExprValidator {
loop {
let parent = top_if_expr.syntax().parent();
let has_parent_expr_stmt_or_stmt_list =
parent.as_ref().map_or(false, |node| {
parent.as_ref().is_some_and(|node| {
ast::ExprStmt::can_cast(node.kind())
| ast::StmtList::can_cast(node.kind())
});
@ -529,7 +529,7 @@ impl FilterMapNextChecker {
let is_dyn_trait = self
.prev_receiver_ty
.as_ref()
.map_or(false, |it| it.strip_references().dyn_trait().is_some());
.is_some_and(|it| it.strip_references().dyn_trait().is_some());
if *receiver_expr_id == prev_filter_map_expr_id && !is_dyn_trait {
return Some(());
}

View file

@ -314,7 +314,7 @@ impl<'db> MatchCheckCtx<'db> {
}
}
impl<'db> PatCx for MatchCheckCtx<'db> {
impl PatCx for MatchCheckCtx<'_> {
type Error = ();
type Ty = Ty;
type VariantIdx = EnumVariantContiguousIndex;

View file

@ -992,7 +992,7 @@ impl InferenceContext<'_> {
},
},
}
if self.result.pat_adjustments.get(&p).map_or(false, |it| !it.is_empty()) {
if self.result.pat_adjustments.get(&p).is_some_and(|it| !it.is_empty()) {
for_mut = BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture };
}
self.body.walk_pats_shallow(p, |p| self.walk_pat_inner(p, update_result, for_mut));

View file

@ -206,7 +206,7 @@ impl InferenceContext<'_> {
path,
self.body.expr_path_hygiene(expr),
)
.map_or(true, |res| matches!(res, ValueNs::LocalBinding(_) | ValueNs::StaticId(_))),
.is_none_or(|res| matches!(res, ValueNs::LocalBinding(_) | ValueNs::StaticId(_))),
Expr::Underscore => true,
Expr::UnaryOp { op: UnaryOp::Deref, .. } => true,
Expr::Field { .. } | Expr::Index { .. } => true,
@ -499,7 +499,7 @@ impl InferenceContext<'_> {
// if the function is unresolved, we use is_varargs=true to
// suppress the arg count diagnostic here
let is_varargs =
derefed_callee.callable_sig(self.db).map_or(false, |sig| sig.is_varargs)
derefed_callee.callable_sig(self.db).is_some_and(|sig| sig.is_varargs)
|| res.is_none();
let (param_tys, ret_ty) = match res {
Some((func, params, ret_ty)) => {
@ -2043,7 +2043,7 @@ impl InferenceContext<'_> {
continue;
}
while skip_indices.peek().map_or(false, |i| *i < idx as u32) {
while skip_indices.peek().is_some_and(|i| *i < idx as u32) {
skip_indices.next();
}
if skip_indices.peek().copied() == Some(idx as u32) {

View file

@ -315,13 +315,7 @@ impl InferenceContext<'_> {
}
AssocItemId::ConstId(konst) => {
if self
.db
.const_data(konst)
.name
.as_ref()
.map_or(false, |n| n == segment.name)
{
if self.db.const_data(konst).name.as_ref() == Some(segment.name) {
Some(AssocItemId::ConstId(konst))
} else {
None

View file

@ -282,7 +282,7 @@ impl<'a> InferenceTable<'a> {
let is_diverging = self
.type_variable_table
.get(iv.index() as usize)
.map_or(false, |data| data.contains(TypeVariableFlags::DIVERGING));
.is_some_and(|data| data.contains(TypeVariableFlags::DIVERGING));
if is_diverging {
return TyKind::Never.intern(Interner);
}

View file

@ -139,7 +139,7 @@ impl UninhabitedFrom<'_> {
ty: &Binders<Ty>,
subst: &Substitution,
) -> ControlFlow<VisiblyUninhabited> {
if vis.map_or(true, |it| it.is_visible_from(self.db.upcast(), self.target_mod)) {
if vis.is_none_or(|it| it.is_visible_from(self.db.upcast(), self.target_mod)) {
let ty = ty.clone().substitute(Interner, subst);
ty.visit_with(self, DebruijnIndex::INNERMOST)
} else {

View file

@ -241,31 +241,31 @@ fn recursive() {
#[test]
fn repr_packed() {
size_and_align! {
#[repr(packed)]
#[repr(Rust, packed)]
struct Goal;
}
size_and_align! {
#[repr(packed(2))]
#[repr(Rust, packed(2))]
struct Goal;
}
size_and_align! {
#[repr(packed(4))]
#[repr(Rust, packed(4))]
struct Goal;
}
size_and_align! {
#[repr(packed)]
#[repr(Rust, packed)]
struct Goal(i32);
}
size_and_align! {
#[repr(packed(2))]
#[repr(Rust, packed(2))]
struct Goal(i32);
}
size_and_align! {
#[repr(packed(4))]
#[repr(Rust, packed(4))]
struct Goal(i32);
}
check_size_and_align("#[repr(packed(5))] struct Goal(i32);", "", 4, 1);
check_size_and_align("#[repr(Rust, packed(5))] struct Goal(i32);", "", 4, 1);
}
#[test]

View file

@ -2751,14 +2751,14 @@ fn fallback_bound_vars<T: TypeFoldable<Interner> + HasInterner<Interner = Intern
crate::fold_free_vars(
s,
|bound, binders| {
if bound.index_if_innermost().map_or(true, is_allowed) {
if bound.index_if_innermost().is_none_or(is_allowed) {
bound.shifted_in_from(binders).to_ty(Interner)
} else {
TyKind::Error.intern(Interner)
}
},
|ty, bound, binders| {
if bound.index_if_innermost().map_or(true, is_allowed) {
if bound.index_if_innermost().is_none_or(is_allowed) {
bound.shifted_in_from(binders).to_const(Interner, ty)
} else {
unknown_const(ty)

View file

@ -377,7 +377,7 @@ pub(crate) fn incoherent_inherent_impl_crates(
for krate in crate_graph.transitive_deps(krate) {
let impls = db.inherent_impls_in_crate(krate);
if impls.map.get(&fp).map_or(false, |v| !v.is_empty()) {
if impls.map.get(&fp).is_some_and(|v| !v.is_empty()) {
res.push(krate);
}
}
@ -811,7 +811,7 @@ fn is_inherent_impl_coherent(
| TyKind::Scalar(_) => def_map.is_rustc_coherence_is_core(),
&TyKind::Adt(AdtId(adt), _) => adt.module(db.upcast()).krate() == def_map.krate(),
TyKind::Dyn(it) => it.principal_id().map_or(false, |trait_id| {
TyKind::Dyn(it) => it.principal_id().is_some_and(|trait_id| {
from_chalk_trait_id(trait_id).module(db.upcast()).krate() == def_map.krate()
}),
@ -840,7 +840,7 @@ fn is_inherent_impl_coherent(
.contains(StructFlags::IS_RUSTC_HAS_INCOHERENT_INHERENT_IMPL),
hir_def::AdtId::EnumId(it) => db.enum_data(it).rustc_has_incoherent_inherent_impls,
},
TyKind::Dyn(it) => it.principal_id().map_or(false, |trait_id| {
TyKind::Dyn(it) => it.principal_id().is_some_and(|trait_id| {
db.trait_data(from_chalk_trait_id(trait_id))
.flags
.contains(TraitFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS)
@ -903,7 +903,7 @@ pub fn check_orphan_rules(db: &dyn HirDatabase, impl_: ImplId) -> bool {
match unwrap_fundamental(ty).kind(Interner) {
&TyKind::Adt(AdtId(id), _) => is_local(id.module(db.upcast()).krate()),
TyKind::Error => true,
TyKind::Dyn(it) => it.principal_id().map_or(false, |trait_id| {
TyKind::Dyn(it) => it.principal_id().is_some_and(|trait_id| {
is_local(from_chalk_trait_id(trait_id).module(db.upcast()).krate())
}),
_ => false,
@ -1481,7 +1481,7 @@ fn is_valid_impl_method_candidate(
AssocItemId::ConstId(c) => {
let db = table.db;
check_that!(receiver_ty.is_none());
check_that!(name.map_or(true, |n| db.const_data(c).name.as_ref() == Some(n)));
check_that!(name.is_none_or(|n| db.const_data(c).name.as_ref() == Some(n)));
if let Some(from_module) = visible_from_module {
if !db.const_visibility(c).is_visible_from(db.upcast(), from_module) {
@ -1519,7 +1519,7 @@ fn is_valid_trait_method_candidate(
AssocItemId::FunctionId(fn_id) => {
let data = db.function_data(fn_id);
check_that!(name.map_or(true, |n| n == &data.name));
check_that!(name.is_none_or(|n| n == &data.name));
table.run_in_snapshot(|table| {
let impl_subst = TyBuilder::subst_for_def(db, trait_id, None)
@ -1548,7 +1548,7 @@ fn is_valid_trait_method_candidate(
}
AssocItemId::ConstId(c) => {
check_that!(receiver_ty.is_none());
check_that!(name.map_or(true, |n| db.const_data(c).name.as_ref() == Some(n)));
check_that!(name.is_none_or(|n| db.const_data(c).name.as_ref() == Some(n)));
IsValidCandidate::Yes
}
@ -1569,7 +1569,7 @@ fn is_valid_impl_fn_candidate(
let db = table.db;
let data = db.function_data(fn_id);
check_that!(name.map_or(true, |n| n == &data.name));
check_that!(name.is_none_or(|n| n == &data.name));
if let Some(from_module) = visible_from_module {
if !db.function_visibility(fn_id).is_visible_from(db.upcast(), from_module) {
cov_mark::hit!(autoderef_candidate_not_visible);

View file

@ -2113,7 +2113,7 @@ impl Evaluator<'_> {
while self.heap.len() % align != 0 {
self.heap.push(0);
}
if size.checked_add(self.heap.len()).map_or(true, |x| x > self.memory_limit) {
if size.checked_add(self.heap.len()).is_none_or(|x| x > self.memory_limit) {
return Err(MirEvalError::Panic(format!("Memory allocation of {size} bytes failed")));
}
let pos = self.heap.len();

View file

@ -373,7 +373,7 @@ impl OpaqueInternableThing for InTypeConstIdMetadata {
}
fn dyn_eq(&self, other: &dyn OpaqueInternableThing) -> bool {
other.as_any().downcast_ref::<Self>().map_or(false, |x| self == x)
other.as_any().downcast_ref::<Self>() == Some(self)
}
fn dyn_clone(&self) -> Box<dyn OpaqueInternableThing> {

View file

@ -699,7 +699,7 @@ impl Module {
let source_map = tree_source_maps.impl_(loc.id.value).item();
let node = &tree[loc.id.value];
let file_id = loc.id.file_id();
if file_id.macro_file().map_or(false, |it| it.is_builtin_derive(db.upcast())) {
if file_id.macro_file().is_some_and(|it| it.is_builtin_derive(db.upcast())) {
// these expansion come from us, diagnosing them is a waste of resources
// FIXME: Once we diagnose the inputs to builtin derives, we should at least extract those diagnostics somehow
continue;
@ -724,7 +724,7 @@ impl Module {
}
let trait_ = impl_def.trait_(db);
let trait_is_unsafe = trait_.map_or(false, |t| t.is_unsafe(db));
let trait_is_unsafe = trait_.is_some_and(|t| t.is_unsafe(db));
let impl_is_negative = impl_def.is_negative(db);
let impl_is_unsafe = impl_def.is_unsafe(db);

View file

@ -1206,7 +1206,6 @@ impl<'db> SemanticsImpl<'db> {
node.original_file_range_opt(self.db.upcast())
.filter(|(_, ctx)| ctx.is_root())
.map(TupleExt::head)
.map(Into::into)
}
/// Attempts to map the node out of macro expanded files.
@ -1500,7 +1499,7 @@ impl<'db> SemanticsImpl<'db> {
pub fn is_proc_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
self.resolve_macro_call(macro_call)
.map_or(false, |m| matches!(m.id, MacroId::ProcMacroId(..)))
.is_some_and(|m| matches!(m.id, MacroId::ProcMacroId(..)))
}
pub fn resolve_macro_call_arm(&self, macro_call: &ast::MacroCall) -> Option<u32> {

View file

@ -408,7 +408,7 @@ impl SourceToDefCtx<'_, '_> {
}
pub(super) fn has_derives(&mut self, adt: InFile<&ast::Adt>) -> bool {
self.dyn_map(adt).as_ref().map_or(false, |map| !map[keys::DERIVE_MACRO_CALL].is_empty())
self.dyn_map(adt).as_ref().is_some_and(|map| !map[keys::DERIVE_MACRO_CALL].is_empty())
}
fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(

View file

@ -949,7 +949,7 @@ impl SourceAnalyzer {
.map(|it| (it, None)),
};
}
if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
if parent().is_some_and(|it| ast::Visibility::can_cast(it.kind())) {
// No substitution because only modules can be inside visibilities, and those have no generics.
resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &types_map)
.map(|it| (it, None))

View file

@ -28,7 +28,7 @@ pub(crate) fn add_lifetime_to_type(acc: &mut Assists, ctx: &AssistContext<'_>) -
let node = ctx.find_node_at_offset::<ast::Adt>()?;
let has_lifetime = node
.generic_param_list()
.map_or(false, |gen_list| gen_list.lifetime_params().next().is_some());
.is_some_and(|gen_list| gen_list.lifetime_params().next().is_some());
if has_lifetime {
return None;

View file

@ -220,7 +220,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.arms()
.find(|arm| matches!(arm.pat(), Some(ast::Pat::WildcardPat(_))));
if let Some(arm) = catch_all_arm {
let is_empty_expr = arm.expr().map_or(true, |e| match e {
let is_empty_expr = arm.expr().is_none_or(|e| match e {
ast::Expr::BlockExpr(b) => {
b.statements().next().is_none() && b.tail_expr().is_none()
}

View file

@ -63,7 +63,7 @@ pub(crate) fn convert_nested_function_to_closure(
/// Returns whether the given function is nested within the body of another function.
fn is_nested_function(function: &ast::Fn) -> bool {
function.syntax().ancestors().skip(1).find_map(ast::Item::cast).map_or(false, |it| {
function.syntax().ancestors().skip(1).find_map(ast::Item::cast).is_some_and(|it| {
matches!(it, ast::Item::Fn(_) | ast::Item::Static(_) | ast::Item::Const(_))
})
}

View file

@ -96,8 +96,7 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option<Str
let struct_def_path = module.find_path(ctx.db(), struct_def, cfg)?;
let is_non_exhaustive = struct_def.attrs(ctx.db())?.by_key(&sym::non_exhaustive).exists();
let is_foreign_crate =
struct_def.module(ctx.db()).map_or(false, |m| m.krate() != module.krate());
let is_foreign_crate = struct_def.module(ctx.db()).is_some_and(|m| m.krate() != module.krate());
let fields = struct_type.fields(ctx.db());
let n_fields = fields.len();

View file

@ -856,7 +856,7 @@ impl FunctionBody {
let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
if loop_
.loop_body()
.map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
.is_some_and(|it| it.syntax().text_range().contains_range(self.text_range()))
{
parent_loop.get_or_insert(loop_.syntax().clone());
}
@ -1090,7 +1090,7 @@ impl FunctionBody {
let defined_outside_parent_loop = container_info
.parent_loop
.as_ref()
.map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
.is_none_or(|it| it.text_range().contains_range(src.syntax().text_range()));
let is_copy = ty.is_copy(ctx.db());
let has_usages = self.has_usages_after_body(&usages);

View file

@ -100,7 +100,7 @@ fn collect_used_generics<'gp>(
fn find_lifetime(text: &str) -> impl Fn(&&ast::GenericParam) -> bool + '_ {
move |gp: &&ast::GenericParam| match gp {
ast::GenericParam::LifetimeParam(lp) => {
lp.lifetime().map_or(false, |lt| lt.text() == text)
lp.lifetime().is_some_and(|lt| lt.text() == text)
}
_ => false,
}
@ -118,7 +118,7 @@ fn collect_used_generics<'gp>(
ast::GenericParam::TypeParam(tp) => tp.name(),
_ => None,
}
.map_or(false, |n| n.text() == name_ref.text())
.is_some_and(|n| n.text() == name_ref.text())
}) {
generics.push(param);
}
@ -165,7 +165,7 @@ fn collect_used_generics<'gp>(
if let Some(name_ref) = path.as_single_name_ref() {
if let Some(param) = known_generics.iter().find(|gp| {
if let ast::GenericParam::ConstParam(cp) = gp {
cp.name().map_or(false, |n| n.text() == name_ref.text())
cp.name().is_some_and(|n| n.text() == name_ref.text())
} else {
false
}

View file

@ -99,7 +99,7 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
let parent = to_extract.syntax().parent().and_then(ast::Expr::cast);
// Any expression that autoderefs may need adjustment.
let mut needs_adjust = parent.as_ref().map_or(false, |it| match it {
let mut needs_adjust = parent.as_ref().is_some_and(|it| match it {
ast::Expr::FieldExpr(_)
| ast::Expr::MethodCallExpr(_)
| ast::Expr::CallExpr(_)

View file

@ -47,7 +47,7 @@ pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext<'_>) ->
.parent() // AssocItemList
.and_then(|x| x.parent())
.and_then(ast::Impl::cast)
.map_or(false, |imp| imp.trait_().is_some())
.is_some_and(|imp| imp.trait_().is_some())
{
cov_mark::hit!(trait_impl);
return None;

View file

@ -135,7 +135,7 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext<'
};
let has_preceding_if_expr =
if_expr.syntax().parent().map_or(false, |it| ast::IfExpr::can_cast(it.kind()));
if_expr.syntax().parent().is_some_and(|it| ast::IfExpr::can_cast(it.kind()));
let expr = if has_preceding_if_expr {
// make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
make::block_expr(None, Some(match_expr)).into()
@ -241,7 +241,7 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'
ast::Pat::LiteralPat(p)
if p.literal()
.map(|it| it.token().kind())
.map_or(false, |it| it == T![true] || it == T![false]) =>
.is_some_and(|it| it == T![true] || it == T![false]) =>
{
""
}
@ -265,12 +265,12 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'
let condition = match if_let_pat {
ast::Pat::LiteralPat(p)
if p.literal().map_or(false, |it| it.token().kind() == T![true]) =>
if p.literal().is_some_and(|it| it.token().kind() == T![true]) =>
{
scrutinee
}
ast::Pat::LiteralPat(p)
if p.literal().map_or(false, |it| it.token().kind() == T![false]) =>
if p.literal().is_some_and(|it| it.token().kind() == T![false]) =>
{
make::expr_prefix(T![!], scrutinee)
}
@ -339,10 +339,10 @@ fn binds_name(sema: &hir::Semantics<'_, RootDatabase>, pat: &ast::Pat) -> bool {
ast::Pat::TupleStructPat(it) => it.fields().any(binds_name_v),
ast::Pat::RecordPat(it) => it
.record_pat_field_list()
.map_or(false, |rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
ast::Pat::RefPat(pat) => pat.pat().map_or(false, binds_name_v),
ast::Pat::BoxPat(pat) => pat.pat().map_or(false, binds_name_v),
ast::Pat::ParenPat(pat) => pat.pat().map_or(false, binds_name_v),
.is_some_and(|rpfl| rpfl.fields().flat_map(|rpf| rpf.pat()).any(binds_name_v)),
ast::Pat::RefPat(pat) => pat.pat().is_some_and(binds_name_v),
ast::Pat::BoxPat(pat) => pat.pat().is_some_and(binds_name_v),
ast::Pat::ParenPat(pat) => pat.pat().is_some_and(binds_name_v),
_ => false,
}
}
@ -350,7 +350,7 @@ fn binds_name(sema: &hir::Semantics<'_, RootDatabase>, pat: &ast::Pat) -> bool {
fn is_sad_pat(sema: &hir::Semantics<'_, RootDatabase>, pat: &ast::Pat) -> bool {
sema.type_of_pat(pat)
.and_then(|ty| TryEnum::from_ty(sema, &ty.adjusted()))
.map_or(false, |it| does_pat_match_variant(pat, &it.sad_pattern()))
.is_some_and(|it| does_pat_match_variant(pat, &it.sad_pattern()))
}
#[cfg(test)]

View file

@ -159,7 +159,7 @@ fn path_eq_no_generics(lhs: ast::Path, rhs: ast::Path) -> bool {
&& lhs
.name_ref()
.zip(rhs.name_ref())
.map_or(false, |(lhs, rhs)| lhs.text() == rhs.text()) => {}
.is_some_and(|(lhs, rhs)| lhs.text() == rhs.text()) => {}
_ => return false,
}

View file

@ -65,7 +65,7 @@ pub(crate) fn unmerge_match_arm(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
let mut pipe_index = pipe_token.index();
if pipe_token
.prev_sibling_or_token()
.map_or(false, |it| it.kind() == SyntaxKind::WHITESPACE)
.is_some_and(|it| it.kind() == SyntaxKind::WHITESPACE)
{
pipe_index -= 1;
}

View file

@ -66,7 +66,7 @@ fn resolve_full_path(tree: &ast::UseTree) -> Option<ast::Path> {
.filter_map(|t| t.path());
let final_path = paths.reduce(|prev, next| make::path_concat(next, prev))?;
if final_path.segment().map_or(false, |it| it.self_token().is_some()) {
if final_path.segment().is_some_and(|it| it.self_token().is_some()) {
final_path.qualifier()
} else {
Some(final_path)

View file

@ -321,8 +321,8 @@ pub(crate) fn does_pat_variant_nested_or_literal(ctx: &AssistContext<'_>, pat: &
}
fn check_pat_variant_from_enum(ctx: &AssistContext<'_>, pat: &ast::Pat) -> bool {
ctx.sema.type_of_pat(pat).map_or(true, |ty: hir::TypeInfo| {
ty.adjusted().as_adt().map_or(false, |adt| matches!(adt, hir::Adt::Enum(_)))
ctx.sema.type_of_pat(pat).is_none_or(|ty: hir::TypeInfo| {
ty.adjusted().as_adt().is_some_and(|adt| matches!(adt, hir::Adt::Enum(_)))
})
}
@ -345,10 +345,10 @@ fn check_pat_variant_nested_or_literal_with_depth(
| ast::Pat::BoxPat(_)
| ast::Pat::ConstBlockPat(_) => true,
ast::Pat::IdentPat(ident_pat) => ident_pat.pat().map_or(false, |pat| {
ast::Pat::IdentPat(ident_pat) => ident_pat.pat().is_some_and(|pat| {
check_pat_variant_nested_or_literal_with_depth(ctx, &pat, depth_after_refutable)
}),
ast::Pat::ParenPat(paren_pat) => paren_pat.pat().map_or(true, |pat| {
ast::Pat::ParenPat(paren_pat) => paren_pat.pat().is_none_or(|pat| {
check_pat_variant_nested_or_literal_with_depth(ctx, &pat, depth_after_refutable)
}),
ast::Pat::TuplePat(tuple_pat) => tuple_pat.fields().any(|pat| {
@ -357,9 +357,9 @@ fn check_pat_variant_nested_or_literal_with_depth(
ast::Pat::RecordPat(record_pat) => {
let adjusted_next_depth =
depth_after_refutable + if check_pat_variant_from_enum(ctx, pat) { 1 } else { 0 };
record_pat.record_pat_field_list().map_or(true, |pat| {
record_pat.record_pat_field_list().is_none_or(|pat| {
pat.fields().any(|pat| {
pat.pat().map_or(true, |pat| {
pat.pat().is_none_or(|pat| {
check_pat_variant_nested_or_literal_with_depth(
ctx,
&pat,
@ -381,8 +381,8 @@ fn check_pat_variant_nested_or_literal_with_depth(
}
ast::Pat::SlicePat(slice_pat) => {
let mut pats = slice_pat.pats();
pats.next() // Edge case for `[..]`
.map_or(true, |pat| !matches!(pat, ast::Pat::RestPat(_)) || pats.next().is_some())
pats.next()
.is_none_or(|pat| !matches!(pat, ast::Pat::RestPat(_)) || pats.next().is_some())
}
}
}

View file

@ -32,7 +32,7 @@ pub(crate) fn gen_trait_fn_body(
/// Generate a `Clone` impl based on the fields and members of the target type.
fn gen_clone_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
stdx::always!(func.name().map_or(false, |name| name.text() == "clone"));
stdx::always!(func.name().is_some_and(|name| name.text() == "clone"));
fn gen_clone_call(target: ast::Expr) -> ast::Expr {
let method = make::name_ref("clone");
make::expr_method_call(target, method, make::arg_list(None))
@ -344,7 +344,7 @@ fn gen_default_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
/// Generate a `Hash` impl based on the fields and members of the target type.
fn gen_hash_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
stdx::always!(func.name().map_or(false, |name| name.text() == "hash"));
stdx::always!(func.name().is_some_and(|name| name.text() == "hash"));
fn gen_hash_call(target: ast::Expr) -> ast::Stmt {
let method = make::name_ref("hash");
let arg = make::expr_path(make::ext::ident_path("state"));
@ -400,7 +400,7 @@ fn gen_hash_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
/// Generate a `PartialEq` impl based on the fields and members of the target type.
fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn, trait_ref: Option<TraitRef>) -> Option<()> {
stdx::always!(func.name().map_or(false, |name| name.text() == "eq"));
stdx::always!(func.name().is_some_and(|name| name.text() == "eq"));
fn gen_eq_chain(expr: Option<ast::Expr>, cmp: ast::Expr) -> Option<ast::Expr> {
match expr {
Some(expr) => Some(make::expr_bin_op(expr, BinaryOp::LogicOp(LogicOp::And), cmp)),
@ -592,7 +592,7 @@ fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn, trait_ref: Option<TraitRef>) -
}
fn gen_partial_ord(adt: &ast::Adt, func: &ast::Fn, trait_ref: Option<TraitRef>) -> Option<()> {
stdx::always!(func.name().map_or(false, |name| name.text() == "partial_cmp"));
stdx::always!(func.name().is_some_and(|name| name.text() == "partial_cmp"));
fn gen_partial_eq_match(match_target: ast::Expr) -> Option<ast::Stmt> {
let mut arms = vec![];

View file

@ -43,7 +43,7 @@ pub(crate) fn complete_cargo_env_vars(
.sema
.hir_file_for(&expanded.syntax().parent()?)
.macro_file()
.map_or(false, |it| it.is_env_or_option_env(ctx.sema.db));
.is_some_and(|it| it.is_env_or_option_env(ctx.sema.db));
if !is_in_env_expansion {
let call = macro_call_for_string_token(expanded)?;
let makro = ctx.sema.resolve_macro_call(&call)?;

View file

@ -46,7 +46,7 @@ pub(crate) fn complete_extern_abi(
ctx: &CompletionContext<'_>,
expanded: &ast::String,
) -> Option<()> {
if !expanded.syntax().parent().map_or(false, |it| ast::Abi::can_cast(it.kind())) {
if !expanded.syntax().parent().is_some_and(|it| ast::Abi::can_cast(it.kind())) {
return None;
}
let abi_str = expanded;

View file

@ -167,7 +167,7 @@ fn should_add_self_completions(
return false;
}
match param_list.params().next() {
Some(first) => first.pat().map_or(false, |pat| pat.syntax().text_range().contains(cursor)),
Some(first) => first.pat().is_some_and(|pat| pat.syntax().text_range().contains(cursor)),
None => true,
}
}

View file

@ -93,7 +93,7 @@ pub(crate) fn add_default_update(
let default_trait = ctx.famous_defs().core_default_Default();
let impls_default_trait = default_trait
.zip(ty.as_ref())
.map_or(false, |(default_trait, ty)| ty.original.impls_trait(ctx.db, default_trait, &[]));
.is_some_and(|(default_trait, ty)| ty.original.impls_trait(ctx.db, default_trait, &[]));
if impls_default_trait {
// FIXME: This should make use of scope_def like completions so we get all the other goodies
// that is we should handle this like actually completing the default function

View file

@ -101,7 +101,7 @@ pub(crate) fn complete_use_path(
ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(e))) => {
// exclude prelude enum
let is_builtin =
res.krate(ctx.db).map_or(false, |krate| krate.is_builtin(ctx.db));
res.krate(ctx.db).is_some_and(|krate| krate.is_builtin(ctx.db));
if !is_builtin {
let item = CompletionItem::new(

View file

@ -456,7 +456,7 @@ fn analyze(
&& p.ancestors().any(|it| it.kind() == SyntaxKind::META)
{
let colon_prefix = previous_non_trivia_token(self_token.clone())
.map_or(false, |it| T![:] == it.kind());
.is_some_and(|it| T![:] == it.kind());
CompletionAnalysis::UnexpandedAttrTT {
fake_attribute_under_caret: fake_ident_token
@ -643,7 +643,7 @@ fn expected_type_and_name(
// match foo { $0 }
// match foo { ..., pat => $0 }
ast::MatchExpr(it) => {
let on_arrow = previous_non_trivia_token(token.clone()).map_or(false, |it| T![=>] == it.kind());
let on_arrow = previous_non_trivia_token(token.clone()).is_some_and(|it| T![=>] == it.kind());
let ty = if on_arrow {
// match foo { ..., pat => $0 }
@ -780,7 +780,7 @@ fn classify_name_ref(
if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
let dot_prefix = previous_non_trivia_token(name_ref.syntax().clone())
.map_or(false, |it| T![.] == it.kind());
.is_some_and(|it| T![.] == it.kind());
return find_node_in_file_compensated(
sema,
@ -814,7 +814,7 @@ fn classify_name_ref(
let receiver_is_ambiguous_float_literal = match &receiver {
Some(ast::Expr::Literal(l)) => matches! {
l.kind(),
ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().is_some_and(|it| it.text().ends_with('.'))
},
_ => false,
};
@ -846,7 +846,7 @@ fn classify_name_ref(
let receiver = find_opt_node_in_file(original_file, method.receiver());
let kind = NameRefKind::DotAccess(DotAccess {
receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
kind: DotAccessKind::Method { has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some()) },
kind: DotAccessKind::Method { has_parens: method.arg_list().is_some_and(|it| it.l_paren_token().is_some()) },
receiver,
ctx: DotAccessExprCtx { in_block_expr: is_in_block(method.syntax()), in_breakable: is_in_breakable(method.syntax()) }
});
@ -1193,13 +1193,13 @@ fn classify_name_ref(
let incomplete_let = it
.parent()
.and_then(ast::LetStmt::cast)
.map_or(false, |it| it.semicolon_token().is_none());
.is_some_and(|it| it.semicolon_token().is_none());
let impl_ = fetch_immediate_impl(sema, original_file, expr.syntax());
let in_match_guard = match it.parent().and_then(ast::MatchArm::cast) {
Some(arm) => arm
.fat_arrow_token()
.map_or(true, |arrow| it.text_range().start() < arrow.text_range().start()),
.is_none_or(|arrow| it.text_range().start() < arrow.text_range().start()),
None => false,
};
@ -1329,7 +1329,7 @@ fn classify_name_ref(
}
}
path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::can_cast(it.kind()));
make_path_kind_expr(it.into())
},
@ -1358,7 +1358,7 @@ fn classify_name_ref(
match parent {
ast::PathType(it) => make_path_kind_type(it.into()),
ast::PathExpr(it) => {
path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::can_cast(it.kind()));
make_path_kind_expr(it.into())
},
@ -1612,8 +1612,7 @@ fn pattern_context_for(
&pat,
ast::Pat::IdentPat(it)
if it.syntax()
.parent()
.map_or(false, |node| {
.parent().is_some_and(|node| {
let kind = node.kind();
ast::LetStmt::can_cast(kind) || ast::Param::can_cast(kind)
})

View file

@ -631,7 +631,7 @@ impl Builder {
self.set_documentation(Some(docs))
}
pub(crate) fn set_documentation(&mut self, docs: Option<Documentation>) -> &mut Builder {
self.documentation = docs.map(Into::into);
self.documentation = docs;
self
}
pub(crate) fn set_deprecated(&mut self, deprecated: bool) -> &mut Builder {

View file

@ -86,11 +86,7 @@ impl<'a> RenderContext<'a> {
fn is_immediately_after_macro_bang(&self) -> bool {
self.completion.token.kind() == SyntaxKind::BANG
&& self
.completion
.token
.parent()
.map_or(false, |it| it.kind() == SyntaxKind::MACRO_CALL)
&& self.completion.token.parent().is_some_and(|it| it.kind() == SyntaxKind::MACRO_CALL)
}
fn is_deprecated(&self, def: impl HasAttrs) -> bool {
@ -636,7 +632,7 @@ fn compute_type_match(
}
fn compute_exact_name_match(ctx: &CompletionContext<'_>, completion_name: &str) -> bool {
ctx.expected_name.as_ref().map_or(false, |name| name.text() == completion_name)
ctx.expected_name.as_ref().is_some_and(|name| name.text() == completion_name)
}
fn compute_ref_match(
@ -778,7 +774,7 @@ mod tests {
relevance.postfix_match == Some(CompletionRelevancePostfixMatch::Exact),
"snippet",
),
(relevance.trait_.map_or(false, |it| it.is_op_method), "op_method"),
(relevance.trait_.is_some_and(|it| it.is_op_method), "op_method"),
(relevance.requires_import, "requires_import"),
]
.into_iter()

View file

@ -48,7 +48,7 @@ pub fn callable_for_token(
let parent = token.parent()?;
let calling_node = parent.ancestors().filter_map(ast::CallableExpr::cast).find(|it| {
it.arg_list()
.map_or(false, |it| it.syntax().text_range().contains(token.text_range().start()))
.is_some_and(|it| it.syntax().text_range().contains(token.text_range().start()))
})?;
callable_for_node(sema, &calling_node, &token)
@ -136,7 +136,7 @@ pub fn generic_def_for_node(
let first_arg_is_non_lifetime = generic_arg_list
.generic_args()
.next()
.map_or(false, |arg| !matches!(arg, ast::GenericArg::LifetimeArg(_)));
.is_some_and(|arg| !matches!(arg, ast::GenericArg::LifetimeArg(_)));
Some((def, active_param, first_arg_is_non_lifetime, variant))
}

View file

@ -335,7 +335,7 @@ fn find_std_module(
let std_crate = famous_defs.std()?;
let std_root_module = std_crate.root_module();
std_root_module.children(db).find(|module| {
module.name(db).map_or(false, |module| module.display(db, edition).to_string() == name)
module.name(db).is_some_and(|module| module.display(db, edition).to_string() == name)
})
}

View file

@ -226,9 +226,8 @@ impl HasDocs for hir::AssocItem {
impl HasDocs for hir::ExternCrateDecl {
fn docs(self, db: &dyn HirDatabase) -> Option<Documentation> {
let crate_docs =
docs_from_attrs(&self.resolved_crate(db)?.root_module().attrs(db)).map(String::from);
let decl_docs = docs_from_attrs(&self.attrs(db)).map(String::from);
let crate_docs = docs_from_attrs(&self.resolved_crate(db)?.root_module().attrs(db));
let decl_docs = docs_from_attrs(&self.attrs(db));
match (decl_docs, crate_docs) {
(None, None) => None,
(Some(decl_docs), None) => Some(decl_docs),

View file

@ -706,7 +706,7 @@ fn path_import_candidate(
Some(match qualifier {
Some(qualifier) => match sema.resolve_path(&qualifier) {
Some(PathResolution::Def(ModuleDef::BuiltinType(_))) | None => {
if qualifier.first_qualifier().map_or(true, |it| sema.resolve_path(&it).is_none()) {
if qualifier.first_qualifier().is_none_or(|it| sema.resolve_path(&it).is_none()) {
let qualifier = qualifier
.segments()
.map(|seg| seg.name_ref().map(|name| SmolStr::new(name.text())))

View file

@ -72,9 +72,7 @@ impl ImportScope {
fn from(syntax: SyntaxNode) -> Option<Self> {
use syntax::match_ast;
fn contains_cfg_attr(attrs: &dyn HasAttrs) -> bool {
attrs
.attrs()
.any(|attr| attr.as_simple_call().map_or(false, |(ident, _)| ident == "cfg"))
attrs.attrs().any(|attr| attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg"))
}
match_ast! {
match syntax {
@ -102,9 +100,7 @@ impl ImportScope {
sema: &Semantics<'_, RootDatabase>,
) -> Option<Self> {
fn contains_cfg_attr(attrs: &dyn HasAttrs) -> bool {
attrs
.attrs()
.any(|attr| attr.as_simple_call().map_or(false, |(ident, _)| ident == "cfg"))
attrs.attrs().any(|attr| attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg"))
}
// Walk up the ancestor tree searching for a suitable node to do insertions on
@ -487,7 +483,7 @@ fn insert_use_(scope: &ImportScope, use_item: ast::Use, group_imports: bool) {
.contains(&token.kind())
}
})
.filter(|child| child.as_token().map_or(true, |t| t.kind() != SyntaxKind::WHITESPACE))
.filter(|child| child.as_token().is_none_or(|t| t.kind() != SyntaxKind::WHITESPACE))
.last()
{
cov_mark::hit!(insert_empty_inner_attr);

View file

@ -290,7 +290,7 @@ pub fn try_normalize_use_tree_mut(
fn recursive_normalize(use_tree: &ast::UseTree, style: NormalizationStyle) -> Option<()> {
let use_tree_list = use_tree.use_tree_list()?;
let merge_subtree_into_parent_tree = |single_subtree: &ast::UseTree| {
let subtree_is_only_self = single_subtree.path().as_ref().map_or(false, path_is_self);
let subtree_is_only_self = single_subtree.path().as_ref().is_some_and(path_is_self);
let merged_path = match (use_tree.path(), single_subtree.path()) {
// If the subtree is `{self}` then we cannot merge: `use

View file

@ -320,7 +320,7 @@ impl<'a> Ranker<'a> {
let same_text = tok.text() == self.text;
// anything that mapped into a token tree has likely no semantic information
let no_tt_parent =
tok.parent().map_or(false, |it| it.kind() != parser::SyntaxKind::TOKEN_TREE);
tok.parent().is_some_and(|it| it.kind() != parser::SyntaxKind::TOKEN_TREE);
(both_idents as usize)
| ((exact_same_kind as usize) << 1)
| ((same_text as usize) << 2)

View file

@ -285,7 +285,7 @@ impl Ctx<'_> {
if path.qualifier().is_some() {
return None;
}
if path.segment().map_or(false, |s| {
if path.segment().is_some_and(|s| {
s.parenthesized_arg_list().is_some()
|| (s.self_token().is_some() && path.parent_path().is_none())
}) {

View file

@ -1356,12 +1356,12 @@ fn is_name_ref_in_import(name_ref: &ast::NameRef) -> bool {
.parent()
.and_then(ast::PathSegment::cast)
.and_then(|it| it.parent_path().top_path().syntax().parent())
.map_or(false, |it| it.kind() == SyntaxKind::USE_TREE)
.is_some_and(|it| it.kind() == SyntaxKind::USE_TREE)
}
fn is_name_ref_in_test(sema: &Semantics<'_, RootDatabase>, name_ref: &ast::NameRef) -> bool {
name_ref.syntax().ancestors().any(|node| match ast::Fn::cast(node) {
Some(it) => sema.to_def(&it).map_or(false, |func| func.is_test(sema.db)),
Some(it) => sema.to_def(&it).is_some_and(|func| func.is_test(sema.db)),
None => false,
})
}

View file

@ -220,7 +220,7 @@ pub fn vis_eq(this: &ast::Visibility, other: &ast::Visibility) -> bool {
match (this.kind(), other.kind()) {
(VisibilityKind::In(this), VisibilityKind::In(other)) => {
stdx::iter_eq_by(this.segments(), other.segments(), |lhs, rhs| {
lhs.kind().zip(rhs.kind()).map_or(false, |it| match it {
lhs.kind().zip(rhs.kind()).is_some_and(|it| match it {
(PathSegmentKind::CrateKw, PathSegmentKind::CrateKw)
| (PathSegmentKind::SelfKw, PathSegmentKind::SelfKw)
| (PathSegmentKind::SuperKw, PathSegmentKind::SuperKw) => true,
@ -259,7 +259,7 @@ pub fn is_pattern_cond(expr: ast::Expr) -> bool {
.or_else(|| expr.rhs().map(is_pattern_cond))
.unwrap_or(false)
}
ast::Expr::ParenExpr(expr) => expr.expr().map_or(false, is_pattern_cond),
ast::Expr::ParenExpr(expr) => expr.expr().is_some_and(is_pattern_cond),
ast::Expr::LetExpr(_) => true,
_ => false,
}
@ -408,7 +408,7 @@ fn for_each_break_expr(
}
pub fn eq_label_lt(lt1: &Option<ast::Lifetime>, lt2: &Option<ast::Lifetime>) -> bool {
lt1.as_ref().zip(lt2.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
lt1.as_ref().zip(lt2.as_ref()).is_some_and(|(lt, lbl)| lt.text() == lbl.text())
}
struct TreeWithDepthIterator {

View file

@ -25,7 +25,7 @@ pub(super) fn parse_intra_doc_link(s: &str) -> (&str, Option<hir::Namespace>) {
.find_map(|(ns, (prefixes, suffixes))| {
if let Some(prefix) = prefixes.iter().find(|&&prefix| {
s.starts_with(prefix)
&& s.chars().nth(prefix.len()).map_or(false, |c| c == '@' || c == ' ')
&& s.chars().nth(prefix.len()).is_some_and(|c| c == '@' || c == ' ')
}) {
Some((&s[prefix.len() + 1..], ns))
} else {
@ -41,7 +41,7 @@ pub(super) fn strip_prefixes_suffixes(s: &str) -> &str {
.find_map(|(prefixes, suffixes)| {
if let Some(prefix) = prefixes.iter().find(|&&prefix| {
s.starts_with(prefix)
&& s.chars().nth(prefix.len()).map_or(false, |c| c == '@' || c == ' ')
&& s.chars().nth(prefix.len()).is_some_and(|c| c == '@' || c == ' ')
}) {
Some(&s[prefix.len() + 1..])
} else {

View file

@ -307,7 +307,7 @@ fn hl_exit_points(
let range = match &expr {
ast::Expr::TryExpr(try_) => try_.question_mark_token().map(|token| token.text_range()),
ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroExpr(_)
if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) =>
if sema.type_of_expr(&expr).is_some_and(|ty| ty.original.is_never()) =>
{
Some(expr.syntax().text_range())
}

View file

@ -336,8 +336,8 @@ pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<Hove
.and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
.filter(|t| t.kind() == T![:])
.and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
.map_or(false, |t| {
t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
.is_some_and(|t| {
t.kind() == T![ident] && t.into_token().is_some_and(|t| t.text() == "clippy")
});
if is_clippy {
(true, CLIPPY_LINTS)
@ -969,7 +969,7 @@ fn find_std_module(
let std_crate = famous_defs.std()?;
let std_root_module = std_crate.root_module();
std_root_module.children(db).find(|module| {
module.name(db).map_or(false, |module| module.display(db, edition).to_string() == name)
module.name(db).is_some_and(|module| module.display(db, edition).to_string() == name)
})
}

View file

@ -313,7 +313,7 @@ fn needs_parens_for_adjustment_hints(expr: &ast::Expr, postfix: bool) -> (bool,
// - `dummy_expr` is the original expression wrapped in the operator we want (`*`/`.*`)
// - `expr` is the clone of the original expression (with `dummy_expr` as the parent)
let needs_outer_parens = parent.map_or(false, |p| dummy_expr.needs_parens_in(p));
let needs_outer_parens = parent.is_some_and(|p| dummy_expr.needs_parens_in(p));
let needs_inner_parens = expr.needs_parens_in(dummy_expr.syntax().clone());
(needs_outer_parens, needs_inner_parens)

View file

@ -32,7 +32,7 @@ pub(super) fn enum_hints(
return None;
}
// data carrying enums without a primitive repr have no stable discriminants
if data_carrying && def.repr(sema.db).map_or(true, |r| r.int.is_none()) {
if data_carrying && def.repr(sema.db).is_none_or(|r| r.int.is_none()) {
return None;
}
for variant in enum_.variant_list()?.variants() {

View file

@ -153,7 +153,7 @@ fn is_param_name_suffix_of_fn_name(
.len()
.checked_sub(param_name.len())
.and_then(|at| function.is_char_boundary(at).then(|| function.split_at(at)))
.map_or(false, |(prefix, suffix)| {
.is_some_and(|(prefix, suffix)| {
suffix.eq_ignore_ascii_case(param_name) && prefix.ends_with('_')
})
}

View file

@ -675,9 +675,7 @@ impl Analysis {
position: FilePosition,
trigger_character: Option<char>,
) -> Cancellable<Option<Vec<CompletionItem>>> {
self.with_db(|db| {
ide_completion::completions(db, config, position, trigger_character).map(Into::into)
})
self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
}
/// Resolves additional completion data at the position given.

View file

@ -34,7 +34,7 @@ pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<Na
if let Some(m) = &module {
if !m
.item_list()
.map_or(false, |it| it.syntax().text_range().contains_inclusive(position.offset))
.is_some_and(|it| it.syntax().text_range().contains_inclusive(position.offset))
{
cov_mark::hit!(test_resolve_parent_module_on_module_decl);
module = m.syntax().ancestors().skip(1).find_map(ast::Module::cast);

View file

@ -205,14 +205,14 @@ fn retain_adt_literal_usages(
reference
.name
.as_name_ref()
.map_or(false, |name_ref| is_enum_lit_name_ref(sema, enum_, name_ref))
.is_some_and(|name_ref| is_enum_lit_name_ref(sema, enum_, name_ref))
})
});
usages.references.retain(|_, it| !it.is_empty());
}
Definition::Adt(_) | Definition::Variant(_) => {
refs.for_each(|it| {
it.retain(|reference| reference.name.as_name_ref().map_or(false, is_lit_name_ref))
it.retain(|reference| reference.name.as_name_ref().is_some_and(is_lit_name_ref))
});
usages.references.retain(|_, it| !it.is_empty());
}

View file

@ -227,8 +227,7 @@ fn find_definitions(
ast::NameLike::Name(name)
if name
.syntax()
.parent()
.map_or(false, |it| ast::Rename::can_cast(it.kind()))
.parent().is_some_and(|it| ast::Rename::can_cast(it.kind()))
// FIXME: uncomment this once we resolve to usages to extern crate declarations
// && name
// .syntax()
@ -264,8 +263,7 @@ fn find_definitions(
.and_then(|def| {
// if the name differs from the definitions name it has to be an alias
if def
.name(sema.db)
.map_or(false, |it| !it.eq_ident(name_ref.text().as_str()))
.name(sema.db).is_some_and(|it| !it.eq_ident(name_ref.text().as_str()))
{
Err(format_err!("Renaming aliases is currently unsupported"))
} else {

View file

@ -560,7 +560,7 @@ fn has_runnable_doc_test(attrs: &hir::Attrs) -> bool {
const RUSTDOC_CODE_BLOCK_ATTRIBUTES_RUNNABLE: &[&str] =
&["", "rust", "should_panic", "edition2015", "edition2018", "edition2021"];
docs_from_attrs(attrs).map_or(false, |doc| {
docs_from_attrs(attrs).is_some_and(|doc| {
let mut in_code_block = false;
for line in doc.lines() {

View file

@ -165,7 +165,7 @@ fn signature_help_for_call(
if let Some(callable) = ast::CallableExpr::cast(nodes.next()?) {
let inside_callable = callable
.arg_list()
.map_or(false, |it| it.syntax().text_range().contains(token.text_range().start()));
.is_some_and(|it| it.syntax().text_range().contains(token.text_range().start()));
if inside_callable {
break callable;
}
@ -650,7 +650,7 @@ fn signature_help_for_tuple_pat_ish(
) -> SignatureHelp {
let rest_pat = field_pats.find(|it| matches!(it, ast::Pat::RestPat(_)));
let is_left_of_rest_pat =
rest_pat.map_or(true, |it| token.text_range().start() < it.syntax().text_range().end());
rest_pat.is_none_or(|it| token.text_range().start() < it.syntax().text_range().end());
let commas = pat
.children_with_tokens()

View file

@ -346,7 +346,7 @@ fn traverse(
macro_highlighter = MacroHighlighter::default();
}
Some(item)
if attr_or_derive_item.as_ref().map_or(false, |it| *it.item() == item) =>
if attr_or_derive_item.as_ref().is_some_and(|it| *it.item() == item) =>
{
attr_or_derive_item = None;
}

View file

@ -155,7 +155,7 @@ fn punctuation(
if parent
.as_ref()
.and_then(SyntaxNode::parent)
.map_or(false, |it| it.kind() == MACRO_RULES) =>
.is_some_and(|it| it.kind() == MACRO_RULES) =>
{
return HlOperator::Other.into()
}
@ -193,7 +193,7 @@ fn keyword(
T![for] if parent_matches::<ast::ForExpr>(&token) => h | HlMod::ControlFlow,
T![unsafe] => h | HlMod::Unsafe,
T![const]
if token.parent().map_or(false, |it| {
if token.parent().is_some_and(|it| {
matches!(
it.kind(),
SyntaxKind::CONST
@ -253,7 +253,7 @@ fn highlight_name_ref(
&& !sema
.hir_file_for(name_ref.syntax())
.macro_file()
.map_or(false, |it| it.is_derive_attr_pseudo_expansion(sema.db)) =>
.is_some_and(|it| it.is_derive_attr_pseudo_expansion(sema.db)) =>
{
return HlTag::Symbol(SymbolKind::Attribute).into();
}
@ -275,7 +275,7 @@ fn highlight_name_ref(
}
Definition::Trait(trait_) if trait_.is_unsafe(db) => {
if ast::Impl::for_trait_name_ref(&name_ref)
.map_or(false, |impl_| impl_.unsafe_token().is_some())
.is_some_and(|impl_| impl_.unsafe_token().is_some())
{
h |= HlMod::Unsafe;
}
@ -550,7 +550,7 @@ pub(super) fn highlight_def(
let def_crate = def.krate(db);
let is_from_other_crate = def_crate != Some(krate);
let is_from_builtin_crate = def_crate.map_or(false, |def_crate| def_crate.is_builtin(db));
let is_from_builtin_crate = def_crate.is_some_and(|def_crate| def_crate.is_builtin(db));
let is_builtin = matches!(
def,
Definition::BuiltinType(_) | Definition::BuiltinLifetime(_) | Definition::BuiltinAttr(_)
@ -688,7 +688,7 @@ fn highlight_name_ref_by_syntax(
let h = HlTag::Symbol(SymbolKind::Field);
let is_union = ast::FieldExpr::cast(parent)
.and_then(|field_expr| sema.resolve_field(&field_expr))
.map_or(false, |field| match field {
.is_some_and(|field| match field {
Either::Left(field) => {
matches!(field.parent_def(sema.db), hir::VariantDef::Union(_))
}
@ -764,5 +764,5 @@ fn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[Sy
}
fn parent_matches<N: AstNode>(token: &SyntaxToken) -> bool {
token.parent().map_or(false, |it| N::can_cast(it.kind()))
token.parent().is_some_and(|it| N::can_cast(it.kind()))
}

View file

@ -28,7 +28,7 @@ pub(super) fn ra_fixture(
expanded: &ast::String,
) -> Option<()> {
let active_parameter = ActiveParameter::at_token(sema, expanded.syntax().clone())?;
if !active_parameter.ident().map_or(false, |name| name.text().starts_with("ra_fixture")) {
if !active_parameter.ident().is_some_and(|name| name.text().starts_with("ra_fixture")) {
return None;
}
let value = literal.value().ok()?;
@ -279,9 +279,7 @@ fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::Stri
.descendants_with_tokens()
.filter_map(NodeOrToken::into_token)
.filter_map(ast::String::cast)
.find(|string| {
string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
})
.find(|string| string.text().get(1..string.text().len() - 1) == Some(text))
}
_ => None,
}

View file

@ -174,7 +174,7 @@ fn on_delimited_node_typed(
kinds: &[fn(SyntaxKind) -> bool],
) -> Option<TextEdit> {
let t = reparsed.syntax().token_at_offset(offset).right_biased()?;
if t.prev_token().map_or(false, |t| t.kind().is_any_identifier()) {
if t.prev_token().is_some_and(|t| t.kind().is_any_identifier()) {
return None;
}
let (filter, node) = t

View file

@ -390,7 +390,7 @@ fn expand_var(
let mut span = id;
marker(&mut span);
let wrap_in_parens = !matches!(sub.flat_tokens(), [tt::TokenTree::Leaf(_)])
&& sub.try_into_subtree().map_or(true, |it| {
&& sub.try_into_subtree().is_none_or(|it| {
it.top_subtree().delimiter.kind == tt::DelimiterKind::Invisible
});
if wrap_in_parens {

View file

@ -72,7 +72,7 @@ impl Input {
}
pub(crate) fn is_joint(&self, n: usize) -> bool {
let (idx, b_idx) = self.bit_index(n);
self.joint[idx] & 1 << b_idx != 0
self.joint[idx] & (1 << b_idx) != 0
}
}

View file

@ -85,7 +85,7 @@ impl Output {
}
pub(crate) fn float_split_hack(&mut self, ends_in_dot: bool) {
let e = (Self::SPLIT_EVENT as u32) << Self::TAG_SHIFT
let e = ((Self::SPLIT_EVENT as u32) << Self::TAG_SHIFT)
| ((ends_in_dot as u32) << Self::N_INPUT_TOKEN_SHIFT)
| Self::EVENT_MASK;
self.event.push(e);
@ -99,7 +99,7 @@ impl Output {
}
pub(crate) fn leave_node(&mut self) {
let e = (Self::EXIT_EVENT as u32) << Self::TAG_SHIFT | Self::EVENT_MASK;
let e = ((Self::EXIT_EVENT as u32) << Self::TAG_SHIFT) | Self::EVENT_MASK;
self.event.push(e)
}

View file

@ -450,13 +450,13 @@ impl<'a, S: InternableSpan> Writer<'a, '_, S> {
}),
suffix,
});
idx << 2 | 0b01
(idx << 2) | 0b01
}
tt::Leaf::Punct(punct) => {
let idx = self.punct.len() as u32;
let id = self.token_id_of(punct.span);
self.punct.push(PunctRepr { char: punct.char, spacing: punct.spacing, id });
idx << 2 | 0b10
(idx << 2) | 0b10
}
tt::Leaf::Ident(ident) => {
let idx = self.ident.len() as u32;
@ -469,7 +469,7 @@ impl<'a, S: InternableSpan> Writer<'a, '_, S> {
self.intern(ident.sym.as_str())
};
self.ident.push(IdentRepr { id, text, is_raw: ident.is_raw.yes() });
idx << 2 | 0b11
(idx << 2) | 0b11
}
},
};

View file

@ -46,7 +46,7 @@ impl ManifestPath {
}
pub fn is_rust_manifest(&self) -> bool {
self.file.extension().map_or(false, |ext| ext == "rs")
self.file.extension() == Some("rs")
}
}

View file

@ -301,7 +301,7 @@ impl flags::RustcTests {
continue;
}
}
if p.extension().map_or(true, |x| x != "rs") {
if p.extension().is_none_or(|x| x != "rs") {
continue;
}
if let Err(e) = std::panic::catch_unwind({

View file

@ -448,7 +448,7 @@ impl SymbolGenerator {
.identifier
.description
.get(moniker.identifier.description.len() - 2)
.map_or(false, |descriptor| {
.is_some_and(|descriptor| {
descriptor.desc == MonikerDescriptorKind::Type
&& descriptor.name == "impl"
}),

View file

@ -895,7 +895,7 @@ impl Config {
if let Some(mut json) = change.client_config_change {
tracing::info!("updating config from JSON: {:#}", json);
if !(json.is_null() || json.as_object().map_or(false, |it| it.is_empty())) {
if !(json.is_null() || json.as_object().is_some_and(|it| it.is_empty())) {
let mut json_errors = vec![];
let detached_files = get_field_json::<Vec<Utf8PathBuf>>(
&mut json,

View file

@ -500,7 +500,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
fn rustc_code_description(code: Option<&str>) -> Option<lsp_types::CodeDescription> {
code.filter(|code| {
let mut chars = code.chars();
chars.next().map_or(false, |c| c == 'E')
chars.next() == Some('E')
&& chars.by_ref().take(4).all(|c| c.is_ascii_digit())
&& chars.next().is_none()
})

View file

@ -464,7 +464,7 @@ impl FlycheckActor {
if let Some(manifest_path) = &self.manifest_path {
cmd.arg("--manifest-path");
cmd.arg(manifest_path);
if manifest_path.extension().map_or(false, |ext| ext == "rs") {
if manifest_path.extension() == Some("rs") {
cmd.arg("-Zscript");
}
}

View file

@ -561,8 +561,7 @@ pub(crate) fn inlay_hint(
let text_edits = if snap
.config
.visual_studio_code_version()
// https://github.com/microsoft/vscode/issues/193124
.map_or(true, |version| VersionReq::parse(">=1.86.0").unwrap().matches(version))
.is_none_or(|version| VersionReq::parse(">=1.86.0").unwrap().matches(version))
&& resolve_range_and_hash.is_some()
&& fields_to_resolve.resolve_text_edits
{

View file

@ -751,7 +751,7 @@ impl ast::MatchArmList {
ted::insert_all(position, elements);
fn needs_comma(arm: &ast::MatchArm) -> bool {
arm.expr().map_or(false, |e| !e.is_block_like()) && arm.comma_token().is_none()
arm.expr().is_some_and(|e| !e.is_block_like()) && arm.comma_token().is_none()
}
}
}

View file

@ -393,7 +393,7 @@ impl ast::BlockExpr {
FOR_EXPR | IF_EXPR => parent
.children()
.find(|it| ast::Expr::can_cast(it.kind()))
.map_or(true, |it| it == *self.syntax()),
.is_none_or(|it| it == *self.syntax()),
LET_ELSE | FN | WHILE_EXPR | LOOP_EXPR | CONST_BLOCK_PAT => false,
_ => true,
}

View file

@ -819,7 +819,7 @@ pub fn match_arm_with_guard(
pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
let arms_str = arms.into_iter().fold(String::new(), |mut acc, arm| {
let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
let needs_comma = arm.expr().is_none_or(|it| !it.is_block_like());
let comma = if needs_comma { "," } else { "" };
let arm = arm.syntax();
format_to_acc!(acc, " {arm}{comma}\n")

View file

@ -333,7 +333,7 @@ impl ast::Path {
impl ast::Use {
pub fn is_simple_glob(&self) -> bool {
self.use_tree().map_or(false, |use_tree| {
self.use_tree().is_some_and(|use_tree| {
use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()
})
}
@ -387,7 +387,7 @@ impl ast::UseTreeList {
if let Some((single_subtree,)) = u.use_trees().collect_tuple() {
// We have a single subtree, check whether it is self.
let is_self = single_subtree.path().as_ref().map_or(false, |path| {
let is_self = single_subtree.path().as_ref().is_some_and(|path| {
path.segment().and_then(|seg| seg.self_token()).is_some()
&& path.qualifier().is_none()
});

View file

@ -116,7 +116,7 @@ impl CommentKind {
impl ast::Whitespace {
pub fn spans_multiple_lines(&self) -> bool {
let text = self.text();
text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n'))
text.find('\n').is_some_and(|idx| text[idx + 1..].contains('\n'))
}
}

View file

@ -24,7 +24,7 @@ impl SyntaxEditor {
if last_param
.syntax()
.next_sibling_or_token()
.map_or(false, |it| it.kind() == SyntaxKind::COMMA)
.is_some_and(|it| it.kind() == SyntaxKind::COMMA)
{
self.insert(
Position::after(last_param.syntax()),

View file

@ -116,7 +116,6 @@ fn lookup_in_path(exec: &str) -> Option<Utf8PathBuf> {
let paths = env::var_os("PATH").unwrap_or_default();
env::split_paths(&paths)
.map(|path| path.join(exec))
.map(PathBuf::from)
.map(Utf8PathBuf::try_from)
.filter_map(Result::ok)
.find_map(probe_for_binary)

View file

@ -884,7 +884,7 @@ fn lower_separated_list(
if !matches!(
repeat.as_slice(),
[comma, nt_]
if trailing_sep.map_or(true, |it| comma == &**it) && match (nt, nt_) {
if trailing_sep.is_none_or(|it| comma == &**it) && match (nt, nt_) {
(Either::Left(node), Rule::Node(nt_)) => node == nt_,
(Either::Right(token), Rule::Token(nt_)) => token == nt_,
_ => false,