diff --git a/Cargo.toml b/Cargo.toml index 9564aaeccabc..2547f1ccb991 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,59 +159,25 @@ suspicious = { level = "warn", priority = -1 } result_unit_err = "allow" # We don't expose public APIs that matter like this len_without_is_empty = "allow" -# We currently prefer explicit control flow return over `...?;` statements whose result is unused -question_mark = "allow" # We have macros that rely on this currently enum_variant_names = "allow" # Builder pattern disagrees new_ret_no_self = "allow" ## Following lints should be tackled at some point -bind_instead_of_map = "allow" borrowed_box = "allow" borrow_deref_ref = "allow" -collapsible_if = "allow" -collapsible_match = "allow" -clone_on_copy = "allow" derivable_impls = "allow" derived_hash_with_manual_eq = "allow" -double_parens = "allow" -explicit_auto_deref = "allow" field_reassign_with_default = "allow" forget_non_drop = "allow" format_collect = "allow" -for_kv_map = "allow" -filter_map_bool_then = "allow" -from_str_radix_10 = "allow" -get_first = "allow" -if_same_then_else = "allow" large_enum_variant = "allow" -let_and_return = "allow" -manual_find = "allow" -manual_map = "allow" -map_clone = "allow" -match_like_matches_macro = "allow" -match_single_binding = "allow" -needless_borrow = "allow" needless_doctest_main = "allow" -needless_lifetimes = "allow" -needless_pass_by_value = "allow" -needless_return = "allow" new_without_default = "allow" -nonminimal_bool = "allow" non_canonical_clone_impl = "allow" non_canonical_partial_ord_impl = "allow" -non_minimal_cfg = "allow" -only_used_in_recursion = "allow" -op_ref = "allow" -option_map_unit_fn = "allow" -partialeq_to_none = "allow" -ptr_arg = "allow" -redundant_closure = "allow" -redundant_pattern_matching = "allow" -search_is_some = "allow" self_named_constructors = "allow" -single_match = "allow" skip_while_next = "allow" too_many_arguments = "allow" toplevel_ref_arg = "allow" diff --git a/crates/base-db/src/input.rs b/crates/base-db/src/input.rs index 1fa5f33575e0..852f36ea712a 100644 --- a/crates/base-db/src/input.rs +++ b/crates/base-db/src/input.rs @@ -331,7 +331,7 @@ impl CrateData { return false; } - if let Some(_) = opts.next() { + if opts.next().is_some() { return false; } } diff --git a/crates/hir-def/src/body.rs b/crates/hir-def/src/body.rs index 36d810bbe8ae..81132d738539 100644 --- a/crates/hir-def/src/body.rs +++ b/crates/hir-def/src/body.rs @@ -258,12 +258,12 @@ impl Body { } } Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => { - args.iter().copied().for_each(|p| f(p)); + args.iter().copied().for_each(f); } Pat::Ref { pat, .. } => f(*pat), Pat::Slice { prefix, slice, suffix } => { let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter()); - total_iter.copied().for_each(|p| f(p)); + total_iter.copied().for_each(f); } Pat::Record { args, .. } => { args.iter().for_each(|RecordFieldPat { pat, .. }| f(*pat)); @@ -369,7 +369,7 @@ impl BodySourceMap { } pub fn label_syntax(&self, label: LabelId) -> LabelSource { - self.label_map_back[label].clone() + self.label_map_back[label] } pub fn node_label(&self, node: InFile<&ast::Label>) -> Option { @@ -378,11 +378,11 @@ impl BodySourceMap { } pub fn field_syntax(&self, expr: ExprId) -> FieldSource { - self.field_map_back[&expr].clone() + self.field_map_back[&expr] } pub fn pat_field_syntax(&self, pat: PatId) -> PatFieldSource { - self.pat_field_map_back[&pat].clone() + self.pat_field_map_back[&pat] } pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option { diff --git a/crates/hir-def/src/body/lower.rs b/crates/hir-def/src/body/lower.rs index 4625ca7fc18d..5fc4867bfa67 100644 --- a/crates/hir-def/src/body/lower.rs +++ b/crates/hir-def/src/body/lower.rs @@ -776,11 +776,10 @@ impl ExprCollector<'_> { None => self.collect_expr_opt(e.condition()), }; - let break_expr = - self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr.clone()); + let break_expr = self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr); let if_expr = self.alloc_expr( Expr::If { condition, then_branch: body, else_branch: Some(break_expr) }, - syntax_ptr.clone(), + syntax_ptr, ); self.alloc_expr(Expr::Loop { body: if_expr, label }, syntax_ptr) } @@ -811,19 +810,19 @@ impl ExprCollector<'_> { return self.alloc_expr(Expr::Missing, syntax_ptr); }; let head = self.collect_expr_opt(e.iterable()); - let into_iter_fn_expr = self.alloc_expr(Expr::Path(into_iter_fn), syntax_ptr.clone()); + let into_iter_fn_expr = self.alloc_expr(Expr::Path(into_iter_fn), syntax_ptr); let iterator = self.alloc_expr( Expr::Call { callee: into_iter_fn_expr, args: Box::new([head]), is_assignee_expr: false, }, - syntax_ptr.clone(), + syntax_ptr, ); let none_arm = MatchArm { pat: self.alloc_pat_desugared(Pat::Path(Box::new(option_none))), guard: None, - expr: self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr.clone()), + expr: self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr), }; let some_pat = Pat::TupleStruct { path: Some(Box::new(option_some)), @@ -839,27 +838,25 @@ impl ExprCollector<'_> { }), }; let iter_name = Name::generate_new_name(); - let iter_expr = - self.alloc_expr(Expr::Path(Path::from(iter_name.clone())), syntax_ptr.clone()); + let iter_expr = self.alloc_expr(Expr::Path(Path::from(iter_name.clone())), syntax_ptr); let iter_expr_mut = self.alloc_expr( Expr::Ref { expr: iter_expr, rawness: Rawness::Ref, mutability: Mutability::Mut }, - syntax_ptr.clone(), + syntax_ptr, ); - let iter_next_fn_expr = self.alloc_expr(Expr::Path(iter_next_fn), syntax_ptr.clone()); + let iter_next_fn_expr = self.alloc_expr(Expr::Path(iter_next_fn), syntax_ptr); let iter_next_expr = self.alloc_expr( Expr::Call { callee: iter_next_fn_expr, args: Box::new([iter_expr_mut]), is_assignee_expr: false, }, - syntax_ptr.clone(), + syntax_ptr, ); let loop_inner = self.alloc_expr( Expr::Match { expr: iter_next_expr, arms: Box::new([none_arm, some_arm]) }, - syntax_ptr.clone(), + syntax_ptr, ); - let loop_outer = - self.alloc_expr(Expr::Loop { body: loop_inner, label }, syntax_ptr.clone()); + let loop_outer = self.alloc_expr(Expr::Loop { body: loop_inner, label }, syntax_ptr); let iter_binding = self.alloc_binding(iter_name, BindingAnnotation::Mutable); let iter_pat = self.alloc_pat_desugared(Pat::Bind { id: iter_binding, subpat: None }); self.add_definition_to_binding(iter_binding, iter_pat); @@ -868,7 +865,7 @@ impl ExprCollector<'_> { expr: iterator, arms: Box::new([MatchArm { pat: iter_pat, guard: None, expr: loop_outer }]), }, - syntax_ptr.clone(), + syntax_ptr, ) } @@ -896,10 +893,10 @@ impl ExprCollector<'_> { return self.alloc_expr(Expr::Missing, syntax_ptr); }; let operand = self.collect_expr_opt(e.expr()); - let try_branch = self.alloc_expr(Expr::Path(try_branch), syntax_ptr.clone()); + let try_branch = self.alloc_expr(Expr::Path(try_branch), syntax_ptr); let expr = self.alloc_expr( Expr::Call { callee: try_branch, args: Box::new([operand]), is_assignee_expr: false }, - syntax_ptr.clone(), + syntax_ptr, ); let continue_name = Name::generate_new_name(); let continue_binding = @@ -914,7 +911,7 @@ impl ExprCollector<'_> { ellipsis: None, }), guard: None, - expr: self.alloc_expr(Expr::Path(Path::from(continue_name)), syntax_ptr.clone()), + expr: self.alloc_expr(Expr::Path(Path::from(continue_name)), syntax_ptr), }; let break_name = Name::generate_new_name(); let break_binding = self.alloc_binding(break_name.clone(), BindingAnnotation::Unannotated); @@ -928,18 +925,18 @@ impl ExprCollector<'_> { }), guard: None, expr: { - let it = self.alloc_expr(Expr::Path(Path::from(break_name)), syntax_ptr.clone()); - let callee = self.alloc_expr(Expr::Path(try_from_residual), syntax_ptr.clone()); + let it = self.alloc_expr(Expr::Path(Path::from(break_name)), syntax_ptr); + let callee = self.alloc_expr(Expr::Path(try_from_residual), syntax_ptr); let result = self.alloc_expr( Expr::Call { callee, args: Box::new([it]), is_assignee_expr: false }, - syntax_ptr.clone(), + syntax_ptr, ); self.alloc_expr( match self.current_try_block_label { Some(label) => Expr::Break { expr: Some(result), label: Some(label) }, None => Expr::Return { expr: Some(result) }, }, - syntax_ptr.clone(), + syntax_ptr, ) }, }; @@ -1847,8 +1844,8 @@ impl ExprCollector<'_> { flags as u128, Some(BuiltinUint::U32), ))); - let precision = self.make_count(&precision, argmap); - let width = self.make_count(&width, argmap); + let precision = self.make_count(precision, argmap); + let width = self.make_count(width, argmap); let format_placeholder_new = { let format_placeholder_new = @@ -1994,7 +1991,7 @@ impl ExprCollector<'_> { fn alloc_expr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId { let src = self.expander.in_file(ptr); let id = self.body.exprs.alloc(expr); - self.source_map.expr_map_back.insert(id, src.clone()); + self.source_map.expr_map_back.insert(id, src); self.source_map.expr_map.insert(src, id); id } @@ -2022,7 +2019,7 @@ impl ExprCollector<'_> { fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId { let src = self.expander.in_file(ptr); let id = self.body.pats.alloc(pat); - self.source_map.pat_map_back.insert(id, src.clone()); + self.source_map.pat_map_back.insert(id, src); self.source_map.pat_map.insert(src, id); id } @@ -2037,7 +2034,7 @@ impl ExprCollector<'_> { fn alloc_label(&mut self, label: Label, ptr: LabelPtr) -> LabelId { let src = self.expander.in_file(ptr); let id = self.body.labels.alloc(label); - self.source_map.label_map_back.insert(id, src.clone()); + self.source_map.label_map_back.insert(id, src); self.source_map.label_map.insert(src, id); id } diff --git a/crates/hir-def/src/db.rs b/crates/hir-def/src/db.rs index d25d41c2cfa4..c9789ceb207c 100644 --- a/crates/hir-def/src/db.rs +++ b/crates/hir-def/src/db.rs @@ -259,10 +259,8 @@ fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: CrateId) -> bool { None => continue, }; - let segments = tt.split(|tt| match tt { - tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => true, - _ => false, - }); + let segments = + tt.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',')); for output in segments.skip(1) { match output { [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "no_std" => { diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index 3ff51b9845ce..efda8abf4b8b 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -230,7 +230,7 @@ fn find_path_for_module( } if let value @ Some(_) = - find_in_prelude(ctx.db, &root_def_map, &def_map, ItemInNs::Types(module_id.into()), from) + find_in_prelude(ctx.db, &root_def_map, def_map, ItemInNs::Types(module_id.into()), from) { return value.zip(Some(Stable)); } diff --git a/crates/hir-def/src/generics.rs b/crates/hir-def/src/generics.rs index 6cb9b8448d14..7daae821f88d 100644 --- a/crates/hir-def/src/generics.rs +++ b/crates/hir-def/src/generics.rs @@ -400,9 +400,8 @@ impl GenericParams { params .type_or_consts .iter() - .filter_map(|(idx, param)| { - enabled(idx.into()).then(|| param.clone()) - }) + .filter(|(idx, _)| enabled((*idx).into())) + .map(|(_, param)| param.clone()) .collect() }), lifetimes: all_lifetimes_enabled @@ -411,9 +410,8 @@ impl GenericParams { params .lifetimes .iter() - .filter_map(|(idx, param)| { - enabled(idx.into()).then(|| param.clone()) - }) + .filter(|(idx, _)| enabled((*idx).into())) + .map(|(_, param)| param.clone()) .collect() }), where_predicates: params.where_predicates.clone(), diff --git a/crates/hir-def/src/hir/type_ref.rs b/crates/hir-def/src/hir/type_ref.rs index 17ff736aae44..8db00f9d76e0 100644 --- a/crates/hir-def/src/hir/type_ref.rs +++ b/crates/hir-def/src/hir/type_ref.rs @@ -410,11 +410,7 @@ impl ConstRef { lower_ctx: &LowerCtx<'_>, param: &ast::ConstParam, ) -> Option { - let default = param.default_val(); - match default { - Some(_) => Some(Self::from_const_arg(lower_ctx, default)), - None => None, - } + param.default_val().map(|default| Self::from_const_arg(lower_ctx, Some(default))) } pub fn display<'a>(&'a self, db: &'a dyn ExpandDatabase) -> impl fmt::Display + 'a { diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs index 989bbc7bfb2d..15c127f15628 100644 --- a/crates/hir-def/src/import_map.rs +++ b/crates/hir-def/src/import_map.rs @@ -294,14 +294,14 @@ impl SearchMode { pub fn check(self, query: &str, case_sensitive: bool, candidate: &str) -> bool { match self { SearchMode::Exact if case_sensitive => candidate == query, - SearchMode::Exact => candidate.eq_ignore_ascii_case(&query), + SearchMode::Exact => candidate.eq_ignore_ascii_case(query), SearchMode::Prefix => { query.len() <= candidate.len() && { let prefix = &candidate[..query.len() as usize]; if case_sensitive { prefix == query } else { - prefix.eq_ignore_ascii_case(&query) + prefix.eq_ignore_ascii_case(query) } } } @@ -382,11 +382,11 @@ impl Query { } fn matches_assoc_mode(&self, is_trait_assoc_item: IsTraitAssocItem) -> bool { - match (is_trait_assoc_item, self.assoc_mode) { + !matches!( + (is_trait_assoc_item, self.assoc_mode), (IsTraitAssocItem::Yes, AssocSearchMode::Exclude) - | (IsTraitAssocItem::No, AssocSearchMode::AssocItemsOnly) => false, - _ => true, - } + | (IsTraitAssocItem::No, AssocSearchMode::AssocItemsOnly) + ) } } diff --git a/crates/hir-def/src/lang_item.rs b/crates/hir-def/src/lang_item.rs index dd2e8735573c..60c8baf424db 100644 --- a/crates/hir-def/src/lang_item.rs +++ b/crates/hir-def/src/lang_item.rs @@ -192,7 +192,7 @@ impl LangItems { pub(crate) fn lang_attr(db: &dyn DefDatabase, item: AttrDefId) -> Option { let attrs = db.attrs(item); - attrs.by_key("lang").string_value().and_then(|it| LangItem::from_str(&it)) + attrs.by_key("lang").string_value().and_then(|it| LangItem::from_str(it)) } pub(crate) fn notable_traits_in_deps( diff --git a/crates/hir-def/src/lib.rs b/crates/hir-def/src/lib.rs index bcd1f37bec4a..adf070fe7da9 100644 --- a/crates/hir-def/src/lib.rs +++ b/crates/hir-def/src/lib.rs @@ -733,9 +733,7 @@ pub struct InTypeConstLoc { impl PartialEq for InTypeConstLoc { fn eq(&self, other: &Self) -> bool { - self.id == other.id - && self.owner == other.owner - && &*self.expected_ty == &*other.expected_ty + self.id == other.id && self.owner == other.owner && *self.expected_ty == *other.expected_ty } } diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index 893ad47e241a..1c0f4d4d35ff 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -1406,7 +1406,7 @@ impl DefCollector<'_> { } if let errors @ [_, ..] = &*value { let loc: MacroCallLoc = self.db.lookup_intern_macro_call(macro_call_id); - let diag = DefDiagnostic::macro_expansion_parse_error(module_id, loc.kind, &errors); + let diag = DefDiagnostic::macro_expansion_parse_error(module_id, loc.kind, errors); self.def_map.diagnostics.push(diag); } @@ -2287,7 +2287,7 @@ impl ModCollector<'_, '_> { &MacroCall { ref path, ast_id, expand_to, call_site }: &MacroCall, container: ItemContainerId, ) { - let ast_id = AstIdWithPath::new(self.file_id(), ast_id, ModPath::clone(&path)); + let ast_id = AstIdWithPath::new(self.file_id(), ast_id, ModPath::clone(path)); let db = self.def_collector.db; // FIXME: Immediately expanding in "Case 1" is insufficient since "Case 2" may also define @@ -2371,9 +2371,9 @@ impl ModCollector<'_, '_> { }; for (name, macs) in source.scope.legacy_macros() { - macs.last().map(|&mac| { + if let Some(&mac) = macs.last() { target.scope.define_legacy_macro(name.clone(), mac); - }); + } } } diff --git a/crates/hir-def/src/nameres/tests/macros.rs b/crates/hir-def/src/nameres/tests/macros.rs index 0f6e64016f18..bf89ea711a0a 100644 --- a/crates/hir-def/src/nameres/tests/macros.rs +++ b/crates/hir-def/src/nameres/tests/macros.rs @@ -1348,8 +1348,8 @@ fn proc_attr(a: TokenStream, b: TokenStream) -> TokenStream { a } let actual = def_map .macro_use_prelude - .iter() - .map(|(name, _)| name.display(&db).to_string()) + .keys() + .map(|name| name.display(&db).to_string()) .sorted() .join("\n"); diff --git a/crates/hir-def/src/path.rs b/crates/hir-def/src/path.rs index 215c49d4c2ce..ff5d39cf53df 100644 --- a/crates/hir-def/src/path.rs +++ b/crates/hir-def/src/path.rs @@ -154,7 +154,7 @@ impl Path { pub fn mod_path(&self) -> Option<&ModPath> { match self { - Path::Normal { mod_path, .. } => Some(&mod_path), + Path::Normal { mod_path, .. } => Some(mod_path), Path::LangItem(..) => None, } } @@ -219,13 +219,13 @@ impl<'a> PathSegments<'a> { } pub fn skip(&self, len: usize) -> PathSegments<'a> { PathSegments { - segments: &self.segments.get(len..).unwrap_or(&[]), + segments: self.segments.get(len..).unwrap_or(&[]), generic_args: self.generic_args.and_then(|it| it.get(len..)), } } pub fn take(&self, len: usize) -> PathSegments<'a> { PathSegments { - segments: &self.segments.get(..len).unwrap_or(&self.segments), + segments: self.segments.get(..len).unwrap_or(self.segments), generic_args: self.generic_args.map(|it| it.get(..len).unwrap_or(it)), } } diff --git a/crates/hir-def/src/path/lower.rs b/crates/hir-def/src/path/lower.rs index 39f1b6f1c06d..b3c41a073c60 100644 --- a/crates/hir-def/src/path/lower.rs +++ b/crates/hir-def/src/path/lower.rs @@ -53,7 +53,7 @@ pub(super) fn lower_path(ctx: &LowerCtx<'_>, mut path: ast::Path) -> Option Option { - let within_impl = - self.scopes().find(|scope| matches!(scope, Scope::ImplDefScope(_))).is_some(); + let within_impl = self.scopes().any(|scope| matches!(scope, Scope::ImplDefScope(_))); match visibility { RawVisibility::Module(_, _) => { let (item_map, module) = self.item_scope(); @@ -509,7 +508,7 @@ impl Resolver { .map(|id| ExternCrateDeclData::extern_crate_decl_data_query(db, id).name.clone()) } - pub fn extern_crates_in_scope<'a>(&'a self) -> impl Iterator + 'a { + pub fn extern_crates_in_scope(&self) -> impl Iterator + '_ { self.module_scope .def_map .extern_prelude() diff --git a/crates/hir-ty/src/diagnostics/expr.rs b/crates/hir-ty/src/diagnostics/expr.rs index 6c09a672334a..f1bf162bc6bf 100644 --- a/crates/hir-ty/src/diagnostics/expr.rs +++ b/crates/hir-ty/src/diagnostics/expr.rs @@ -114,34 +114,26 @@ impl ExprValidator { ) { // Check that the number of arguments matches the number of parameters. - // FIXME: Due to shortcomings in the current type system implementation, only emit this - // diagnostic if there are no type mismatches in the containing function. if self.infer.expr_type_mismatches().next().is_some() { - return; - } - - match expr { - Expr::MethodCall { receiver, .. } => { - let (callee, _) = match self.infer.method_resolution(call_id) { - Some(it) => it, - None => return, - }; - - if filter_map_next_checker - .get_or_insert_with(|| { - FilterMapNextChecker::new(&self.owner.resolver(db.upcast()), db) - }) - .check(call_id, receiver, &callee) - .is_some() - { - self.diagnostics.push( - BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { - method_call_expr: call_id, - }, - ); - } + // FIXME: Due to shortcomings in the current type system implementation, only emit + // this diagnostic if there are no type mismatches in the containing function. + } else if let Expr::MethodCall { receiver, .. } = expr { + let (callee, _) = match self.infer.method_resolution(call_id) { + Some(it) => it, + None => return, + }; + + if filter_map_next_checker + .get_or_insert_with(|| { + FilterMapNextChecker::new(&self.owner.resolver(db.upcast()), db) + }) + .check(call_id, receiver, &callee) + .is_some() + { + self.diagnostics.push(BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { + method_call_expr: call_id, + }); } - _ => (), } } diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index a630db05de2f..96c7949e3d62 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -1043,7 +1043,7 @@ impl HirDisplay for Ty { f.start_location_link(t.into()); } write!(f, "Future")?; - if let Some(_) = future_trait { + if future_trait.is_some() { f.end_location_link(); } write!(f, "<")?; @@ -1051,7 +1051,7 @@ impl HirDisplay for Ty { f.start_location_link(t.into()); } write!(f, "Output")?; - if let Some(_) = output { + if output.is_some() { f.end_location_link(); } write!(f, " = ")?; @@ -1520,7 +1520,7 @@ fn write_bounds_like_dyn_trait( } write!(f, "Sized")?; } - if let Some(_) = sized_trait { + if sized_trait.is_some() { f.end_location_link(); } } diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index d6d021340d15..572df8f71374 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -142,13 +142,10 @@ impl HirPlace { mut current_capture: CaptureKind, len: usize, ) -> CaptureKind { - match current_capture { - CaptureKind::ByRef(BorrowKind::Mut { .. }) => { - if self.projections[len..].iter().any(|it| *it == ProjectionElem::Deref) { - current_capture = CaptureKind::ByRef(BorrowKind::Unique); - } + if let CaptureKind::ByRef(BorrowKind::Mut { .. }) = current_capture { + if self.projections[len..].iter().any(|it| *it == ProjectionElem::Deref) { + current_capture = CaptureKind::ByRef(BorrowKind::Unique); } - _ => (), } current_capture } @@ -334,12 +331,10 @@ impl InferenceContext<'_> { match &self.body[tgt_expr] { Expr::Path(p) => { let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); - if let Some(r) = resolver.resolve_path_in_value_ns(self.db.upcast(), p) { - if let ResolveValueResult::ValueNs(v, _) = r { - if let ValueNs::LocalBinding(b) = v { - return Some(HirPlace { local: b, projections: vec![] }); - } - } + if let Some(ResolveValueResult::ValueNs(ValueNs::LocalBinding(b), _)) = + resolver.resolve_path_in_value_ns(self.db.upcast(), p) + { + return Some(HirPlace { local: b, projections: vec![] }); } } Expr::Field { expr, name: _ } => { @@ -1010,7 +1005,7 @@ impl InferenceContext<'_> { let mut deferred_closures = mem::take(&mut self.deferred_closures); let mut dependents_count: FxHashMap = deferred_closures.keys().map(|it| (*it, 0)).collect(); - for (_, deps) in &self.closure_dependencies { + for deps in self.closure_dependencies.values() { for dep in deps { *dependents_count.entry(*dep).or_default() += 1; } diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index bf64795a4bea..842f7bdafe7a 100644 --- a/crates/hir-ty/src/infer/expr.rs +++ b/crates/hir-ty/src/infer/expr.rs @@ -439,7 +439,7 @@ impl InferenceContext<'_> { ty } &Expr::Continue { label } => { - if let None = find_continuable(&mut self.breakables, label) { + if find_continuable(&mut self.breakables, label).is_none() { self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop { expr: tgt_expr, is_break: false, @@ -946,7 +946,7 @@ impl InferenceContext<'_> { derefed_callee: &Ty, adjustments: &mut Vec, callee_ty: &Ty, - params: &Vec, + params: &[Ty], tgt_expr: ExprId, ) { match fn_x { diff --git a/crates/hir-ty/src/layout/tests/closure.rs b/crates/hir-ty/src/layout/tests/closure.rs index dd0e5729b6bd..6c76c6fed062 100644 --- a/crates/hir-ty/src/layout/tests/closure.rs +++ b/crates/hir-ty/src/layout/tests/closure.rs @@ -1,3 +1,6 @@ +#![allow(clippy::match_single_binding)] +#![allow(clippy::no_effect)] + use crate::size_and_align_expr; #[test] diff --git a/crates/hir-ty/src/lib.rs b/crates/hir-ty/src/lib.rs index 61055583fc0d..19052a18b192 100644 --- a/crates/hir-ty/src/lib.rs +++ b/crates/hir-ty/src/lib.rs @@ -414,6 +414,7 @@ impl Hash for FnAbi { } impl FnAbi { + #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> FnAbi { match s { "aapcs-unwind" => FnAbi::AapcsUnwind, diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index 46f5830ef7d7..386a03d93f37 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -1335,7 +1335,7 @@ fn named_associated_type_shorthand_candidates( ), _ => None, }); - if let Some(_) = res { + if res.is_some() { return res; } // Handle `Self::Type` referring to own associated type in trait definitions diff --git a/crates/hir-ty/src/mir/borrowck.rs b/crates/hir-ty/src/mir/borrowck.rs index 186921ae7a48..f7d043fc4e6a 100644 --- a/crates/hir-ty/src/mir/borrowck.rs +++ b/crates/hir-ty/src/mir/borrowck.rs @@ -339,11 +339,8 @@ fn push_mut_span(local: LocalId, span: MirSpan, result: &mut ArenaMap) { - match &mut result[local] { - it @ MutabilityReason::Unused => { - *it = MutabilityReason::Not; - } - _ => (), + if let it @ MutabilityReason::Unused = &mut result[local] { + *it = MutabilityReason::Not; }; } diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index f8e4c6e43d9c..8143dc05c38d 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -272,6 +272,7 @@ const STACK_OFFSET: usize = 1 << 30; const HEAP_OFFSET: usize = 1 << 29; impl Address { + #[allow(clippy::double_parens)] fn from_bytes(it: &[u8]) -> Result { Ok(Address::from_usize(from_bytes!(usize, it))) } @@ -1386,13 +1387,10 @@ impl Evaluator<'_> { | CastKind::PointerExposeAddress | CastKind::PointerFromExposedAddress => { let current_ty = self.operand_ty(operand, locals)?; - let is_signed = match current_ty.kind(Interner) { - TyKind::Scalar(s) => match s { - chalk_ir::Scalar::Int(_) => true, - _ => false, - }, - _ => false, - }; + let is_signed = matches!( + current_ty.kind(Interner), + TyKind::Scalar(chalk_ir::Scalar::Int(_)) + ); let current = pad16(self.eval_operand(operand, locals)?.get(self)?, is_signed); let dest_size = self.size_of_sized(target_ty, locals, "destination of int to int cast")?; @@ -1664,6 +1662,7 @@ impl Evaluator<'_> { }) } + #[allow(clippy::double_parens)] fn allocate_const_in_heap(&mut self, locals: &Locals, konst: &Const) -> Result { let ty = &konst.data(Interner).ty; let chalk_ir::ConstValue::Concrete(c) = &konst.data(Interner).value else { @@ -1842,10 +1841,10 @@ impl Evaluator<'_> { } } let layout = self.layout(ty); - if self.assert_placeholder_ty_is_unused { - if matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _))) { - return Ok(Some((0, 1))); - } + if self.assert_placeholder_ty_is_unused + && matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _))) + { + return Ok(Some((0, 1))); } let layout = layout?; Ok(layout @@ -2218,7 +2217,7 @@ impl Evaluator<'_> { let generic_args = generic_args.clone(); match def { CallableDefId::FunctionId(def) => { - if let Some(_) = self.detect_fn_trait(def) { + if self.detect_fn_trait(def).is_some() { return self.exec_fn_trait( def, args, diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index 169e0e204c5c..99930798e87a 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -288,12 +288,9 @@ impl<'ctx> MirLowerCtx<'ctx> { current: BasicBlockId, ) -> Result> { if !self.has_adjustments(expr_id) { - match &self.body.exprs[expr_id] { - Expr::Literal(l) => { - let ty = self.expr_ty_without_adjust(expr_id); - return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); - } - _ => (), + if let Expr::Literal(l) = &self.body.exprs[expr_id] { + let ty = self.expr_ty_without_adjust(expr_id); + return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); } } let Some((p, current)) = self.lower_expr_as_place(current, expr_id, true)? else { @@ -948,10 +945,11 @@ impl<'ctx> MirLowerCtx<'ctx> { // for binary operator, and use without adjust to simplify our conditions. let lhs_ty = self.expr_ty_without_adjust(*lhs); let rhs_ty = self.expr_ty_without_adjust(*rhs); - if matches!(op, BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) { - if lhs_ty.as_raw_ptr().is_some() && rhs_ty.as_raw_ptr().is_some() { - break 'b true; - } + if matches!(op, BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) + && lhs_ty.as_raw_ptr().is_some() + && rhs_ty.as_raw_ptr().is_some() + { + break 'b true; } let builtin_inequal_impls = matches!( op, diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs index fc51168f99e9..8d157944020d 100644 --- a/crates/hir-ty/src/mir/lower/as_place.rs +++ b/crates/hir-ty/src/mir/lower/as_place.rs @@ -160,57 +160,53 @@ impl MirLowerCtx<'_> { _ => try_rvalue(self), } } - Expr::UnaryOp { expr, op } => match op { - hir_def::hir::UnaryOp::Deref => { - let is_builtin = match self.expr_ty_without_adjust(*expr).kind(Interner) { - TyKind::Ref(..) | TyKind::Raw(..) => true, - TyKind::Adt(id, _) => { - if let Some(lang_item) = self.db.lang_attr(id.0.into()) { - lang_item == LangItem::OwnedBox - } else { - false - } + Expr::UnaryOp { expr, op: hir_def::hir::UnaryOp::Deref } => { + let is_builtin = match self.expr_ty_without_adjust(*expr).kind(Interner) { + TyKind::Ref(..) | TyKind::Raw(..) => true, + TyKind::Adt(id, _) => { + if let Some(lang_item) = self.db.lang_attr(id.0.into()) { + lang_item == LangItem::OwnedBox + } else { + false } - _ => false, + } + _ => false, + }; + if !is_builtin { + let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)? else { + return Ok(None); }; - if !is_builtin { - let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)? - else { - return Ok(None); - }; - return self.lower_overloaded_deref( - current, - p, - self.expr_ty_after_adjustments(*expr), - self.expr_ty_without_adjust(expr_id), - expr_id.into(), - 'b: { - if let Some((f, _)) = self.infer.method_resolution(expr_id) { - if let Some(deref_trait) = - self.resolve_lang_item(LangItem::DerefMut)?.as_trait() + return self.lower_overloaded_deref( + current, + p, + self.expr_ty_after_adjustments(*expr), + self.expr_ty_without_adjust(expr_id), + expr_id.into(), + 'b: { + if let Some((f, _)) = self.infer.method_resolution(expr_id) { + if let Some(deref_trait) = + self.resolve_lang_item(LangItem::DerefMut)?.as_trait() + { + if let Some(deref_fn) = self + .db + .trait_data(deref_trait) + .method_by_name(&name![deref_mut]) { - if let Some(deref_fn) = self - .db - .trait_data(deref_trait) - .method_by_name(&name![deref_mut]) - { - break 'b deref_fn == f; - } + break 'b deref_fn == f; } } - false - }, - ); - } - let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? - else { - return Ok(None); - }; - r = r.project(ProjectionElem::Deref, &mut self.result.projection_store); - Ok(Some((r, current))) + } + false + }, + ); } - _ => try_rvalue(self), - }, + let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else { + return Ok(None); + }; + r = r.project(ProjectionElem::Deref, &mut self.result.projection_store); + Ok(Some((r, current))) + } + Expr::UnaryOp { .. } => try_rvalue(self), Expr::Field { expr, .. } => { let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else { return Ok(None); diff --git a/crates/hir-ty/src/mir/lower/pattern_matching.rs b/crates/hir-ty/src/mir/lower/pattern_matching.rs index ea0beef3c082..65ab12929dd2 100644 --- a/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -331,10 +331,8 @@ impl MirLowerCtx<'_> { break 'b (c, x.1); } } - if let ResolveValueResult::ValueNs(v, _) = pr { - if let ValueNs::ConstId(c) = v { - break 'b (c, Substitution::empty(Interner)); - } + if let ResolveValueResult::ValueNs(ValueNs::ConstId(c), _) = pr { + break 'b (c, Substitution::empty(Interner)); } not_supported!("path in pattern position that is not const or variant") }; diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 392ac56d6150..c50be5f11419 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1439,7 +1439,7 @@ impl Adt { resolver .generic_params() .and_then(|gp| { - (&gp.lifetimes) + gp.lifetimes .iter() // there should only be a single lifetime // but `Arena` requires to use an iterator @@ -1594,12 +1594,11 @@ impl DefWithBody { for diag in source_map.diagnostics() { match diag { BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push( - InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() } - .into(), + InactiveCode { node: *node, cfg: cfg.clone(), opts: opts.clone() }.into(), ), BodyDiagnostic::MacroError { node, message } => acc.push( MacroError { - node: node.clone().map(|it| it.into()), + node: (*node).map(|it| it.into()), precise_location: None, message: message.to_string(), } @@ -1607,7 +1606,7 @@ impl DefWithBody { ), BodyDiagnostic::UnresolvedProcMacro { node, krate } => acc.push( UnresolvedProcMacro { - node: node.clone().map(|it| it.into()), + node: (*node).map(|it| it.into()), precise_location: None, macro_name: None, kind: MacroKind::ProcMacro, @@ -1617,7 +1616,7 @@ impl DefWithBody { ), BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push( UnresolvedMacroCall { - macro_call: node.clone().map(|ast_ptr| ast_ptr.into()), + macro_call: (*node).map(|ast_ptr| ast_ptr.into()), precise_location: None, path: path.clone(), is_bang: true, @@ -1625,10 +1624,10 @@ impl DefWithBody { .into(), ), BodyDiagnostic::UnreachableLabel { node, name } => { - acc.push(UnreachableLabel { node: node.clone(), name: name.clone() }.into()) + acc.push(UnreachableLabel { node: *node, name: name.clone() }.into()) } BodyDiagnostic::UndeclaredLabel { node, name } => { - acc.push(UndeclaredLabel { node: node.clone(), name: name.clone() }.into()) + acc.push(UndeclaredLabel { node: *node, name: name.clone() }.into()) } } } @@ -1715,7 +1714,7 @@ impl DefWithBody { field_with_same_name: field_with_same_name .clone() .map(|ty| Type::new(db, DefWithBodyId::from(self), ty)), - assoc_func_with_same_name: assoc_func_with_same_name.clone(), + assoc_func_with_same_name: *assoc_func_with_same_name, } .into(), ) @@ -1931,8 +1930,7 @@ impl DefWithBody { }, Either::Right(record_pat) => match source_map.pat_syntax(record_pat) { Ok(source_ptr) => { - if let Some(ptr) = source_ptr.value.clone().cast::() - { + if let Some(ptr) = source_ptr.value.cast::() { let root = source_ptr.file_syntax(db.upcast()); let record_pat = ptr.to_node(&root); if record_pat.record_pat_field_list().is_some() { @@ -2083,9 +2081,7 @@ impl Function { } pub fn method_params(self, db: &dyn HirDatabase) -> Option> { - if self.self_param(db).is_none() { - return None; - } + self.self_param(db)?; Some(self.params_without_self(db)) } @@ -2406,10 +2402,10 @@ impl Const { } } if let Ok(s) = mir::render_const_using_debug_impl(db, self.id, &c) { - return Ok(s); + Ok(s) + } else { + Ok(format!("{}", c.display(db))) } - let r = format!("{}", c.display(db)); - return Ok(r); } } @@ -2497,14 +2493,7 @@ impl Trait { db.generic_params(GenericDefId::from(self.id)) .type_or_consts .iter() - .filter(|(_, ty)| match ty { - TypeOrConstParamData::TypeParamData(ty) - if ty.provenance != TypeParamProvenance::TypeParamList => - { - false - } - _ => true, - }) + .filter(|(_, ty)| !matches!(ty, TypeOrConstParamData::TypeParamData(ty) if ty.provenance != TypeParamProvenance::TypeParamList)) .filter(|(_, ty)| !count_required_only || !ty.has_default()) .count() } @@ -3163,7 +3152,7 @@ impl DeriveHelper { .and_then(|it| it.get(self.idx as usize)) .cloned(), } - .unwrap_or_else(|| Name::missing()) + .unwrap_or_else(Name::missing) } } @@ -3874,10 +3863,7 @@ impl Type { } pub fn is_int_or_uint(&self) -> bool { - match self.ty.kind(Interner) { - TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)) => true, - _ => false, - } + matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))) } pub fn is_scalar(&self) -> bool { @@ -4285,10 +4271,8 @@ impl Type { // arg can be either a `Ty` or `constant` if let Some(ty) = arg.ty(Interner) { Some(format_smolstr!("{}", ty.display(db))) - } else if let Some(const_) = arg.constant(Interner) { - Some(format_smolstr!("{}", const_.display(db))) } else { - None + arg.constant(Interner).map(|const_| format_smolstr!("{}", const_.display(db))) } }) } @@ -4300,7 +4284,7 @@ impl Type { ) -> impl Iterator + 'a { // iterate the lifetime self.as_adt() - .and_then(|a| a.lifetime(db).and_then(|lt| Some((<.name).to_smol_str()))) + .and_then(|a| a.lifetime(db).map(|lt| lt.name.to_smol_str())) .into_iter() // add the type and const parameters .chain(self.type_and_const_arguments(db)) @@ -4437,7 +4421,7 @@ impl Type { traits_in_scope, with_local_impls.and_then(|b| b.id.containing_block()).into(), name, - &mut |id| callback(id), + callback, ); } diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index 4267bd4efae4..fdb94a6d5a74 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -659,10 +659,8 @@ impl<'db> SemanticsImpl<'db> { // First expand into attribute invocations let containing_attribute_macro_call = self.with_ctx(|ctx| { token.parent_ancestors().filter_map(ast::Item::cast).find_map(|item| { - if item.attrs().next().is_none() { - // Don't force populate the dyn cache for items that don't have an attribute anyways - return None; - } + // Don't force populate the dyn cache for items that don't have an attribute anyways + item.attrs().next()?; Some(( ctx.item_to_macro_call(InFile::new(file_id, item.clone()))?, item, @@ -1008,9 +1006,7 @@ impl<'db> SemanticsImpl<'db> { // Update `source_ty` for the next adjustment let source = mem::replace(&mut source_ty, target.clone()); - let adjustment = Adjustment { source, target, kind }; - - adjustment + Adjustment { source, target, kind } }) .collect() }) @@ -1255,7 +1251,7 @@ impl<'db> SemanticsImpl<'db> { assert!(root_node.parent().is_none()); let mut cache = self.cache.borrow_mut(); let prev = cache.insert(root_node, file_id); - assert!(prev == None || prev == Some(file_id)) + assert!(prev.is_none() || prev == Some(file_id)) } pub fn assert_contains_node(&self, node: &SyntaxNode) { diff --git a/crates/hir/src/semantics/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs index cb04f98911eb..f60b3749b080 100644 --- a/crates/hir/src/semantics/source_to_def.rs +++ b/crates/hir/src/semantics/source_to_def.rs @@ -142,7 +142,7 @@ impl SourceToDefCtx<'_, '_> { Some(parent_declaration) => self.module_to_def(parent_declaration), None => { let file_id = src.file_id.original_file(self.db.upcast()); - self.file_to_def(file_id).get(0).copied() + self.file_to_def(file_id).first().copied() } }?; @@ -155,7 +155,7 @@ impl SourceToDefCtx<'_, '_> { pub(super) fn source_file_to_def(&self, src: InFile) -> Option { let _p = profile::span("source_file_to_def"); let file_id = src.file_id.original_file(self.db.upcast()); - self.file_to_def(file_id).get(0).copied() + self.file_to_def(file_id).first().copied() } pub(super) fn trait_to_def(&mut self, src: InFile) -> Option { @@ -308,7 +308,7 @@ impl SourceToDefCtx<'_, '_> { pub(super) fn type_param_to_def(&mut self, src: InFile) -> Option { let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into(); let dyn_map = self.cache_for(container, src.file_id); - dyn_map[keys::TYPE_PARAM].get(&src.value).copied().map(|it| TypeParamId::from_unchecked(it)) + dyn_map[keys::TYPE_PARAM].get(&src.value).copied().map(TypeParamId::from_unchecked) } pub(super) fn lifetime_param_to_def( @@ -326,10 +326,7 @@ impl SourceToDefCtx<'_, '_> { ) -> Option { let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into(); let dyn_map = self.cache_for(container, src.file_id); - dyn_map[keys::CONST_PARAM] - .get(&src.value) - .copied() - .map(|it| ConstParamId::from_unchecked(it)) + dyn_map[keys::CONST_PARAM].get(&src.value).copied().map(ConstParamId::from_unchecked) } pub(super) fn generic_param_to_def( @@ -370,7 +367,7 @@ impl SourceToDefCtx<'_, '_> { } } - let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).get(0).copied()?; + let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).first().copied()?; Some(def.into()) } diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 4dc30950da47..fd0a11784215 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -197,10 +197,8 @@ impl SourceAnalyzer { ) -> Option<(Type, Option)> { let pat_id = self.pat_id(pat)?; let infer = self.infer.as_ref()?; - let coerced = infer - .pat_adjustments - .get(&pat_id) - .and_then(|adjusts| adjusts.last().map(|adjust| adjust.clone())); + let coerced = + infer.pat_adjustments.get(&pat_id).and_then(|adjusts| adjusts.last().cloned()); let ty = infer[pat_id].clone(); let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty); Some((mk_ty(ty), coerced.map(mk_ty))) @@ -616,7 +614,7 @@ impl SourceAnalyzer { } None })(); - if let Some(_) = resolved { + if resolved.is_some() { return resolved; } @@ -661,7 +659,7 @@ impl SourceAnalyzer { if let Some(name_ref) = path.as_single_name_ref() { let builtin = BuiltinAttr::by_name(db, self.resolver.krate().into(), &name_ref.text()); - if let Some(_) = builtin { + if builtin.is_some() { return builtin.map(PathResolution::BuiltinAttr); } diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index 45ac03fbf31c..62696d1a9a80 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -198,7 +198,7 @@ pub(super) fn find_importable_node( { ImportAssets::for_method_call(&method_under_caret, &ctx.sema) .zip(Some(method_under_caret.syntax().clone().into())) - } else if let Some(_) = ctx.find_node_at_offset_with_descend::() { + } else if ctx.find_node_at_offset_with_descend::().is_some() { None } else if let Some(pat) = ctx .find_node_at_offset_with_descend::() diff --git a/crates/ide-assists/src/handlers/convert_match_to_let_else.rs b/crates/ide-assists/src/handlers/convert_match_to_let_else.rs index 5657f2dbfb3f..c7f41ffce046 100644 --- a/crates/ide-assists/src/handlers/convert_match_to_let_else.rs +++ b/crates/ide-assists/src/handlers/convert_match_to_let_else.rs @@ -38,7 +38,7 @@ pub(crate) fn convert_match_to_let_else(acc: &mut Assists, ctx: &AssistContext<' let Some(ast::Expr::MatchExpr(initializer)) = let_stmt.initializer() else { return None }; let initializer_expr = initializer.expr()?; - let Some((extracting_arm, diverging_arm)) = find_arms(ctx, &initializer) else { return None }; + let (extracting_arm, diverging_arm) = find_arms(ctx, &initializer)?; if extracting_arm.guard().is_some() { cov_mark::hit!(extracting_arm_has_guard); return None; diff --git a/crates/ide-assists/src/handlers/extract_module.rs b/crates/ide-assists/src/handlers/extract_module.rs index 3bc13bde2652..30c3983dc411 100644 --- a/crates/ide-assists/src/handlers/extract_module.rs +++ b/crates/ide-assists/src/handlers/extract_module.rs @@ -689,27 +689,22 @@ fn does_source_exists_outside_sel_in_same_mod( match def { Definition::Module(x) => { let source = x.definition_source(ctx.db()); - let have_same_parent; - if let Some(ast_module) = &curr_parent_module { + let have_same_parent = if let Some(ast_module) = &curr_parent_module { if let Some(hir_module) = x.parent(ctx.db()) { - have_same_parent = - compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some(); + compare_hir_and_ast_module(ast_module, hir_module, ctx).is_some() } else { let source_file_id = source.file_id.original_file(ctx.db()); - have_same_parent = source_file_id == curr_file_id; + source_file_id == curr_file_id } } else { let source_file_id = source.file_id.original_file(ctx.db()); - have_same_parent = source_file_id == curr_file_id; - } + source_file_id == curr_file_id + }; if have_same_parent { - match source.value { - ModuleSource::Module(module_) => { - source_exists_outside_sel_in_same_mod = - !selection_range.contains_range(module_.syntax().text_range()); - } - _ => {} + if let ModuleSource::Module(module_) = source.value { + source_exists_outside_sel_in_same_mod = + !selection_range.contains_range(module_.syntax().text_range()); } } } diff --git a/crates/ide-assists/src/handlers/generate_delegate_trait.rs b/crates/ide-assists/src/handlers/generate_delegate_trait.rs index efb92936c4e8..154a1f59c722 100644 --- a/crates/ide-assists/src/handlers/generate_delegate_trait.rs +++ b/crates/ide-assists/src/handlers/generate_delegate_trait.rs @@ -236,7 +236,7 @@ fn generate_impl( ctx: &AssistContext<'_>, strukt: &Struct, field_ty: &ast::Type, - field_name: &String, + field_name: &str, delegee: &Delegee, ) -> Option { let delegate: ast::Impl; @@ -270,19 +270,16 @@ fn generate_impl( make::path_from_text(&format!("<{} as {}>", field_ty, delegate.trait_()?)); let delegate_assoc_items = delegate.get_or_create_assoc_item_list(); - match bound_def.assoc_item_list() { - Some(ai) => { - ai.assoc_items() - .filter(|item| matches!(item, AssocItem::MacroCall(_)).not()) - .for_each(|item| { - let assoc = - process_assoc_item(item, qualified_path_type.clone(), field_name); - if let Some(assoc) = assoc { - delegate_assoc_items.add_item(assoc); - } - }); - } - None => {} + if let Some(ai) = bound_def.assoc_item_list() { + ai.assoc_items() + .filter(|item| matches!(item, AssocItem::MacroCall(_)).not()) + .for_each(|item| { + let assoc = + process_assoc_item(item, qualified_path_type.clone(), field_name); + if let Some(assoc) = assoc { + delegate_assoc_items.add_item(assoc); + } + }); }; let target_scope = ctx.sema.scope(strukt.strukt.syntax())?; @@ -512,17 +509,14 @@ fn generate_args_for_impl( // form the substitution list let mut arg_substs = FxHashMap::default(); - match field_ty { - field_ty @ ast::Type::PathType(_) => { - let field_args = field_ty.generic_arg_list().map(|gal| gal.generic_args()); - let self_ty_args = self_ty.generic_arg_list().map(|gal| gal.generic_args()); - if let (Some(field_args), Some(self_ty_args)) = (field_args, self_ty_args) { - self_ty_args.zip(field_args).for_each(|(self_ty_arg, field_arg)| { - arg_substs.entry(self_ty_arg.to_string()).or_insert(field_arg); - }) - } + if let field_ty @ ast::Type::PathType(_) = field_ty { + let field_args = field_ty.generic_arg_list().map(|gal| gal.generic_args()); + let self_ty_args = self_ty.generic_arg_list().map(|gal| gal.generic_args()); + if let (Some(field_args), Some(self_ty_args)) = (field_args, self_ty_args) { + self_ty_args.zip(field_args).for_each(|(self_ty_arg, field_arg)| { + arg_substs.entry(self_ty_arg.to_string()).or_insert(field_arg); + }) } - _ => {} } let args = old_impl_args diff --git a/crates/ide-assists/src/handlers/generate_getter_or_setter.rs b/crates/ide-assists/src/handlers/generate_getter_or_setter.rs index 596e277e0f01..79307fcec5af 100644 --- a/crates/ide-assists/src/handlers/generate_getter_or_setter.rs +++ b/crates/ide-assists/src/handlers/generate_getter_or_setter.rs @@ -377,10 +377,8 @@ fn build_source_change( }; // Insert `$0` only for last getter we generate - if i == record_fields_count - 1 { - if ctx.config.snippet_cap.is_some() { - getter_buf = getter_buf.replacen("fn ", "fn $0", 1); - } + if i == record_fields_count - 1 && ctx.config.snippet_cap.is_some() { + getter_buf = getter_buf.replacen("fn ", "fn $0", 1); } // For first element we do not merge with '\n', as diff --git a/crates/ide-assists/src/handlers/generate_impl.rs b/crates/ide-assists/src/handlers/generate_impl.rs index 9ad14a819d97..d52d778d344a 100644 --- a/crates/ide-assists/src/handlers/generate_impl.rs +++ b/crates/ide-assists/src/handlers/generate_impl.rs @@ -29,7 +29,7 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio let name = nominal.name()?; let target = nominal.syntax().text_range(); - if let Some(_) = ctx.find_node_at_offset::() { + if ctx.find_node_at_offset::().is_some() { return None; } @@ -77,7 +77,7 @@ pub(crate) fn generate_trait_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> let name = nominal.name()?; let target = nominal.syntax().text_range(); - if let Some(_) = ctx.find_node_at_offset::() { + if ctx.find_node_at_offset::().is_some() { return None; } diff --git a/crates/ide-assists/src/handlers/generate_trait_from_impl.rs b/crates/ide-assists/src/handlers/generate_trait_from_impl.rs index 8f61b43cd0f7..a8817436ba1f 100644 --- a/crates/ide-assists/src/handlers/generate_trait_from_impl.rs +++ b/crates/ide-assists/src/handlers/generate_trait_from_impl.rs @@ -181,21 +181,18 @@ fn remove_items_visibility(item: &ast::AssocItem) { } fn strip_body(item: &ast::AssocItem) { - match item { - ast::AssocItem::Fn(f) => { - if let Some(body) = f.body() { - // In constrast to function bodies, we want to see no ws before a semicolon. - // So let's remove them if we see any. - if let Some(prev) = body.syntax().prev_sibling_or_token() { - if prev.kind() == SyntaxKind::WHITESPACE { - ted::remove(prev); - } + if let ast::AssocItem::Fn(f) = item { + if let Some(body) = f.body() { + // In constrast to function bodies, we want to see no ws before a semicolon. + // So let's remove them if we see any. + if let Some(prev) = body.syntax().prev_sibling_or_token() { + if prev.kind() == SyntaxKind::WHITESPACE { + ted::remove(prev); } - - ted::replace(body.syntax(), make::tokens::semicolon()); } + + ted::replace(body.syntax(), make::tokens::semicolon()); } - _ => (), }; } diff --git a/crates/ide-assists/src/handlers/inline_call.rs b/crates/ide-assists/src/handlers/inline_call.rs index bb87b9b6c912..4ba33ada48c7 100644 --- a/crates/ide-assists/src/handlers/inline_call.rs +++ b/crates/ide-assists/src/handlers/inline_call.rs @@ -425,8 +425,8 @@ fn inline( if is_self { let mut this_pat = make::ident_pat(false, false, make::name("this")); let mut expr = expr.clone(); - match pat { - Pat::IdentPat(pat) => match (pat.ref_token(), pat.mut_token()) { + if let Pat::IdentPat(pat) = pat { + match (pat.ref_token(), pat.mut_token()) { // self => let this = obj (None, None) => {} // mut self => let mut this = obj @@ -449,8 +449,7 @@ fn inline( make::expr_ref(expr, true) }; } - }, - _ => {} + } }; let_stmts .push(make::let_stmt(this_pat.into(), ty, Some(expr)).clone_for_update().into()) diff --git a/crates/ide-assists/src/handlers/inline_const_as_literal.rs b/crates/ide-assists/src/handlers/inline_const_as_literal.rs index d5ede9e3c014..18437453761c 100644 --- a/crates/ide-assists/src/handlers/inline_const_as_literal.rs +++ b/crates/ide-assists/src/handlers/inline_const_as_literal.rs @@ -100,7 +100,7 @@ fn validate_type_recursively( } (_, Some(ty)) => match ty.as_builtin() { // `const A: str` is not correct, but `const A: &builtin` is. - Some(builtin) if refed || (!refed && !builtin.is_str()) => Some(()), + Some(builtin) if refed || !builtin.is_str() => Some(()), _ => None, }, _ => None, diff --git a/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs b/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs index 5cc95fd9c0b2..1794c8874399 100644 --- a/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs +++ b/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs @@ -69,7 +69,7 @@ pub(crate) fn replace_turbofish_with_explicit_type( return None; } - if let None = let_stmt.colon_token() { + if let_stmt.colon_token().is_none() { // If there's no colon in a let statement, then there is no explicit type. // let x = fn::<...>(); let ident_range = let_stmt.pat()?.syntax().text_range(); diff --git a/crates/ide-assists/src/handlers/unnecessary_async.rs b/crates/ide-assists/src/handlers/unnecessary_async.rs index 1cfa291a29d8..b2e8c4cf9fd5 100644 --- a/crates/ide-assists/src/handlers/unnecessary_async.rs +++ b/crates/ide-assists/src/handlers/unnecessary_async.rs @@ -37,16 +37,14 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_>) -> O return None; } // Do nothing if the function isn't async. - if let None = function.async_token() { - return None; - } + function.async_token()?; // Do nothing if the function has an `await` expression in its body. if function.body()?.syntax().descendants().find_map(ast::AwaitExpr::cast).is_some() { return None; } // Do nothing if the method is a member of trait. if let Some(impl_) = function.syntax().ancestors().nth(2).and_then(ast::Impl::cast) { - if let Some(_) = impl_.trait_() { + if impl_.trait_().is_some() { return None; } } diff --git a/crates/ide-assists/src/utils/suggest_name.rs b/crates/ide-assists/src/utils/suggest_name.rs index b4c6cbff2a4f..78dee24a6d3a 100644 --- a/crates/ide-assists/src/utils/suggest_name.rs +++ b/crates/ide-assists/src/utils/suggest_name.rs @@ -185,10 +185,10 @@ fn normalize(name: &str) -> Option { } fn is_valid_name(name: &str) -> bool { - match ide_db::syntax_helpers::LexedStr::single_token(name) { - Some((syntax::SyntaxKind::IDENT, _error)) => true, - _ => false, - } + matches!( + ide_db::syntax_helpers::LexedStr::single_token(name), + Some((syntax::SyntaxKind::IDENT, _error)) + ) } fn is_useless_method(method: &ast::MethodCallExpr) -> bool { diff --git a/crates/ide-completion/src/completions/field.rs b/crates/ide-completion/src/completions/field.rs index 870df63b7bf2..53fcb7ca6c02 100644 --- a/crates/ide-completion/src/completions/field.rs +++ b/crates/ide-completion/src/completions/field.rs @@ -11,22 +11,18 @@ pub(crate) fn complete_field_list_tuple_variant( path_ctx: &PathCompletionCtx, ) { if ctx.qualifier_ctx.vis_node.is_some() { - return; - } - match path_ctx { - PathCompletionCtx { - has_macro_bang: false, - qualified: Qualified::No, - parent: None, - has_type_args: false, - .. - } => { - let mut add_keyword = |kw, snippet| acc.add_keyword_snippet(ctx, kw, snippet); - add_keyword("pub(crate)", "pub(crate)"); - add_keyword("pub(super)", "pub(super)"); - add_keyword("pub", "pub"); - } - _ => (), + } else if let PathCompletionCtx { + has_macro_bang: false, + qualified: Qualified::No, + parent: None, + has_type_args: false, + .. + } = path_ctx + { + let mut add_keyword = |kw, snippet| acc.add_keyword_snippet(ctx, kw, snippet); + add_keyword("pub(crate)", "pub(crate)"); + add_keyword("pub(super)", "pub(super)"); + add_keyword("pub", "pub"); } } diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index 3cb090da1ab7..e330430d6b90 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -369,11 +369,10 @@ fn import_on_the_fly_method( }; key(&a.import_path).cmp(&key(&b.import_path)) }) - .for_each(|import| match import.original_item { - ItemInNs::Values(hir::ModuleDef::Function(f)) => { + .for_each(|import| { + if let ItemInNs::Values(hir::ModuleDef::Function(f)) = import.original_item { acc.add_method_with_import(ctx, dot_access, f, import); } - _ => (), }); Some(()) } diff --git a/crates/ide-completion/src/completions/item_list.rs b/crates/ide-completion/src/completions/item_list.rs index 5ea6a49b1ae1..4de15ab75962 100644 --- a/crates/ide-completion/src/completions/item_list.rs +++ b/crates/ide-completion/src/completions/item_list.rs @@ -80,7 +80,7 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let in_trait_impl = matches!(kind, Some(ItemListKind::TraitImpl(_))); let in_inherent_impl = matches!(kind, Some(ItemListKind::Impl)); let no_qualifiers = ctx.qualifier_ctx.vis_node.is_none(); - let in_block = matches!(kind, None); + let in_block = kind.is_none(); if !in_trait_impl { if ctx.qualifier_ctx.unsafe_tok.is_some() { diff --git a/crates/ide-completion/src/context.rs b/crates/ide-completion/src/context.rs index 92aa1da89c41..575f524209c7 100644 --- a/crates/ide-completion/src/context.rs +++ b/crates/ide-completion/src/context.rs @@ -186,14 +186,13 @@ impl TypeLocation { } pub(crate) fn complete_consts(&self) -> bool { - match self { + matches!( + self, TypeLocation::GenericArg { corresponding_param: Some(ast::GenericParam::ConstParam(_)), .. - } => true, - TypeLocation::AssocConstEq => true, - _ => false, - } + } | TypeLocation::AssocConstEq + ) } pub(crate) fn complete_types(&self) -> bool { diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs index 0264931db153..8a4ac00de910 100644 --- a/crates/ide-completion/src/context/analysis.rs +++ b/crates/ide-completion/src/context/analysis.rs @@ -796,8 +796,7 @@ fn classify_name_ref( ast::AssocTypeArg(arg) => { let trait_ = ast::PathSegment::cast(arg.syntax().parent()?.parent()?)?; match sema.resolve_path(&trait_.parent_path().top_path())? { - hir::PathResolution::Def(def) => match def { - hir::ModuleDef::Trait(trait_) => { + hir::PathResolution::Def(hir::ModuleDef::Trait(trait_)) => { let arg_name = arg.name_ref()?; let arg_name = arg_name.text(); let trait_items = trait_.items_with_supertraits(sema.db); @@ -810,8 +809,6 @@ fn classify_name_ref( })?; sema.source(*assoc_ty)?.value.generic_param_list() } - _ => None, - }, _ => None, } }, diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index 9f5c011dc39d..6fd988bfc0fc 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -295,15 +295,12 @@ fn render_resolution_pat( let _p = profile::span("render_resolution"); use hir::ModuleDef::*; - match resolution { - ScopeDef::ModuleDef(Macro(mac)) => { - let ctx = ctx.import_to_add(import_to_add); - return render_macro_pat(ctx, pattern_ctx, local_name, mac); - } - _ => (), + if let ScopeDef::ModuleDef(Macro(mac)) = resolution { + let ctx = ctx.import_to_add(import_to_add); + render_macro_pat(ctx, pattern_ctx, local_name, mac) + } else { + render_resolution_simple_(ctx, &local_name, import_to_add, resolution) } - - render_resolution_simple_(ctx, &local_name, import_to_add, resolution) } fn render_resolution_path( diff --git a/crates/ide-completion/src/render/literal.rs b/crates/ide-completion/src/render/literal.rs index b218502f7f05..f2d67df01d31 100644 --- a/crates/ide-completion/src/render/literal.rs +++ b/crates/ide-completion/src/render/literal.rs @@ -57,11 +57,11 @@ fn render( ) -> Option { let db = completion.db; let mut kind = thing.kind(db); - let should_add_parens = match &path_ctx { - PathCompletionCtx { has_call_parens: true, .. } => false, - PathCompletionCtx { kind: PathKind::Use | PathKind::Type { .. }, .. } => false, - _ => true, - }; + let should_add_parens = !matches!( + path_ctx, + PathCompletionCtx { has_call_parens: true, .. } + | PathCompletionCtx { kind: PathKind::Use | PathKind::Type { .. }, .. } + ); let fields = thing.fields(completion)?; let (qualified_name, short_qualified_name, qualified) = match path { diff --git a/crates/ide-db/src/active_parameter.rs b/crates/ide-db/src/active_parameter.rs index 8d34f01b008b..5780b5a5bb93 100644 --- a/crates/ide-db/src/active_parameter.rs +++ b/crates/ide-db/src/active_parameter.rs @@ -23,7 +23,7 @@ impl ActiveParameter { let idx = active_parameter?; let mut params = signature.params(sema.db); - if !(idx < params.len()) { + if idx >= params.len() { cov_mark::hit!(too_many_arguments); return None; } diff --git a/crates/ide-db/src/symbol_index.rs b/crates/ide-db/src/symbol_index.rs index e8a3c11dced0..7774b0834dca 100644 --- a/crates/ide-db/src/symbol_index.rs +++ b/crates/ide-db/src/symbol_index.rs @@ -383,10 +383,10 @@ impl Query { } fn matches_assoc_mode(&self, is_trait_assoc_item: bool) -> bool { - match (is_trait_assoc_item, self.assoc_mode) { - (true, AssocSearchMode::Exclude) | (false, AssocSearchMode::AssocItemsOnly) => false, - _ => true, - } + !matches!( + (is_trait_assoc_item, self.assoc_mode), + (true, AssocSearchMode::Exclude) | (false, AssocSearchMode::AssocItemsOnly) + ) } } diff --git a/crates/ide-ssr/src/matching.rs b/crates/ide-ssr/src/matching.rs index 66cb14451fbc..060897a68529 100644 --- a/crates/ide-ssr/src/matching.rs +++ b/crates/ide-ssr/src/matching.rs @@ -310,6 +310,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> { Ok(()) } + #[allow(clippy::only_used_in_recursion)] fn check_constraint( &self, constraint: &Constraint, @@ -764,12 +765,7 @@ impl Iterator for PatternIterator { type Item = SyntaxElement; fn next(&mut self) -> Option { - for element in &mut self.iter { - if !element.kind().is_trivia() { - return Some(element); - } - } - None + self.iter.find(|element| !element.kind().is_trivia()) } } diff --git a/crates/ide/src/folding_ranges.rs b/crates/ide/src/folding_ranges.rs index c694d95d537f..b863e144f0ac 100755 --- a/crates/ide/src/folding_ranges.rs +++ b/crates/ide/src/folding_ranges.rs @@ -271,13 +271,13 @@ fn fold_range_for_where_clause(where_clause: ast::WhereClause) -> Option Option { - if let Some(_) = fold_kind(match_arm.expr()?.syntax().kind()) { - return None; - } - if match_arm.expr()?.syntax().text().contains_char('\n') { - return Some(match_arm.expr()?.syntax().text_range()); + if fold_kind(match_arm.expr()?.syntax().kind()).is_some() { + None + } else if match_arm.expr()?.syntax().text().contains_char('\n') { + Some(match_arm.expr()?.syntax().text_range()) + } else { + None } - None } #[cfg(test)] diff --git a/crates/ide/src/inlay_hints/fn_lifetime_fn.rs b/crates/ide/src/inlay_hints/fn_lifetime_fn.rs index eb97f2fb8192..6e5f23bed09f 100644 --- a/crates/ide/src/inlay_hints/fn_lifetime_fn.rs +++ b/crates/ide/src/inlay_hints/fn_lifetime_fn.rs @@ -98,15 +98,13 @@ pub(super) fn hints( }; { let mut potential_lt_refs = potential_lt_refs.iter().filter(|&&(.., is_elided)| is_elided); - if let Some(_) = &self_param { - if let Some(_) = potential_lt_refs.next() { - allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints { - // self can't be used as a lifetime, so no need to check for collisions - "'self".into() - } else { - gen_idx_name() - }); - } + if self_param.is_some() && potential_lt_refs.next().is_some() { + allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints { + // self can't be used as a lifetime, so no need to check for collisions + "'self".into() + } else { + gen_idx_name() + }); } potential_lt_refs.for_each(|(name, ..)| { let name = match name { diff --git a/crates/ide/src/inlay_hints/param_name.rs b/crates/ide/src/inlay_hints/param_name.rs index b4260d82506a..418fc002a8be 100644 --- a/crates/ide/src/inlay_hints/param_name.rs +++ b/crates/ide/src/inlay_hints/param_name.rs @@ -47,7 +47,7 @@ pub(super) fn hints( if let Some(name) = param { if let hir::CallableKind::Function(f) = callable.kind() { // assert the file is cached so we can map out of macros - if let Some(_) = sema.source(f) { + if sema.source(f).is_some() { linked_location = sema.original_range_opt(name.syntax()); } } diff --git a/crates/ide/src/moniker.rs b/crates/ide/src/moniker.rs index 486329dadeda..c49d75b2f811 100644 --- a/crates/ide/src/moniker.rs +++ b/crates/ide/src/moniker.rs @@ -95,11 +95,7 @@ pub struct MonikerIdentifier { impl ToString for MonikerIdentifier { fn to_string(&self) -> String { - match self { - MonikerIdentifier { description, crate_name } => { - format!("{}::{}", crate_name, description.iter().map(|x| &x.name).join("::")) - } - } + format!("{}::{}", self.crate_name, self.description.iter().map(|x| &x.name).join("::")) } } diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs index 307812156e92..3607c486d7d3 100644 --- a/crates/ide/src/syntax_highlighting.rs +++ b/crates/ide/src/syntax_highlighting.rs @@ -282,8 +282,8 @@ fn traverse( inside_attribute = false } - Enter(NodeOrToken::Node(node)) => match ast::Item::cast(node.clone()) { - Some(item) => { + Enter(NodeOrToken::Node(node)) => { + if let Some(item) = ast::Item::cast(node.clone()) { match item { ast::Item::MacroRules(mac) => { macro_highlighter.init(); @@ -324,8 +324,7 @@ fn traverse( } } } - _ => (), - }, + } Leave(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => { match ast::Item::cast(node.clone()) { Some(ast::Item::MacroRules(mac)) => { diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs index a4aed6096943..2108b53861c1 100644 --- a/crates/ide/src/syntax_tree.rs +++ b/crates/ide/src/syntax_tree.rs @@ -52,7 +52,6 @@ fn syntax_tree_for_string(token: &SyntaxToken, text_range: TextRange) -> Option< } } -#[allow(clippy::redundant_locals)] fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option { // Range of the full node let node_range = node.text_range(); @@ -68,8 +67,6 @@ fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option Option".to_string()), is_snippet: true, - }); + }) + } else { + None } - - None } /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }` diff --git a/crates/load-cargo/src/lib.rs b/crates/load-cargo/src/lib.rs index 6c65e6a04fc1..3878e20a2a63 100644 --- a/crates/load-cargo/src/lib.rs +++ b/crates/load-cargo/src/lib.rs @@ -358,7 +358,7 @@ fn expander_to_proc_macro( proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr, }; let expander: sync::Arc = - if dummy_replace.iter().any(|replace| &**replace == name) { + if dummy_replace.iter().any(|replace| **replace == name) { match kind { ProcMacroKind::Attr => sync::Arc::new(IdentityExpander), _ => sync::Arc::new(EmptyExpander), diff --git a/crates/mbe/src/expander/transcriber.rs b/crates/mbe/src/expander/transcriber.rs index b3fb0e8de130..5b7a25408a82 100644 --- a/crates/mbe/src/expander/transcriber.rs +++ b/crates/mbe/src/expander/transcriber.rs @@ -282,9 +282,9 @@ fn expand_subtree( } let res = if ctx.new_meta_vars { - count(ctx, binding, 0, depth.unwrap_or(0)) + count(binding, 0, depth.unwrap_or(0)) } else { - count_old(ctx, binding, 0, *depth) + count_old(binding, 0, *depth) }; let c = match res { @@ -537,7 +537,6 @@ fn fix_up_and_push_path_tt( /// Handles `${count(t, depth)}`. `our_depth` is the recursion depth and `count_depth` is the depth /// defined by the metavar expression. fn count( - ctx: &ExpandCtx<'_, S>, binding: &Binding, depth_curr: usize, depth_max: usize, @@ -547,7 +546,7 @@ fn count( if depth_curr == depth_max { Ok(bs.len()) } else { - bs.iter().map(|b| count(ctx, b, depth_curr + 1, depth_max)).sum() + bs.iter().map(|b| count(b, depth_curr + 1, depth_max)).sum() } } Binding::Empty => Ok(0), @@ -556,16 +555,15 @@ fn count( } fn count_old( - ctx: &ExpandCtx<'_, S>, binding: &Binding, our_depth: usize, count_depth: Option, ) -> Result { match binding { Binding::Nested(bs) => match count_depth { - None => bs.iter().map(|b| count_old(ctx, b, our_depth + 1, None)).sum(), + None => bs.iter().map(|b| count_old(b, our_depth + 1, None)).sum(), Some(0) => Ok(bs.len()), - Some(d) => bs.iter().map(|b| count_old(ctx, b, our_depth + 1, Some(d - 1))).sum(), + Some(d) => bs.iter().map(|b| count_old(b, our_depth + 1, Some(d - 1))).sum(), }, Binding::Empty => Ok(0), Binding::Fragment(_) | Binding::Missing(_) => { diff --git a/crates/parser/src/tests/sourcegen_inline_tests.rs b/crates/parser/src/tests/sourcegen_inline_tests.rs index 54e85c07344b..bd9e188e4d84 100644 --- a/crates/parser/src/tests/sourcegen_inline_tests.rs +++ b/crates/parser/src/tests/sourcegen_inline_tests.rs @@ -22,7 +22,7 @@ fn sourcegen_parser_tests() { } // ok is never actually read, but it needs to be specified to create a Test in existing_tests let existing = existing_tests(&tests_dir, true); - for t in existing.keys().filter(|&t| !tests.contains_key(t)) { + if let Some(t) = existing.keys().find(|&t| !tests.contains_key(t)) { panic!("Test is deleted: {t}"); } diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs index 66da084b49b8..361f8721a4ec 100644 --- a/crates/project-model/src/cargo_workspace.rs +++ b/crates/project-model/src/cargo_workspace.rs @@ -368,7 +368,7 @@ impl CargoWorkspace { name, root: AbsPathBuf::assert(src_path.into()), kind: TargetKind::new(&kind), - is_proc_macro: &*kind == ["proc-macro"], + is_proc_macro: *kind == ["proc-macro"], required_features, }); pkg_data.targets.push(tgt); diff --git a/crates/project-model/src/manifest_path.rs b/crates/project-model/src/manifest_path.rs index 490e1a4ea886..d86e81e7e1ac 100644 --- a/crates/project-model/src/manifest_path.rs +++ b/crates/project-model/src/manifest_path.rs @@ -36,7 +36,7 @@ impl ManifestPath { } pub fn canonicalize(&self) -> ! { - (&**self).canonicalize() + (**self).canonicalize() } } diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 7432f0f7a7ce..04387291907b 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs @@ -17,7 +17,7 @@ use lsp_server::Connection; use rust_analyzer::{cli::flags, config::Config, from_json}; use vfs::AbsPathBuf; -#[cfg(all(feature = "mimalloc"))] +#[cfg(feature = "mimalloc")] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; diff --git a/crates/rust-analyzer/src/cli/rustc_tests.rs b/crates/rust-analyzer/src/cli/rustc_tests.rs index df0c2d497a6f..522eb53128fb 100644 --- a/crates/rust-analyzer/src/cli/rustc_tests.rs +++ b/crates/rust-analyzer/src/cli/rustc_tests.rs @@ -226,7 +226,6 @@ const SUPPORTED_DIAGNOSTICS: &[DiagnosticCode] = &[ ]; impl flags::RustcTests { - #[allow(clippy::redundant_locals)] pub fn run(self) -> Result<()> { let mut tester = Tester::new()?; let walk_dir = WalkDir::new(self.rustc_repo.join("tests/ui")); @@ -246,8 +245,7 @@ impl flags::RustcTests { let p = p.clone(); move || { let _guard = stdx::panic_context::enter(p.display().to_string()); - let tester = tester; - tester.0.test(p); + { tester }.0.test(p); } }) { std::panic::resume_unwind(e); diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs index ce69d612255a..c556fdee504b 100644 --- a/crates/rust-analyzer/src/handlers/notification.rs +++ b/crates/rust-analyzer/src/handlers/notification.rs @@ -36,7 +36,7 @@ pub(crate) fn handle_work_done_progress_cancel( ) -> anyhow::Result<()> { if let lsp_types::NumberOrString::String(s) = ¶ms.token { if let Some(id) = s.strip_prefix("rust-analyzer/flycheck/") { - if let Ok(id) = u32::from_str_radix(id, 10) { + if let Ok(id) = id.parse::() { if let Some(flycheck) = state.flycheck.get(id as usize) { flycheck.cancel(); } diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs index 4b2a1f7e8ef1..f3c2df24d951 100644 --- a/crates/rust-analyzer/src/handlers/request.rs +++ b/crates/rust-analyzer/src/handlers/request.rs @@ -1978,14 +1978,13 @@ fn run_rustfmt( // approach: if the command name contains a path separator, join it with the workspace root. // however, if the path is absolute, joining will result in the absolute path being preserved. // as a fallback, rely on $PATH-based discovery. - let cmd_path = - if cfg!(windows) && command.contains([std::path::MAIN_SEPARATOR, '/']) { - spec.workspace_root.join(cmd).into() - } else if command.contains(std::path::MAIN_SEPARATOR) { - spec.workspace_root.join(cmd).into() - } else { - cmd - }; + let cmd_path = if command.contains(std::path::MAIN_SEPARATOR) + || (cfg!(windows) && command.contains('/')) + { + spec.workspace_root.join(cmd).into() + } else { + cmd + }; process::Command::new(cmd_path) } None => process::Command::new(cmd), diff --git a/crates/rust-analyzer/src/lsp/to_proto.rs b/crates/rust-analyzer/src/lsp/to_proto.rs index d26fe16cbd3a..fe381fbeb3f0 100644 --- a/crates/rust-analyzer/src/lsp/to_proto.rs +++ b/crates/rust-analyzer/src/lsp/to_proto.rs @@ -310,22 +310,20 @@ fn completion_item( set_score(&mut lsp_item, max_relevance, item.relevance); - if config.completion().enable_imports_on_the_fly { - if !item.import_to_add.is_empty() { - let imports: Vec<_> = item - .import_to_add - .into_iter() - .filter_map(|(import_path, import_name)| { - Some(lsp_ext::CompletionImport { - full_import_path: import_path, - imported_name: import_name, - }) + if config.completion().enable_imports_on_the_fly && !item.import_to_add.is_empty() { + let imports: Vec<_> = item + .import_to_add + .into_iter() + .filter_map(|(import_path, import_name)| { + Some(lsp_ext::CompletionImport { + full_import_path: import_path, + imported_name: import_name, }) - .collect(); - if !imports.is_empty() { - let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports }; - lsp_item.data = Some(to_value(data).unwrap()); - } + }) + .collect(); + if !imports.is_empty() { + let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports }; + lsp_item.data = Some(to_value(data).unwrap()); } } diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index f76758569702..0173805d4477 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -579,10 +579,10 @@ impl GlobalState { let path = VfsPath::from(path); // if the file is in mem docs, it's managed by the client via notifications // so only set it if its not in there - if !self.mem_docs.contains(&path) { - if is_changed || vfs.file_id(&path).is_none() { - vfs.set_file_contents(path, contents); - } + if !self.mem_docs.contains(&path) + && (is_changed || vfs.file_id(&path).is_none()) + { + vfs.set_file_contents(path, contents); } } } diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index 83736c65ed3a..969211f44007 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -109,7 +109,7 @@ impl GlobalState { status.health = lsp_ext::Health::Warning; message.push_str("Proc-macros have changed and need to be rebuilt.\n\n"); } - if let Err(_) = self.fetch_build_data_error() { + if self.fetch_build_data_error().is_err() { status.health = lsp_ext::Health::Warning; message.push_str("Failed to run build scripts of some packages.\n\n"); } @@ -173,7 +173,7 @@ impl GlobalState { } } - if let Err(_) = self.fetch_workspace_error() { + if self.fetch_workspace_error().is_err() { status.health = lsp_ext::Health::Error; message.push_str("Failed to load workspaces."); @@ -364,15 +364,13 @@ impl GlobalState { return; }; - if let Err(_) = self.fetch_workspace_error() { - if !self.workspaces.is_empty() { - if *force_reload_crate_graph { - self.recreate_crate_graph(cause); - } - // It only makes sense to switch to a partially broken workspace - // if we don't have any workspace at all yet. - return; + if self.fetch_workspace_error().is_err() && !self.workspaces.is_empty() { + if *force_reload_crate_graph { + self.recreate_crate_graph(cause); } + // It only makes sense to switch to a partially broken workspace + // if we don't have any workspace at all yet. + return; } let workspaces = @@ -454,27 +452,27 @@ impl GlobalState { let files_config = self.config.files(); let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude); - if self.proc_macro_clients.is_empty() || !same_workspaces { - if self.config.expand_proc_macros() { - tracing::info!("Spawning proc-macro servers"); - - self.proc_macro_clients = Arc::from_iter(self.workspaces.iter().map(|ws| { - let path = match self.config.proc_macro_srv() { - Some(path) => path, - None => ws.find_sysroot_proc_macro_srv()?, - }; - - tracing::info!("Using proc-macro server at {path}"); - ProcMacroServer::spawn(path.clone()).map_err(|err| { - tracing::error!( - "Failed to run proc-macro server from path {path}, error: {err:?}", - ); - anyhow::format_err!( - "Failed to run proc-macro server from path {path}, error: {err:?}", - ) - }) - })) - }; + if (self.proc_macro_clients.is_empty() || !same_workspaces) + && self.config.expand_proc_macros() + { + tracing::info!("Spawning proc-macro servers"); + + self.proc_macro_clients = Arc::from_iter(self.workspaces.iter().map(|ws| { + let path = match self.config.proc_macro_srv() { + Some(path) => path, + None => ws.find_sysroot_proc_macro_srv()?, + }; + + tracing::info!("Using proc-macro server at {path}"); + ProcMacroServer::spawn(path.clone()).map_err(|err| { + tracing::error!( + "Failed to run proc-macro server from path {path}, error: {err:?}", + ); + anyhow::format_err!( + "Failed to run proc-macro server from path {path}, error: {err:?}", + ) + }) + })) } let watch = match files_config.watcher { @@ -569,10 +567,11 @@ impl GlobalState { for ws in &self.fetch_build_data_queue.last_op_result().1 { match ws { - Ok(data) => match data.error() { - Some(stderr) => stdx::format_to!(buf, "{:#}\n", stderr), - _ => (), - }, + Ok(data) => { + if let Some(stderr) = data.error() { + stdx::format_to!(buf, "{:#}\n", stderr) + } + } // io errors Err(err) => stdx::format_to!(buf, "{:#}\n", err), } diff --git a/crates/rust-analyzer/tests/slow-tests/tidy.rs b/crates/rust-analyzer/tests/slow-tests/tidy.rs index dba336ea7d6d..db192cf8fe53 100644 --- a/crates/rust-analyzer/tests/slow-tests/tidy.rs +++ b/crates/rust-analyzer/tests/slow-tests/tidy.rs @@ -379,7 +379,7 @@ impl TidyDocs { ) } - for path in self.contains_fixme { + if let Some(path) = self.contains_fixme.first() { panic!("FIXME doc in a fully-documented crate: {}", path.display()) } } diff --git a/lib/line-index/src/lib.rs b/lib/line-index/src/lib.rs index 1614504f80a3..1ab62e99235f 100644 --- a/lib/line-index/src/lib.rs +++ b/lib/line-index/src/lib.rs @@ -339,7 +339,7 @@ unsafe fn analyze_source_file_sse2( } #[target_feature(enable = "neon")] -#[cfg(any(target_arch = "aarch64"))] +#[cfg(target_arch = "aarch64")] #[inline] // See https://community.arm.com/arm-community-blogs/b/infrastructure-solutions-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon // @@ -354,7 +354,7 @@ unsafe fn move_mask(v: std::arch::aarch64::uint8x16_t) -> u64 { } #[target_feature(enable = "neon")] -#[cfg(any(target_arch = "aarch64"))] +#[cfg(target_arch = "aarch64")] unsafe fn analyze_source_file_neon( src: &str, lines: &mut Vec,