From 8ce30264c8201b616b43d10b54d0ea694e2840ef Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 31 Jul 2025 10:30:22 +0200 Subject: [PATCH] `cargo clippy --fix` --- crates/cfg/src/cfg_expr.rs | 8 +- crates/hir-def/src/attr.rs | 8 +- crates/hir-def/src/expr_store/lower.rs | 39 +++-- crates/hir-def/src/expr_store/lower/asm.rs | 8 +- crates/hir-def/src/expr_store/lower/path.rs | 21 +-- crates/hir-def/src/expr_store/pretty.rs | 12 +- crates/hir-def/src/find_path.rs | 72 ++++---- crates/hir-def/src/item_scope.rs | 9 +- crates/hir-def/src/item_tree/lower.rs | 23 ++- crates/hir-def/src/lang_item.rs | 8 +- .../hir-def/src/macro_expansion_tests/mod.rs | 64 ++++---- crates/hir-def/src/nameres/collector.rs | 154 ++++++++---------- crates/hir-def/src/resolver.rs | 94 +++++------ crates/hir-expand/src/builtin/fn_macro.rs | 11 +- crates/hir-expand/src/cfg_process.rs | 8 +- crates/hir-expand/src/fixup.rs | 10 +- crates/hir-expand/src/lib.rs | 22 ++- crates/hir-expand/src/mod_path.rs | 21 +-- crates/hir-ty/src/autoderef.rs | 9 +- crates/hir-ty/src/builder.rs | 10 +- crates/hir-ty/src/chalk_db.rs | 64 ++++---- crates/hir-ty/src/consteval.rs | 8 +- crates/hir-ty/src/diagnostics/decl_check.rs | 8 +- crates/hir-ty/src/diagnostics/expr.rs | 18 +- crates/hir-ty/src/diagnostics/match_check.rs | 8 +- crates/hir-ty/src/diagnostics/unsafe_check.rs | 17 +- crates/hir-ty/src/display.rs | 123 +++++++------- crates/hir-ty/src/dyn_compatibility.rs | 25 ++- crates/hir-ty/src/infer.rs | 47 +++--- crates/hir-ty/src/infer/cast.rs | 37 ++--- crates/hir-ty/src/infer/closure.rs | 154 ++++++++---------- crates/hir-ty/src/infer/coerce.rs | 46 +++--- crates/hir-ty/src/infer/expr.rs | 75 ++++----- crates/hir-ty/src/infer/mutability.rs | 119 ++++++-------- crates/hir-ty/src/infer/pat.rs | 31 ++-- crates/hir-ty/src/lower.rs | 8 +- crates/hir-ty/src/lower/path.rs | 120 +++++++------- crates/hir-ty/src/method_resolution.rs | 38 ++--- crates/hir-ty/src/mir/borrowck.rs | 5 +- crates/hir-ty/src/mir/eval.rs | 73 ++++----- crates/hir-ty/src/mir/eval/shim.rs | 76 +++++---- crates/hir-ty/src/mir/eval/shim/simd.rs | 11 +- crates/hir-ty/src/mir/lower.rs | 60 +++---- crates/hir-ty/src/mir/lower/as_place.rs | 17 +- .../hir-ty/src/mir/lower/pattern_matching.rs | 49 +++--- crates/hir-ty/src/traits.rs | 7 +- crates/hir-ty/src/utils.rs | 14 +- crates/hir/src/diagnostics.rs | 14 +- crates/hir/src/lib.rs | 80 +++++---- crates/hir/src/semantics.rs | 93 +++++------ crates/hir/src/source_analyzer.rs | 83 +++++----- crates/hir/src/term_search.rs | 16 +- crates/hir/src/term_search/expr.rs | 8 +- .../src/handlers/add_lifetime_to_type.rs | 24 +-- .../src/handlers/add_missing_impl_members.rs | 14 +- .../src/handlers/apply_demorgan.rs | 8 +- .../src/handlers/convert_bool_then.rs | 23 ++- .../src/handlers/convert_closure_to_fn.rs | 57 ++++--- .../src/handlers/convert_from_to_tryfrom.rs | 19 +-- .../src/handlers/convert_into_to_from.rs | 8 +- .../convert_tuple_return_type_to_struct.rs | 8 +- .../convert_tuple_struct_to_named_struct.rs | 2 +- ...ert_two_arm_bool_match_to_matches_macro.rs | 8 +- .../src/handlers/desugar_try_expr.rs | 130 +++++++-------- .../src/handlers/expand_glob_import.rs | 10 +- .../src/handlers/extract_function.rs | 101 ++++++------ .../src/handlers/extract_module.rs | 81 +++++---- .../extract_struct_from_enum_variant.rs | 12 +- .../src/handlers/extract_type_alias.rs | 42 +++-- .../src/handlers/extract_variable.rs | 15 +- .../generate_documentation_template.rs | 18 +- .../src/handlers/generate_fn_type_alias.rs | 8 +- .../src/handlers/generate_function.rs | 8 +- .../src/handlers/generate_getter_or_setter.rs | 11 +- .../ide-assists/src/handlers/generate_impl.rs | 10 +- .../src/handlers/generate_trait_from_impl.rs | 22 +-- .../ide-assists/src/handlers/inline_call.rs | 49 +++--- .../src/handlers/move_const_to_impl.rs | 8 +- .../src/handlers/pull_assignment_up.rs | 16 +- crates/ide-assists/src/handlers/raw_string.rs | 18 +- .../replace_qualified_name_with_use.rs | 8 +- .../src/handlers/unnecessary_async.rs | 8 +- .../src/handlers/unwrap_return_type.rs | 24 +-- .../ide-assists/src/handlers/unwrap_tuple.rs | 8 +- .../src/handlers/wrap_return_type.rs | 40 ++--- .../src/handlers/wrap_unwrap_cfg_attr.rs | 22 ++- crates/ide-assists/src/utils.rs | 48 +++--- crates/ide-completion/src/completions.rs | 17 +- crates/ide-completion/src/completions/dot.rs | 11 +- .../src/completions/fn_param.rs | 8 +- .../src/completions/item_list/trait_impl.rs | 92 +++++------ crates/ide-completion/src/completions/mod_.rs | 17 +- .../ide-completion/src/completions/pattern.rs | 21 ++- .../ide-completion/src/completions/postfix.rs | 153 ++++++++--------- crates/ide-completion/src/completions/use_.rs | 8 +- crates/ide-completion/src/completions/vis.rs | 10 +- crates/ide-completion/src/context/analysis.rs | 140 +++++++--------- crates/ide-completion/src/item.rs | 8 +- crates/ide-completion/src/lib.rs | 14 +- crates/ide-completion/src/render.rs | 108 ++++++------ crates/ide-completion/src/render/const_.rs | 8 +- crates/ide-completion/src/render/function.rs | 34 ++-- .../ide-completion/src/render/type_alias.rs | 8 +- crates/ide-db/src/defs.rs | 64 ++++---- crates/ide-db/src/helpers.rs | 10 +- crates/ide-db/src/imports/insert_use.rs | 45 +++-- crates/ide-db/src/path_transform.rs | 100 ++++++------ crates/ide-db/src/rename.rs | 22 +-- crates/ide-db/src/search.rs | 83 +++++----- crates/ide-db/src/symbol_index.rs | 16 +- .../src/syntax_helpers/format_string.rs | 10 +- crates/ide-db/src/syntax_helpers/node_ext.rs | 23 ++- crates/ide-db/src/use_trivial_constructor.rs | 20 +-- .../src/handlers/json_is_not_rust.rs | 50 +++--- .../src/handlers/missing_fields.rs | 11 +- .../src/handlers/mutability_errors.rs | 24 +-- .../src/handlers/unlinked_file.rs | 14 +- crates/ide-diagnostics/src/lib.rs | 54 +++--- crates/ide-ssr/src/lib.rs | 21 ++- crates/ide-ssr/src/matching.rs | 101 ++++++------ crates/ide-ssr/src/replacing.rs | 28 ++-- crates/ide-ssr/src/resolving.rs | 61 +++---- crates/ide-ssr/src/search.rs | 27 ++- crates/ide/src/annotations.rs | 8 +- crates/ide/src/expand_macro.rs | 16 +- crates/ide/src/extend_selection.rs | 54 +++--- crates/ide/src/folding_ranges.rs | 88 +++++----- crates/ide/src/goto_definition.rs | 28 ++-- crates/ide/src/highlight_related.rs | 45 +++-- crates/ide/src/hover.rs | 13 +- crates/ide/src/hover/render.rs | 116 ++++++------- crates/ide/src/inlay_hints.rs | 12 +- crates/ide/src/inlay_hints/adjustment.rs | 8 +- crates/ide/src/inlay_hints/bind_pat.rs | 8 +- crates/ide/src/inlay_hints/chaining.rs | 11 +- crates/ide/src/inlay_hints/closing_brace.rs | 10 +- crates/ide/src/inlay_hints/closure_ret.rs | 8 +- crates/ide/src/inlay_hints/extern_block.rs | 8 +- crates/ide/src/inlay_hints/generic_param.rs | 8 +- crates/ide/src/inlay_hints/implicit_static.rs | 43 ++--- crates/ide/src/inlay_hints/lifetime.rs | 50 +++--- crates/ide/src/inlay_hints/param_name.rs | 8 +- crates/ide/src/join_lines.rs | 26 +-- crates/ide/src/parent_module.rs | 11 +- crates/ide/src/rename.rs | 8 +- crates/ide/src/runnables.rs | 34 ++-- crates/ide/src/signature_help.rs | 19 +-- crates/ide/src/static_index.rs | 8 +- .../ide/src/syntax_highlighting/highlight.rs | 39 +++-- crates/load-cargo/src/lib.rs | 8 +- crates/mbe/src/benchmark.rs | 32 ++-- crates/mbe/src/expander/matcher.rs | 12 +- crates/parser/src/grammar/expressions.rs | 69 ++++---- crates/parser/src/input.rs | 2 +- crates/parser/src/shortcuts.rs | 8 +- crates/query-group-macro/src/lib.rs | 18 +- crates/rust-analyzer/src/bin/main.rs | 12 +- .../rust-analyzer/src/cli/analysis_stats.rs | 111 ++++++------- .../rust-analyzer/src/cli/progress_report.rs | 10 +- crates/rust-analyzer/src/cli/rustc_tests.rs | 8 +- crates/rust-analyzer/src/config.rs | 21 ++- .../src/config/patch_old_style.rs | 24 +-- .../rust-analyzer/src/diagnostics/to_proto.rs | 14 +- crates/rust-analyzer/src/flycheck.rs | 11 +- crates/rust-analyzer/src/global_state.rs | 26 +-- crates/rust-analyzer/src/handlers/dispatch.rs | 8 +- .../src/handlers/notification.rs | 37 ++--- crates/rust-analyzer/src/handlers/request.rs | 150 ++++++++--------- crates/rust-analyzer/src/main_loop.rs | 64 ++++---- crates/rust-analyzer/src/reload.rs | 14 +- crates/span/src/map.rs | 14 +- crates/syntax-bridge/src/lib.rs | 22 +-- .../src/prettify_macro_expansion.rs | 9 +- crates/syntax-bridge/src/tests.rs | 9 +- crates/syntax-bridge/src/to_parser_input.rs | 20 +-- crates/syntax/src/ast/edit.rs | 24 +-- crates/syntax/src/ast/edit_in_place.rs | 41 +++-- crates/syntax/src/ast/prec.rs | 24 +-- crates/syntax/src/syntax_editor.rs | 8 +- crates/syntax/src/ted.rs | 42 ++--- crates/syntax/src/validation.rs | 92 +++++------ crates/test-fixture/src/lib.rs | 12 +- crates/tt/src/lib.rs | 16 +- crates/vfs-notify/src/lib.rs | 85 +++++----- xtask/src/codegen.rs | 10 +- xtask/src/publish/notes.rs | 138 ++++++++-------- 186 files changed, 3073 insertions(+), 3331 deletions(-) diff --git a/crates/cfg/src/cfg_expr.rs b/crates/cfg/src/cfg_expr.rs index aed00aa9fc44..f83c21eb8d64 100644 --- a/crates/cfg/src/cfg_expr.rs +++ b/crates/cfg/src/cfg_expr.rs @@ -134,10 +134,10 @@ fn next_cfg_expr(it: &mut tt::iter::TtIter<'_, S>) -> Option { }; // Eat comma separator - if let Some(TtElement::Leaf(tt::Leaf::Punct(punct))) = it.peek() { - if punct.char == ',' { - it.next(); - } + if let Some(TtElement::Leaf(tt::Leaf::Punct(punct))) = it.peek() + && punct.char == ',' + { + it.next(); } Some(ret) } diff --git a/crates/hir-def/src/attr.rs b/crates/hir-def/src/attr.rs index b509e69b0d37..53250510f875 100644 --- a/crates/hir-def/src/attr.rs +++ b/crates/hir-def/src/attr.rs @@ -377,10 +377,10 @@ fn parse_repr_tt(tt: &crate::tt::TopSubtree) -> Option { let mut align = None; if let Some(TtElement::Subtree(_, mut tt_iter)) = tts.peek() { tts.next(); - if let Some(TtElement::Leaf(tt::Leaf::Literal(lit))) = tt_iter.next() { - if let Ok(a) = lit.symbol.as_str().parse() { - align = Align::from_bytes(a).ok(); - } + if let Some(TtElement::Leaf(tt::Leaf::Literal(lit))) = tt_iter.next() + && let Ok(a) = lit.symbol.as_str().parse() + { + align = Align::from_bytes(a).ok(); } } ReprOptions { align, ..Default::default() } diff --git a/crates/hir-def/src/expr_store/lower.rs b/crates/hir-def/src/expr_store/lower.rs index abd1382801dd..3b9281ffb9c1 100644 --- a/crates/hir-def/src/expr_store/lower.rs +++ b/crates/hir-def/src/expr_store/lower.rs @@ -1487,13 +1487,13 @@ impl ExprCollector<'_> { ast::Expr::UnderscoreExpr(_) => self.alloc_pat_from_expr(Pat::Wild, syntax_ptr), ast::Expr::ParenExpr(e) => { // We special-case `(..)` for consistency with patterns. - if let Some(ast::Expr::RangeExpr(range)) = e.expr() { - if range.is_range_full() { - return Some(self.alloc_pat_from_expr( - Pat::Tuple { args: Box::default(), ellipsis: Some(0) }, - syntax_ptr, - )); - } + if let Some(ast::Expr::RangeExpr(range)) = e.expr() + && range.is_range_full() + { + return Some(self.alloc_pat_from_expr( + Pat::Tuple { args: Box::default(), ellipsis: Some(0) }, + syntax_ptr, + )); } return e.expr().and_then(|expr| self.maybe_collect_expr_as_pat(&expr)); } @@ -2569,19 +2569,18 @@ impl ExprCollector<'_> { } } RibKind::MacroDef(macro_id) => { - if let Some((parent_ctx, label_macro_id)) = hygiene_info { - if label_macro_id == **macro_id { - // A macro is allowed to refer to labels from before its declaration. - // Therefore, if we got to the rib of its declaration, give up its hygiene - // and use its parent expansion. - - hygiene_id = - HygieneId::new(parent_ctx.opaque_and_semitransparent(self.db)); - hygiene_info = parent_ctx.outer_expn(self.db).map(|expansion| { - let expansion = self.db.lookup_intern_macro_call(expansion.into()); - (parent_ctx.parent(self.db), expansion.def) - }); - } + if let Some((parent_ctx, label_macro_id)) = hygiene_info + && label_macro_id == **macro_id + { + // A macro is allowed to refer to labels from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + + hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(self.db)); + hygiene_info = parent_ctx.outer_expn(self.db).map(|expansion| { + let expansion = self.db.lookup_intern_macro_call(expansion.into()); + (parent_ctx.parent(self.db), expansion.def) + }); } } _ => {} diff --git a/crates/hir-def/src/expr_store/lower/asm.rs b/crates/hir-def/src/expr_store/lower/asm.rs index 3bc4afb5c8ac..230d1c934636 100644 --- a/crates/hir-def/src/expr_store/lower/asm.rs +++ b/crates/hir-def/src/expr_store/lower/asm.rs @@ -259,10 +259,10 @@ impl ExprCollector<'_> { } }; - if let Some(operand_idx) = operand_idx { - if let Some(position_span) = to_span(arg.position_span) { - mappings.push((position_span, operand_idx)); - } + if let Some(operand_idx) = operand_idx + && let Some(position_span) = to_span(arg.position_span) + { + mappings.push((position_span, operand_idx)); } } } diff --git a/crates/hir-def/src/expr_store/lower/path.rs b/crates/hir-def/src/expr_store/lower/path.rs index be006c98a582..579465e10f93 100644 --- a/crates/hir-def/src/expr_store/lower/path.rs +++ b/crates/hir-def/src/expr_store/lower/path.rs @@ -211,16 +211,17 @@ pub(super) fn lower_path( // Basically, even in rustc it is quite hacky: // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456 // We follow what it did anyway :) - if segments.len() == 1 && kind == PathKind::Plain { - if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - let syn_ctxt = collector.expander.ctx_for_range(path.segment()?.syntax().text_range()); - if let Some(macro_call_id) = syn_ctxt.outer_expn(collector.db) { - if collector.db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner { - kind = match resolve_crate_root(collector.db, syn_ctxt) { - Some(crate_root) => PathKind::DollarCrate(crate_root), - None => PathKind::Crate, - } - } + if segments.len() == 1 + && kind == PathKind::Plain + && let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + let syn_ctxt = collector.expander.ctx_for_range(path.segment()?.syntax().text_range()); + if let Some(macro_call_id) = syn_ctxt.outer_expn(collector.db) + && collector.db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner + { + kind = match resolve_crate_root(collector.db, syn_ctxt) { + Some(crate_root) => PathKind::DollarCrate(crate_root), + None => PathKind::Crate, } } } diff --git a/crates/hir-def/src/expr_store/pretty.rs b/crates/hir-def/src/expr_store/pretty.rs index f1b011333d94..b81dcc1fe96d 100644 --- a/crates/hir-def/src/expr_store/pretty.rs +++ b/crates/hir-def/src/expr_store/pretty.rs @@ -900,14 +900,12 @@ impl Printer<'_> { let field_name = arg.name.display(self.db, edition).to_string(); let mut same_name = false; - if let Pat::Bind { id, subpat: None } = &self.store[arg.pat] { - if let Binding { name, mode: BindingAnnotation::Unannotated, .. } = + if let Pat::Bind { id, subpat: None } = &self.store[arg.pat] + && let Binding { name, mode: BindingAnnotation::Unannotated, .. } = &self.store.assert_expr_only().bindings[*id] - { - if name.as_str() == field_name { - same_name = true; - } - } + && name.as_str() == field_name + { + same_name = true; } w!(p, "{}", field_name); diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index dccfff002f23..faa0ef8ceec7 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -107,11 +107,11 @@ struct FindPathCtx<'db> { /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Option { // - if the item is a module, jump straight to module search - if !ctx.is_std_item { - if let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item { - return find_path_for_module(ctx, &mut FxHashSet::default(), module_id, true, max_len) - .map(|choice| choice.path); - } + if !ctx.is_std_item + && let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item + { + return find_path_for_module(ctx, &mut FxHashSet::default(), module_id, true, max_len) + .map(|choice| choice.path); } let may_be_in_scope = match ctx.prefix { @@ -226,15 +226,15 @@ fn find_path_for_module( } // - if the module can be referenced as self, super or crate, do that - if let Some(kind) = is_kw_kind_relative_to_from(ctx.from_def_map, module_id, ctx.from) { - if ctx.prefix != PrefixKind::ByCrate || kind == PathKind::Crate { - return Some(Choice { - path: ModPath::from_segments(kind, None), - path_text_len: path_kind_len(kind), - stability: Stable, - prefer_due_to_prelude: false, - }); - } + if let Some(kind) = is_kw_kind_relative_to_from(ctx.from_def_map, module_id, ctx.from) + && (ctx.prefix != PrefixKind::ByCrate || kind == PathKind::Crate) + { + return Some(Choice { + path: ModPath::from_segments(kind, None), + path_text_len: path_kind_len(kind), + stability: Stable, + prefer_due_to_prelude: false, + }); } // - if the module is in the prelude, return it by that path @@ -604,29 +604,29 @@ fn find_local_import_locations( &def_map[module.local_id] }; - if let Some((name, vis, declared)) = data.scope.name_of(item) { - if vis.is_visible_from(db, from) { - let is_pub_or_explicit = match vis { - Visibility::Module(_, VisibilityExplicitness::Explicit) => { - cov_mark::hit!(explicit_private_imports); - true - } - Visibility::Module(_, VisibilityExplicitness::Implicit) => { - cov_mark::hit!(discount_private_imports); - false - } - Visibility::PubCrate(_) => true, - Visibility::Public => true, - }; - - // Ignore private imports unless they are explicit. these could be used if we are - // in a submodule of this module, but that's usually not - // what the user wants; and if this module can import - // the item and we're a submodule of it, so can we. - // Also this keeps the cached data smaller. - if declared || is_pub_or_explicit { - cb(visited_modules, name, module); + if let Some((name, vis, declared)) = data.scope.name_of(item) + && vis.is_visible_from(db, from) + { + let is_pub_or_explicit = match vis { + Visibility::Module(_, VisibilityExplicitness::Explicit) => { + cov_mark::hit!(explicit_private_imports); + true } + Visibility::Module(_, VisibilityExplicitness::Implicit) => { + cov_mark::hit!(discount_private_imports); + false + } + Visibility::PubCrate(_) => true, + Visibility::Public => true, + }; + + // Ignore private imports unless they are explicit. these could be used if we are + // in a submodule of this module, but that's usually not + // what the user wants; and if this module can import + // the item and we're a submodule of it, so can we. + // Also this keeps the cached data smaller. + if declared || is_pub_or_explicit { + cb(visited_modules, name, module); } } diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index efa439946850..8f526d1a2369 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -510,12 +510,11 @@ impl ItemScope { id: AttrId, idx: usize, ) { - if let Some(derives) = self.derive_macros.get_mut(&adt) { - if let Some(DeriveMacroInvocation { derive_call_ids, .. }) = + if let Some(derives) = self.derive_macros.get_mut(&adt) + && let Some(DeriveMacroInvocation { derive_call_ids, .. }) = derives.iter_mut().find(|&&mut DeriveMacroInvocation { attr_id, .. }| id == attr_id) - { - derive_call_ids[idx] = Some(call); - } + { + derive_call_ids[idx] = Some(call); } } diff --git a/crates/hir-def/src/item_tree/lower.rs b/crates/hir-def/src/item_tree/lower.rs index 5ab61c89394b..032b287cd6a8 100644 --- a/crates/hir-def/src/item_tree/lower.rs +++ b/crates/hir-def/src/item_tree/lower.rs @@ -83,12 +83,12 @@ impl<'a> Ctx<'a> { .flat_map(|item| self.lower_mod_item(&item)) .collect(); - if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() { - if let Some(call) = tail_macro.macro_call() { - cov_mark::hit!(macro_stmt_with_trailing_macro_expr); - if let Some(mod_item) = self.lower_mod_item(&call.into()) { - self.top_level.push(mod_item); - } + if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() + && let Some(call) = tail_macro.macro_call() + { + cov_mark::hit!(macro_stmt_with_trailing_macro_expr); + if let Some(mod_item) = self.lower_mod_item(&call.into()) { + self.top_level.push(mod_item); } } @@ -112,12 +112,11 @@ impl<'a> Ctx<'a> { _ => None, }) .collect(); - if let Some(ast::Expr::MacroExpr(expr)) = block.tail_expr() { - if let Some(call) = expr.macro_call() { - if let Some(mod_item) = self.lower_mod_item(&call.into()) { - self.top_level.push(mod_item); - } - } + if let Some(ast::Expr::MacroExpr(expr)) = block.tail_expr() + && let Some(call) = expr.macro_call() + && let Some(mod_item) = self.lower_mod_item(&call.into()) + { + self.top_level.push(mod_item); } self.tree.vis.arena = self.visibilities.into_iter().collect(); self.tree.top_level = self.top_level.into_boxed_slice(); diff --git a/crates/hir-def/src/lang_item.rs b/crates/hir-def/src/lang_item.rs index 750308026eec..d431f2140165 100644 --- a/crates/hir-def/src/lang_item.rs +++ b/crates/hir-def/src/lang_item.rs @@ -218,10 +218,10 @@ pub(crate) fn crate_notable_traits(db: &dyn DefDatabase, krate: Crate) -> Option for (_, module_data) in crate_def_map.modules() { for def in module_data.scope.declarations() { - if let ModuleDefId::TraitId(trait_) = def { - if db.attrs(trait_.into()).has_doc_notable_trait() { - traits.push(trait_); - } + if let ModuleDefId::TraitId(trait_) = def + && db.attrs(trait_.into()).has_doc_notable_trait() + { + traits.push(trait_); } } } diff --git a/crates/hir-def/src/macro_expansion_tests/mod.rs b/crates/hir-def/src/macro_expansion_tests/mod.rs index 5e95b061399a..e8ae499d27b2 100644 --- a/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -221,46 +221,42 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream _ => None, }; - if let Some(src) = src { - if let Some(file_id) = src.file_id.macro_file() { - if let MacroKind::Derive - | MacroKind::DeriveBuiltIn - | MacroKind::Attr - | MacroKind::AttrBuiltIn = file_id.kind(&db) - { - let call = file_id.call_node(&db); - let mut show_spans = false; - let mut show_ctxt = false; - for comment in - call.value.children_with_tokens().filter(|it| it.kind() == COMMENT) - { - show_spans |= comment.to_string().contains("+spans"); - show_ctxt |= comment.to_string().contains("+syntaxctxt"); - } - let pp = pretty_print_macro_expansion( - src.value, - db.span_map(src.file_id).as_ref(), - show_spans, - show_ctxt, - ); - format_to!(expanded_text, "\n{}", pp) - } + if let Some(src) = src + && let Some(file_id) = src.file_id.macro_file() + && let MacroKind::Derive + | MacroKind::DeriveBuiltIn + | MacroKind::Attr + | MacroKind::AttrBuiltIn = file_id.kind(&db) + { + let call = file_id.call_node(&db); + let mut show_spans = false; + let mut show_ctxt = false; + for comment in call.value.children_with_tokens().filter(|it| it.kind() == COMMENT) { + show_spans |= comment.to_string().contains("+spans"); + show_ctxt |= comment.to_string().contains("+syntaxctxt"); } + let pp = pretty_print_macro_expansion( + src.value, + db.span_map(src.file_id).as_ref(), + show_spans, + show_ctxt, + ); + format_to!(expanded_text, "\n{}", pp) } } for impl_id in def_map[local_id].scope.impls() { let src = impl_id.lookup(&db).source(&db); - if let Some(macro_file) = src.file_id.macro_file() { - if let MacroKind::DeriveBuiltIn | MacroKind::Derive = macro_file.kind(&db) { - let pp = pretty_print_macro_expansion( - src.value.syntax().clone(), - db.span_map(macro_file.into()).as_ref(), - false, - false, - ); - format_to!(expanded_text, "\n{}", pp) - } + if let Some(macro_file) = src.file_id.macro_file() + && let MacroKind::DeriveBuiltIn | MacroKind::Derive = macro_file.kind(&db) + { + let pp = pretty_print_macro_expansion( + src.value.syntax().clone(), + db.span_map(macro_file.into()).as_ref(), + false, + false, + ); + format_to!(expanded_text, "\n{}", pp) } } diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index 0c3274d849ad..267c4451b9d7 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -261,20 +261,20 @@ impl<'db> DefCollector<'db> { // Process other crate-level attributes. for attr in &*attrs { - if let Some(cfg) = attr.cfg() { - if self.cfg_options.check(&cfg) == Some(false) { - process = false; - break; - } + if let Some(cfg) = attr.cfg() + && self.cfg_options.check(&cfg) == Some(false) + { + process = false; + break; } let Some(attr_name) = attr.path.as_ident() else { continue }; match () { () if *attr_name == sym::recursion_limit => { - if let Some(limit) = attr.string_value() { - if let Ok(limit) = limit.as_str().parse() { - crate_data.recursion_limit = Some(limit); - } + if let Some(limit) = attr.string_value() + && let Ok(limit) = limit.as_str().parse() + { + crate_data.recursion_limit = Some(limit); } } () if *attr_name == sym::crate_type => { @@ -1188,56 +1188,44 @@ impl<'db> DefCollector<'db> { // Multiple globs may import the same item and they may override visibility from // previously resolved globs. Handle overrides here and leave the rest to // `ItemScope::push_res_with_import()`. - if let Some(def) = defs.types { - if let Some(prev_def) = prev_defs.types { - if def.def == prev_def.def - && self.from_glob_import.contains_type(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // This import is being handled here, don't pass it down to - // `ItemScope::push_res_with_import()`. - defs.types = None; - self.def_map.modules[module_id] - .scope - .update_visibility_types(name, def.vis); - } - } + if let Some(def) = defs.types + && let Some(prev_def) = prev_defs.types + && def.def == prev_def.def + && self.from_glob_import.contains_type(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // This import is being handled here, don't pass it down to + // `ItemScope::push_res_with_import()`. + defs.types = None; + self.def_map.modules[module_id].scope.update_visibility_types(name, def.vis); } - if let Some(def) = defs.values { - if let Some(prev_def) = prev_defs.values { - if def.def == prev_def.def - && self.from_glob_import.contains_value(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // See comment above. - defs.values = None; - self.def_map.modules[module_id] - .scope - .update_visibility_values(name, def.vis); - } - } + if let Some(def) = defs.values + && let Some(prev_def) = prev_defs.values + && def.def == prev_def.def + && self.from_glob_import.contains_value(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // See comment above. + defs.values = None; + self.def_map.modules[module_id].scope.update_visibility_values(name, def.vis); } - if let Some(def) = defs.macros { - if let Some(prev_def) = prev_defs.macros { - if def.def == prev_def.def - && self.from_glob_import.contains_macro(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // See comment above. - defs.macros = None; - self.def_map.modules[module_id] - .scope - .update_visibility_macros(name, def.vis); - } - } + if let Some(def) = defs.macros + && let Some(prev_def) = prev_defs.macros + && def.def == prev_def.def + && self.from_glob_import.contains_macro(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // See comment above. + defs.macros = None; + self.def_map.modules[module_id].scope.update_visibility_macros(name, def.vis); } } @@ -1392,15 +1380,14 @@ impl<'db> DefCollector<'db> { Resolved::Yes }; - if let Some(ident) = path.as_ident() { - if let Some(helpers) = self.def_map.derive_helpers_in_scope.get(&ast_id) { - if helpers.iter().any(|(it, ..)| it == ident) { - cov_mark::hit!(resolved_derive_helper); - // Resolved to derive helper. Collect the item's attributes again, - // starting after the derive helper. - return recollect_without(self); - } - } + if let Some(ident) = path.as_ident() + && let Some(helpers) = self.def_map.derive_helpers_in_scope.get(&ast_id) + && helpers.iter().any(|(it, ..)| it == ident) + { + cov_mark::hit!(resolved_derive_helper); + // Resolved to derive helper. Collect the item's attributes again, + // starting after the derive helper. + return recollect_without(self); } let def = match resolver_def_id(path) { @@ -1729,12 +1716,12 @@ impl ModCollector<'_, '_> { let mut process_mod_item = |item: ModItemId| { let attrs = self.item_tree.attrs(db, krate, item.ast_id()); - if let Some(cfg) = attrs.cfg() { - if !self.is_cfg_enabled(&cfg) { - let ast_id = item.ast_id().erase(); - self.emit_unconfigured_diagnostic(InFile::new(self.file_id(), ast_id), &cfg); - return; - } + if let Some(cfg) = attrs.cfg() + && !self.is_cfg_enabled(&cfg) + { + let ast_id = item.ast_id().erase(); + self.emit_unconfigured_diagnostic(InFile::new(self.file_id(), ast_id), &cfg); + return; } if let Err(()) = self.resolve_attributes(&attrs, item, container) { @@ -1871,14 +1858,13 @@ impl ModCollector<'_, '_> { if self.def_collector.def_map.block.is_none() && self.def_collector.is_proc_macro && self.module_id == DefMap::ROOT + && let Some(proc_macro) = attrs.parse_proc_macro_decl(&it.name) { - if let Some(proc_macro) = attrs.parse_proc_macro_decl(&it.name) { - self.def_collector.export_proc_macro( - proc_macro, - InFile::new(self.file_id(), id), - fn_id, - ); - } + self.def_collector.export_proc_macro( + proc_macro, + InFile::new(self.file_id(), id), + fn_id, + ); } update_def(self.def_collector, fn_id.into(), &it.name, vis, false); @@ -2419,13 +2405,13 @@ impl ModCollector<'_, '_> { macro_id, &self.item_tree[mac.visibility], ); - if let Some(helpers) = helpers_opt { - if self.def_collector.def_map.block.is_none() { - Arc::get_mut(&mut self.def_collector.def_map.data) - .unwrap() - .exported_derives - .insert(macro_id.into(), helpers); - } + if let Some(helpers) = helpers_opt + && self.def_collector.def_map.block.is_none() + { + Arc::get_mut(&mut self.def_collector.def_map.data) + .unwrap() + .exported_derives + .insert(macro_id.into(), helpers); } } diff --git a/crates/hir-def/src/resolver.rs b/crates/hir-def/src/resolver.rs index 316ad5dae69d..a10990e6a8f9 100644 --- a/crates/hir-def/src/resolver.rs +++ b/crates/hir-def/src/resolver.rs @@ -228,15 +228,15 @@ impl<'db> Resolver<'db> { ResolvePathResultPrefixInfo::default(), )); } - } else if let &GenericDefId::AdtId(adt) = def { - if *first_name == sym::Self_ { - return Some(( - TypeNs::AdtSelfType(adt), - remaining_idx(), - None, - ResolvePathResultPrefixInfo::default(), - )); - } + } else if let &GenericDefId::AdtId(adt) = def + && *first_name == sym::Self_ + { + return Some(( + TypeNs::AdtSelfType(adt), + remaining_idx(), + None, + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_type_by_name(first_name, *def) { return Some(( @@ -401,13 +401,13 @@ impl<'db> Resolver<'db> { handle_macro_def_scope(db, &mut hygiene_id, &mut hygiene_info, macro_id) } Scope::GenericParams { params, def } => { - if let &GenericDefId::ImplId(impl_) = def { - if *first_name == sym::Self_ { - return Some(( - ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None), - ResolvePathResultPrefixInfo::default(), - )); - } + if let &GenericDefId::ImplId(impl_) = def + && *first_name == sym::Self_ + { + return Some(( + ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None), + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_const_by_name(first_name, *def) { let val = ValueNs::GenericParam(id); @@ -436,14 +436,14 @@ impl<'db> Resolver<'db> { ResolvePathResultPrefixInfo::default(), )); } - } else if let &GenericDefId::AdtId(adt) = def { - if *first_name == sym::Self_ { - let ty = TypeNs::AdtSelfType(adt); - return Some(( - ResolveValueResult::Partial(ty, 1, None), - ResolvePathResultPrefixInfo::default(), - )); - } + } else if let &GenericDefId::AdtId(adt) = def + && *first_name == sym::Self_ + { + let ty = TypeNs::AdtSelfType(adt); + return Some(( + ResolveValueResult::Partial(ty, 1, None), + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_type_by_name(first_name, *def) { let ty = TypeNs::GenericParam(id); @@ -469,13 +469,14 @@ impl<'db> Resolver<'db> { // If a path of the shape `u16::from_le_bytes` failed to resolve at all, then we fall back // to resolving to the primitive type, to allow this to still work in the presence of // `use core::u16;`. - if path.kind == PathKind::Plain && n_segments > 1 { - if let Some(builtin) = BuiltinType::by_name(first_name) { - return Some(( - ResolveValueResult::Partial(TypeNs::BuiltinType(builtin), 1, None), - ResolvePathResultPrefixInfo::default(), - )); - } + if path.kind == PathKind::Plain + && n_segments > 1 + && let Some(builtin) = BuiltinType::by_name(first_name) + { + return Some(( + ResolveValueResult::Partial(TypeNs::BuiltinType(builtin), 1, None), + ResolvePathResultPrefixInfo::default(), + )); } None @@ -660,12 +661,11 @@ impl<'db> Resolver<'db> { Scope::BlockScope(m) => traits.extend(m.def_map[m.module_id].scope.traits()), &Scope::GenericParams { def: GenericDefId::ImplId(impl_), .. } => { let impl_data = db.impl_signature(impl_); - if let Some(target_trait) = impl_data.target_trait { - if let Some(TypeNs::TraitId(trait_)) = self + if let Some(target_trait) = impl_data.target_trait + && let Some(TypeNs::TraitId(trait_)) = self .resolve_path_in_type_ns_fully(db, &impl_data.store[target_trait.path]) - { - traits.insert(trait_); - } + { + traits.insert(trait_); } } _ => (), @@ -918,17 +918,17 @@ fn handle_macro_def_scope( hygiene_info: &mut Option<(SyntaxContext, MacroDefId)>, macro_id: &MacroDefId, ) { - if let Some((parent_ctx, label_macro_id)) = hygiene_info { - if label_macro_id == macro_id { - // A macro is allowed to refer to variables from before its declaration. - // Therefore, if we got to the rib of its declaration, give up its hygiene - // and use its parent expansion. - *hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(db)); - *hygiene_info = parent_ctx.outer_expn(db).map(|expansion| { - let expansion = db.lookup_intern_macro_call(expansion.into()); - (parent_ctx.parent(db), expansion.def) - }); - } + if let Some((parent_ctx, label_macro_id)) = hygiene_info + && label_macro_id == macro_id + { + // A macro is allowed to refer to variables from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + *hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(db)); + *hygiene_info = parent_ctx.outer_expn(db).map(|expansion| { + let expansion = db.lookup_intern_macro_call(expansion.into()); + (parent_ctx.parent(db), expansion.def) + }); } } diff --git a/crates/hir-expand/src/builtin/fn_macro.rs b/crates/hir-expand/src/builtin/fn_macro.rs index 4a9af01091f2..58ab7f470c40 100644 --- a/crates/hir-expand/src/builtin/fn_macro.rs +++ b/crates/hir-expand/src/builtin/fn_macro.rs @@ -555,12 +555,11 @@ fn concat_expand( // FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses // to ensure the right parsing order, so skip the parentheses here. Ideally we'd // implement rustc's model. cc https://github.com/rust-lang/rust-analyzer/pull/10623 - if let TtElement::Subtree(subtree, subtree_iter) = &t { - if let [tt::TokenTree::Leaf(tt)] = subtree_iter.remaining().flat_tokens() { - if subtree.delimiter.kind == tt::DelimiterKind::Parenthesis { - t = TtElement::Leaf(tt); - } - } + if let TtElement::Subtree(subtree, subtree_iter) = &t + && let [tt::TokenTree::Leaf(tt)] = subtree_iter.remaining().flat_tokens() + && subtree.delimiter.kind == tt::DelimiterKind::Parenthesis + { + t = TtElement::Leaf(tt); } match t { TtElement::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => { diff --git a/crates/hir-expand/src/cfg_process.rs b/crates/hir-expand/src/cfg_process.rs index c6ea4a3a33db..d5ebd6ee19f5 100644 --- a/crates/hir-expand/src/cfg_process.rs +++ b/crates/hir-expand/src/cfg_process.rs @@ -334,10 +334,10 @@ where _ => Some(CfgExpr::Atom(CfgAtom::Flag(name))), }, }; - if let Some(NodeOrToken::Token(element)) = iter.peek() { - if element.kind() == syntax::T![,] { - iter.next(); - } + if let Some(NodeOrToken::Token(element)) = iter.peek() + && element.kind() == syntax::T![,] + { + iter.next(); } result } diff --git a/crates/hir-expand/src/fixup.rs b/crates/hir-expand/src/fixup.rs index 4a4a3e52aea4..fe77e1565987 100644 --- a/crates/hir-expand/src/fixup.rs +++ b/crates/hir-expand/src/fixup.rs @@ -280,8 +280,8 @@ pub(crate) fn fixup_syntax( } }, ast::RecordExprField(it) => { - if let Some(colon) = it.colon_token() { - if it.name_ref().is_some() && it.expr().is_none() { + if let Some(colon) = it.colon_token() + && it.name_ref().is_some() && it.expr().is_none() { append.insert(colon.into(), vec![ Leaf::Ident(Ident { sym: sym::__ra_fixup, @@ -290,11 +290,10 @@ pub(crate) fn fixup_syntax( }) ]); } - } }, ast::Path(it) => { - if let Some(colon) = it.coloncolon_token() { - if it.segment().is_none() { + if let Some(colon) = it.coloncolon_token() + && it.segment().is_none() { append.insert(colon.into(), vec![ Leaf::Ident(Ident { sym: sym::__ra_fixup, @@ -303,7 +302,6 @@ pub(crate) fn fixup_syntax( }) ]); } - } }, ast::ClosureExpr(it) => { if it.body().is_none() { diff --git a/crates/hir-expand/src/lib.rs b/crates/hir-expand/src/lib.rs index ac61b2200970..472ec83ffef5 100644 --- a/crates/hir-expand/src/lib.rs +++ b/crates/hir-expand/src/lib.rs @@ -365,12 +365,11 @@ impl HirFileId { HirFileId::FileId(id) => break id, HirFileId::MacroFile(file) => { let loc = db.lookup_intern_macro_call(file); - if loc.def.is_include() { - if let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind { - if let Ok(it) = include_input_to_file_id(db, file, &eager.arg) { - break it; - } - } + if loc.def.is_include() + && let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind + && let Ok(it) = include_input_to_file_id(db, file, &eager.arg) + { + break it; } self = loc.kind.file_id(); } @@ -648,12 +647,11 @@ impl MacroCallLoc { db: &dyn ExpandDatabase, macro_call_id: MacroCallId, ) -> Option { - if self.def.is_include() { - if let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind { - if let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg) { - return Some(it); - } - } + if self.def.is_include() + && let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind + && let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg) + { + return Some(it); } None diff --git a/crates/hir-expand/src/mod_path.rs b/crates/hir-expand/src/mod_path.rs index 9f1e3879e1ee..d84d978cdb7e 100644 --- a/crates/hir-expand/src/mod_path.rs +++ b/crates/hir-expand/src/mod_path.rs @@ -273,16 +273,17 @@ fn convert_path( // Basically, even in rustc it is quite hacky: // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456 // We follow what it did anyway :) - if mod_path.segments.len() == 1 && mod_path.kind == PathKind::Plain { - if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - let syn_ctx = span_for_range(segment.syntax().text_range()); - if let Some(macro_call_id) = syn_ctx.outer_expn(db) { - if db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner { - mod_path.kind = match resolve_crate_root(db, syn_ctx) { - Some(crate_root) => PathKind::DollarCrate(crate_root), - None => PathKind::Crate, - } - } + if mod_path.segments.len() == 1 + && mod_path.kind == PathKind::Plain + && let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + let syn_ctx = span_for_range(segment.syntax().text_range()); + if let Some(macro_call_id) = syn_ctx.outer_expn(db) + && db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner + { + mod_path.kind = match resolve_crate_root(db, syn_ctx) { + Some(crate_root) => PathKind::DollarCrate(crate_root), + None => PathKind::Crate, } } } diff --git a/crates/hir-ty/src/autoderef.rs b/crates/hir-ty/src/autoderef.rs index cc8f7bf04a5c..26ca7fb9a15e 100644 --- a/crates/hir-ty/src/autoderef.rs +++ b/crates/hir-ty/src/autoderef.rs @@ -197,10 +197,11 @@ pub(crate) fn deref_by_trait( // effectively bump the MSRV of rust-analyzer to 1.84 due to 1.83 and below lacking the // blanked impl on `Deref`. #[expect(clippy::overly_complex_bool_expr)] - if use_receiver_trait && false { - if let Some(receiver) = LangItem::Receiver.resolve_trait(db, table.trait_env.krate) { - return Some(receiver); - } + if use_receiver_trait + && false + && let Some(receiver) = LangItem::Receiver.resolve_trait(db, table.trait_env.krate) + { + return Some(receiver); } // Old rustc versions might not have `Receiver` trait. // Fallback to `Deref` if they don't diff --git a/crates/hir-ty/src/builder.rs b/crates/hir-ty/src/builder.rs index 77d15a73af6f..8af8fb73f344 100644 --- a/crates/hir-ty/src/builder.rs +++ b/crates/hir-ty/src/builder.rs @@ -309,11 +309,11 @@ impl TyBuilder { if let Some(defaults) = defaults.get(self.vec.len()..) { for default_ty in defaults { // NOTE(skip_binders): we only check if the arg type is error type. - if let Some(x) = default_ty.skip_binders().ty(Interner) { - if x.is_unknown() { - self.vec.push(fallback().cast(Interner)); - continue; - } + if let Some(x) = default_ty.skip_binders().ty(Interner) + && x.is_unknown() + { + self.vec.push(fallback().cast(Interner)); + continue; } // Each default can only depend on the previous parameters. self.vec.push(default_ty.clone().substitute(Interner, &*self.vec).cast(Interner)); diff --git a/crates/hir-ty/src/chalk_db.rs b/crates/hir-ty/src/chalk_db.rs index 26b635298a65..3ba7c93d4fb7 100644 --- a/crates/hir-ty/src/chalk_db.rs +++ b/crates/hir-ty/src/chalk_db.rs @@ -83,34 +83,34 @@ impl chalk_solve::RustIrDatabase for ChalkContext<'_> { Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None }) } fn discriminant_type(&self, ty: chalk_ir::Ty) -> chalk_ir::Ty { - if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) { - if let hir_def::AdtId::EnumId(e) = id.0 { - let enum_data = self.db.enum_signature(e); - let ty = enum_data.repr.unwrap_or_default().discr_type(); - return chalk_ir::TyKind::Scalar(match ty { - hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed { - true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize), - false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize), - }, - hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed { - true => chalk_ir::Scalar::Int(match size { - hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8, - hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16, - hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32, - hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64, - hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128, - }), - false => chalk_ir::Scalar::Uint(match size { - hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8, - hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16, - hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32, - hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64, - hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128, - }), - }, - }) - .intern(Interner); - } + if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) + && let hir_def::AdtId::EnumId(e) = id.0 + { + let enum_data = self.db.enum_signature(e); + let ty = enum_data.repr.unwrap_or_default().discr_type(); + return chalk_ir::TyKind::Scalar(match ty { + hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed { + true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize), + false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize), + }, + hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed { + true => chalk_ir::Scalar::Int(match size { + hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8, + hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16, + hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32, + hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64, + hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128, + }), + false => chalk_ir::Scalar::Uint(match size { + hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8, + hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16, + hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32, + hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64, + hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128, + }), + }, + }) + .intern(Interner); } chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U8)).intern(Interner) } @@ -142,10 +142,10 @@ impl chalk_solve::RustIrDatabase for ChalkContext<'_> { ) -> Option { if let TyKind::BoundVar(bv) = ty.kind(Interner) { let binders = binders.as_slice(Interner); - if bv.debruijn == DebruijnIndex::INNERMOST { - if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind { - return Some(tk); - } + if bv.debruijn == DebruijnIndex::INNERMOST + && let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind + { + return Some(tk); } } None diff --git a/crates/hir-ty/src/consteval.rs b/crates/hir-ty/src/consteval.rs index 14b9cd203f60..f30ec839a009 100644 --- a/crates/hir-ty/src/consteval.rs +++ b/crates/hir-ty/src/consteval.rs @@ -342,10 +342,10 @@ pub(crate) fn eval_to_const( return c; } } - if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, ctx.body, &infer, expr) { - if let Ok((Ok(result), _)) = interpret_mir(db, Arc::new(mir_body), true, None) { - return result; - } + if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, ctx.body, &infer, expr) + && let Ok((Ok(result), _)) = interpret_mir(db, Arc::new(mir_body), true, None) + { + return result; } unknown_const(infer[expr].clone()) } diff --git a/crates/hir-ty/src/diagnostics/decl_check.rs b/crates/hir-ty/src/diagnostics/decl_check.rs index 40fe3073cf2c..0815e62f87ee 100644 --- a/crates/hir-ty/src/diagnostics/decl_check.rs +++ b/crates/hir-ty/src/diagnostics/decl_check.rs @@ -657,10 +657,10 @@ impl<'a> DeclValidator<'a> { } fn is_trait_impl_container(&self, container_id: ItemContainerId) -> bool { - if let ItemContainerId::ImplId(impl_id) = container_id { - if self.db.impl_trait(impl_id).is_some() { - return true; - } + if let ItemContainerId::ImplId(impl_id) = container_id + && self.db.impl_trait(impl_id).is_some() + { + return true; } false } diff --git a/crates/hir-ty/src/diagnostics/expr.rs b/crates/hir-ty/src/diagnostics/expr.rs index cc531f076dd1..b26bd2b8fa9c 100644 --- a/crates/hir-ty/src/diagnostics/expr.rs +++ b/crates/hir-ty/src/diagnostics/expr.rs @@ -528,15 +528,15 @@ impl FilterMapNextChecker { return None; } - if *function_id == self.next_function_id? { - if let Some(prev_filter_map_expr_id) = self.prev_filter_map_expr_id { - let is_dyn_trait = self - .prev_receiver_ty - .as_ref() - .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(()); - } + if *function_id == self.next_function_id? + && let Some(prev_filter_map_expr_id) = self.prev_filter_map_expr_id + { + let is_dyn_trait = self + .prev_receiver_ty + .as_ref() + .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(()); } } diff --git a/crates/hir-ty/src/diagnostics/match_check.rs b/crates/hir-ty/src/diagnostics/match_check.rs index ca132fbdc454..e803b56a1ed8 100644 --- a/crates/hir-ty/src/diagnostics/match_check.rs +++ b/crates/hir-ty/src/diagnostics/match_check.rs @@ -382,10 +382,10 @@ impl HirDisplay for Pat { let subpats = (0..num_fields).map(|i| { WriteWith(move |f| { let fid = LocalFieldId::from_raw((i as u32).into()); - if let Some(p) = subpatterns.get(i) { - if p.field == fid { - return p.pattern.hir_fmt(f); - } + if let Some(p) = subpatterns.get(i) + && p.field == fid + { + return p.pattern.hir_fmt(f); } if let Some(p) = subpatterns.iter().find(|p| p.field == fid) { p.pattern.hir_fmt(f) diff --git a/crates/hir-ty/src/diagnostics/unsafe_check.rs b/crates/hir-ty/src/diagnostics/unsafe_check.rs index f6ad3c7aae2d..827585e50693 100644 --- a/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -272,10 +272,10 @@ impl<'db> UnsafeVisitor<'db> { if let Some(func) = callee.as_fn_def(self.db) { self.check_call(current, func); } - if let TyKind::Function(fn_ptr) = callee.kind(Interner) { - if fn_ptr.sig.safety == chalk_ir::Safety::Unsafe { - self.on_unsafe_op(current.into(), UnsafetyReason::UnsafeFnCall); - } + if let TyKind::Function(fn_ptr) = callee.kind(Interner) + && fn_ptr.sig.safety == chalk_ir::Safety::Unsafe + { + self.on_unsafe_op(current.into(), UnsafetyReason::UnsafeFnCall); } } Expr::Path(path) => { @@ -346,12 +346,11 @@ impl<'db> UnsafeVisitor<'db> { Expr::Cast { .. } => self.inside_assignment = inside_assignment, Expr::Field { .. } => { self.inside_assignment = inside_assignment; - if !inside_assignment { - if let Some(Either::Left(FieldId { parent: VariantId::UnionId(_), .. })) = + if !inside_assignment + && let Some(Either::Left(FieldId { parent: VariantId::UnionId(_), .. })) = self.infer.field_resolution(current) - { - self.on_unsafe_op(current.into(), UnsafetyReason::UnionField); - } + { + self.on_unsafe_op(current.into(), UnsafetyReason::UnionField); } } Expr::Unsafe { statements, .. } => { diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index f0e31ebd020c..8f35a3c21455 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -608,48 +608,46 @@ impl HirDisplay for ProjectionTy { // if we are projection on a type parameter, check if the projection target has bounds // itself, if so, we render them directly as `impl Bound` instead of the less useful // `::Assoc` - if !f.display_kind.is_source_code() { - if let TyKind::Placeholder(idx) = self_ty.kind(Interner) { - if !f.bounds_formatting_ctx.contains(self) { - let db = f.db; - let id = from_placeholder_idx(db, *idx); - let generics = generics(db, id.parent); - - let substs = generics.placeholder_subst(db); - let bounds = db - .generic_predicates(id.parent) - .iter() - .map(|pred| pred.clone().substitute(Interner, &substs)) - .filter(|wc| { - let ty = match wc.skip_binders() { - WhereClause::Implemented(tr) => tr.self_type_parameter(Interner), - WhereClause::TypeOutlives(t) => t.ty.clone(), - // We shouldn't be here if these exist - WhereClause::AliasEq(_) | WhereClause::LifetimeOutlives(_) => { - return false; - } - }; - let TyKind::Alias(AliasTy::Projection(proj)) = ty.kind(Interner) else { - return false; - }; - proj == self - }) - .collect::>(); - if !bounds.is_empty() { - return f.format_bounds_with(self.clone(), |f| { - write_bounds_like_dyn_trait_with_prefix( - f, - "impl", - Either::Left( - &TyKind::Alias(AliasTy::Projection(self.clone())) - .intern(Interner), - ), - &bounds, - SizedByDefault::NotSized, - ) - }); - } - } + if !f.display_kind.is_source_code() + && let TyKind::Placeholder(idx) = self_ty.kind(Interner) + && !f.bounds_formatting_ctx.contains(self) + { + let db = f.db; + let id = from_placeholder_idx(db, *idx); + let generics = generics(db, id.parent); + + let substs = generics.placeholder_subst(db); + let bounds = db + .generic_predicates(id.parent) + .iter() + .map(|pred| pred.clone().substitute(Interner, &substs)) + .filter(|wc| { + let ty = match wc.skip_binders() { + WhereClause::Implemented(tr) => tr.self_type_parameter(Interner), + WhereClause::TypeOutlives(t) => t.ty.clone(), + // We shouldn't be here if these exist + WhereClause::AliasEq(_) | WhereClause::LifetimeOutlives(_) => { + return false; + } + }; + let TyKind::Alias(AliasTy::Projection(proj)) = ty.kind(Interner) else { + return false; + }; + proj == self + }) + .collect::>(); + if !bounds.is_empty() { + return f.format_bounds_with(self.clone(), |f| { + write_bounds_like_dyn_trait_with_prefix( + f, + "impl", + Either::Left( + &TyKind::Alias(AliasTy::Projection(self.clone())).intern(Interner), + ), + &bounds, + SizedByDefault::NotSized, + ) + }); } } @@ -1860,18 +1858,13 @@ fn write_bounds_like_dyn_trait( write!(f, "{}", f.db.trait_signature(trait_).name.display(f.db, f.edition()))?; f.end_location_link(); if is_fn_trait { - if let [self_, params @ ..] = trait_ref.substitution.as_slice(Interner) { - if let Some(args) = + if let [self_, params @ ..] = trait_ref.substitution.as_slice(Interner) + && let Some(args) = params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple()) - { - write!(f, "(")?; - hir_fmt_generic_arguments( - f, - args.as_slice(Interner), - self_.ty(Interner), - )?; - write!(f, ")")?; - } + { + write!(f, "(")?; + hir_fmt_generic_arguments(f, args.as_slice(Interner), self_.ty(Interner))?; + write!(f, ")")?; } } else { let params = generic_args_sans_defaults( @@ -1879,13 +1872,13 @@ fn write_bounds_like_dyn_trait( Some(trait_.into()), trait_ref.substitution.as_slice(Interner), ); - if let [self_, params @ ..] = params { - if !params.is_empty() { - write!(f, "<")?; - hir_fmt_generic_arguments(f, params, self_.ty(Interner))?; - // there might be assoc type bindings, so we leave the angle brackets open - angle_open = true; - } + if let [self_, params @ ..] = params + && !params.is_empty() + { + write!(f, "<")?; + hir_fmt_generic_arguments(f, params, self_.ty(Interner))?; + // there might be assoc type bindings, so we leave the angle brackets open + angle_open = true; } } } @@ -2443,11 +2436,11 @@ impl HirDisplayWithExpressionStore for Path { generic_args.args[0].hir_fmt(f, store)?; } } - if let Some(ret) = generic_args.bindings[0].type_ref { - if !matches!(&store[ret], TypeRef::Tuple(v) if v.is_empty()) { - write!(f, " -> ")?; - ret.hir_fmt(f, store)?; - } + if let Some(ret) = generic_args.bindings[0].type_ref + && !matches!(&store[ret], TypeRef::Tuple(v) if v.is_empty()) + { + write!(f, " -> ")?; + ret.hir_fmt(f, store)?; } } hir_def::expr_store::path::GenericArgsParentheses::No => { diff --git a/crates/hir-ty/src/dyn_compatibility.rs b/crates/hir-ty/src/dyn_compatibility.rs index 30949c83bfae..6294d683e6c0 100644 --- a/crates/hir-ty/src/dyn_compatibility.rs +++ b/crates/hir-ty/src/dyn_compatibility.rs @@ -136,16 +136,15 @@ pub fn generics_require_sized_self(db: &dyn HirDatabase, def: GenericDefId) -> b let predicates = predicates.iter().map(|p| p.skip_binders().skip_binders().clone()); elaborate_clause_supertraits(db, predicates).any(|pred| match pred { WhereClause::Implemented(trait_ref) => { - if from_chalk_trait_id(trait_ref.trait_id) == sized { - if let TyKind::BoundVar(it) = + if from_chalk_trait_id(trait_ref.trait_id) == sized + && let TyKind::BoundVar(it) = *trait_ref.self_type_parameter(Interner).kind(Interner) - { - // Since `generic_predicates` is `Binder>`, the `DebrujinIndex` of - // self-parameter is `1` - return it - .index_if_bound_at(DebruijnIndex::ONE) - .is_some_and(|idx| idx == trait_self_param_idx); - } + { + // Since `generic_predicates` is `Binder>`, the `DebrujinIndex` of + // self-parameter is `1` + return it + .index_if_bound_at(DebruijnIndex::ONE) + .is_some_and(|idx| idx == trait_self_param_idx); } false } @@ -401,10 +400,10 @@ where cb(MethodViolationCode::ReferencesSelfOutput)?; } - if !func_data.is_async() { - if let Some(mvc) = contains_illegal_impl_trait_in_trait(db, &sig) { - cb(mvc)?; - } + if !func_data.is_async() + && let Some(mvc) = contains_illegal_impl_trait_in_trait(db, &sig) + { + cb(mvc)?; } let generic_params = db.generic_params(func.into()); diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs index 7c39afa0ef89..86345b23364d 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -902,12 +902,12 @@ impl<'db> InferenceContext<'db> { return false; } - if let UnresolvedMethodCall { field_with_same_name, .. } = diagnostic { - if let Some(ty) = field_with_same_name { - *ty = table.resolve_completely(ty.clone()); - if ty.contains_unknown() { - *field_with_same_name = None; - } + if let UnresolvedMethodCall { field_with_same_name, .. } = diagnostic + && let Some(ty) = field_with_same_name + { + *ty = table.resolve_completely(ty.clone()); + if ty.contains_unknown() { + *field_with_same_name = None; } } } @@ -1010,12 +1010,12 @@ impl<'db> InferenceContext<'db> { param_tys.push(va_list_ty); } let mut param_tys = param_tys.into_iter().chain(iter::repeat(self.table.new_type_var())); - if let Some(self_param) = self.body.self_param { - if let Some(ty) = param_tys.next() { - let ty = self.insert_type_vars(ty); - let ty = self.normalize_associated_types_in(ty); - self.write_binding_ty(self_param, ty); - } + if let Some(self_param) = self.body.self_param + && let Some(ty) = param_tys.next() + { + let ty = self.insert_type_vars(ty); + let ty = self.normalize_associated_types_in(ty); + self.write_binding_ty(self_param, ty); } let mut tait_candidates = FxHashSet::default(); for (ty, pat) in param_tys.zip(&*self.body.params) { @@ -1199,20 +1199,19 @@ impl<'db> InferenceContext<'db> { ) -> std::ops::ControlFlow { let ty = self.table.resolve_ty_shallow(ty); - if let TyKind::OpaqueType(id, _) = ty.kind(Interner) { - if let ImplTraitId::TypeAliasImplTrait(alias_id, _) = + if let TyKind::OpaqueType(id, _) = ty.kind(Interner) + && let ImplTraitId::TypeAliasImplTrait(alias_id, _) = self.db.lookup_intern_impl_trait_id((*id).into()) - { - let loc = self.db.lookup_intern_type_alias(alias_id); - match loc.container { - ItemContainerId::ImplId(impl_id) => { - self.assocs.insert(*id, (impl_id, ty.clone())); - } - ItemContainerId::ModuleId(..) | ItemContainerId::ExternBlockId(..) => { - self.non_assocs.insert(*id, ty.clone()); - } - _ => {} + { + let loc = self.db.lookup_intern_type_alias(alias_id); + match loc.container { + ItemContainerId::ImplId(impl_id) => { + self.assocs.insert(*id, (impl_id, ty.clone())); + } + ItemContainerId::ModuleId(..) | ItemContainerId::ExternBlockId(..) => { + self.non_assocs.insert(*id, ty.clone()); } + _ => {} } } diff --git a/crates/hir-ty/src/infer/cast.rs b/crates/hir-ty/src/infer/cast.rs index 4e95eca3f940..f0a4167f8e25 100644 --- a/crates/hir-ty/src/infer/cast.rs +++ b/crates/hir-ty/src/infer/cast.rs @@ -233,26 +233,25 @@ impl CastCheck { F: FnMut(ExprId, Vec), { // Mutability order is opposite to rustc. `Mut < Not` - if m_expr <= m_cast { - if let TyKind::Array(ety, _) = t_expr.kind(Interner) { - // Coerce to a raw pointer so that we generate RawPtr in MIR. - let array_ptr_type = TyKind::Raw(m_expr, t_expr.clone()).intern(Interner); - if let Ok((adj, _)) = table.coerce(&self.expr_ty, &array_ptr_type, CoerceNever::Yes) - { - apply_adjustments(self.source_expr, adj); - } else { - never!( - "could not cast from reference to array to pointer to array ({:?} to {:?})", - self.expr_ty, - array_ptr_type - ); - } + if m_expr <= m_cast + && let TyKind::Array(ety, _) = t_expr.kind(Interner) + { + // Coerce to a raw pointer so that we generate RawPtr in MIR. + let array_ptr_type = TyKind::Raw(m_expr, t_expr.clone()).intern(Interner); + if let Ok((adj, _)) = table.coerce(&self.expr_ty, &array_ptr_type, CoerceNever::Yes) { + apply_adjustments(self.source_expr, adj); + } else { + never!( + "could not cast from reference to array to pointer to array ({:?} to {:?})", + self.expr_ty, + array_ptr_type + ); + } - // This is a less strict condition than rustc's `demand_eqtype`, - // but false negative is better than false positive - if table.coerce(ety, t_cast, CoerceNever::Yes).is_ok() { - return Ok(()); - } + // This is a less strict condition than rustc's `demand_eqtype`, + // but false negative is better than false positive + if table.coerce(ety, t_cast, CoerceNever::Yes).is_ok() { + return Ok(()); } } diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index c3029bf2b59a..8024c1a9a4e9 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -176,12 +176,12 @@ impl InferenceContext<'_> { } // Deduction based on the expected `dyn Fn` is done separately. - if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) { - if let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) { - let expected_sig_ty = TyKind::Function(sig).intern(Interner); + if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) + && let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) + { + let expected_sig_ty = TyKind::Function(sig).intern(Interner); - self.unify(sig_ty, &expected_sig_ty); - } + self.unify(sig_ty, &expected_sig_ty); } } @@ -208,14 +208,13 @@ impl InferenceContext<'_> { alias: AliasTy::Projection(projection_ty), ty: projected_ty, }) = bound.skip_binders() - { - if let Some(sig) = self.deduce_sig_from_projection( + && let Some(sig) = self.deduce_sig_from_projection( closure_kind, projection_ty, projected_ty, - ) { - return Some(sig); - } + ) + { + return Some(sig); } None }); @@ -254,55 +253,44 @@ impl InferenceContext<'_> { let mut expected_kind = None; for clause in elaborate_clause_supertraits(self.db, clauses.rev()) { - if expected_sig.is_none() { - if let WhereClause::AliasEq(AliasEq { - alias: AliasTy::Projection(projection), - ty, - }) = &clause - { - let inferred_sig = - self.deduce_sig_from_projection(closure_kind, projection, ty); - // Make sure that we didn't infer a signature that mentions itself. - // This can happen when we elaborate certain supertrait bounds that - // mention projections containing the `Self` type. See rust-lang/rust#105401. - struct MentionsTy<'a> { - expected_ty: &'a Ty, - } - impl TypeVisitor for MentionsTy<'_> { - type BreakTy = (); + if expected_sig.is_none() + && let WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection), ty }) = + &clause + { + let inferred_sig = self.deduce_sig_from_projection(closure_kind, projection, ty); + // Make sure that we didn't infer a signature that mentions itself. + // This can happen when we elaborate certain supertrait bounds that + // mention projections containing the `Self` type. See rust-lang/rust#105401. + struct MentionsTy<'a> { + expected_ty: &'a Ty, + } + impl TypeVisitor for MentionsTy<'_> { + type BreakTy = (); - fn interner(&self) -> Interner { - Interner - } + fn interner(&self) -> Interner { + Interner + } - fn as_dyn( - &mut self, - ) -> &mut dyn TypeVisitor - { - self - } + fn as_dyn( + &mut self, + ) -> &mut dyn TypeVisitor + { + self + } - fn visit_ty( - &mut self, - t: &Ty, - db: chalk_ir::DebruijnIndex, - ) -> ControlFlow<()> { - if t == self.expected_ty { - ControlFlow::Break(()) - } else { - t.super_visit_with(self, db) - } + fn visit_ty(&mut self, t: &Ty, db: chalk_ir::DebruijnIndex) -> ControlFlow<()> { + if t == self.expected_ty { + ControlFlow::Break(()) + } else { + t.super_visit_with(self, db) } } - if inferred_sig - .visit_with( - &mut MentionsTy { expected_ty }, - chalk_ir::DebruijnIndex::INNERMOST, - ) - .is_continue() - { - expected_sig = inferred_sig; - } + } + if inferred_sig + .visit_with(&mut MentionsTy { expected_ty }, chalk_ir::DebruijnIndex::INNERMOST) + .is_continue() + { + expected_sig = inferred_sig; } } @@ -617,11 +605,10 @@ impl HirPlace { if let CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhasedBorrow, }) = current_capture + && self.projections[len..].contains(&ProjectionElem::Deref) { - if self.projections[len..].contains(&ProjectionElem::Deref) { - current_capture = - CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }); - } + current_capture = + CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }); } current_capture } @@ -1076,12 +1063,11 @@ impl InferenceContext<'_> { Mutability::Mut => CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::Default }), Mutability::Not => CaptureKind::ByRef(BorrowKind::Shared), }; - if let Some(place) = self.place_of_expr_without_adjust(tgt_expr) { - if let Some(place) = + if let Some(place) = self.place_of_expr_without_adjust(tgt_expr) + && let Some(place) = apply_adjusts_to_place(&mut self.current_capture_span_stack, place, rest) - { - self.add_capture(place, capture_kind); - } + { + self.add_capture(place, capture_kind); } self.walk_expr_with_adjust(tgt_expr, rest); } @@ -1169,15 +1155,15 @@ impl InferenceContext<'_> { } } self.walk_expr(*expr); - if let Some(discr_place) = self.place_of_expr(*expr) { - if self.is_upvar(&discr_place) { - let mut capture_mode = None; - for arm in arms.iter() { - self.walk_pat(&mut capture_mode, arm.pat); - } - if let Some(c) = capture_mode { - self.push_capture(discr_place, c); - } + if let Some(discr_place) = self.place_of_expr(*expr) + && self.is_upvar(&discr_place) + { + let mut capture_mode = None; + for arm in arms.iter() { + self.walk_pat(&mut capture_mode, arm.pat); + } + if let Some(c) = capture_mode { + self.push_capture(discr_place, c); } } } @@ -1209,13 +1195,11 @@ impl InferenceContext<'_> { let mutability = 'b: { if let Some(deref_trait) = self.resolve_lang_item(LangItem::DerefMut).and_then(|it| it.as_trait()) - { - if let Some(deref_fn) = deref_trait + && let Some(deref_fn) = deref_trait .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - break 'b deref_fn == f; - } + { + break 'b deref_fn == f; } false }; @@ -1405,10 +1389,10 @@ impl InferenceContext<'_> { fn expr_ty_after_adjustments(&self, e: ExprId) -> Ty { let mut ty = None; - if let Some(it) = self.result.expr_adjustments.get(&e) { - if let Some(it) = it.last() { - ty = Some(it.target.clone()); - } + if let Some(it) = self.result.expr_adjustments.get(&e) + && let Some(it) = it.last() + { + ty = Some(it.target.clone()); } ty.unwrap_or_else(|| self.expr_ty(e)) } @@ -1793,10 +1777,10 @@ impl InferenceContext<'_> { } pub(super) fn add_current_closure_dependency(&mut self, dep: ClosureId) { - if let Some(c) = self.current_closure { - if !dep_creates_cycle(&self.closure_dependencies, &mut FxHashSet::default(), c, dep) { - self.closure_dependencies.entry(c).or_default().push(dep); - } + if let Some(c) = self.current_closure + && !dep_creates_cycle(&self.closure_dependencies, &mut FxHashSet::default(), c, dep) + { + self.closure_dependencies.entry(c).or_default().push(dep); } fn dep_creates_cycle( diff --git a/crates/hir-ty/src/infer/coerce.rs b/crates/hir-ty/src/infer/coerce.rs index 39bd90849fe8..761a2564aa79 100644 --- a/crates/hir-ty/src/infer/coerce.rs +++ b/crates/hir-ty/src/infer/coerce.rs @@ -164,14 +164,14 @@ impl CoerceMany { // - [Comment from rustc](https://github.com/rust-lang/rust/blob/5ff18d0eaefd1bd9ab8ec33dab2404a44e7631ed/compiler/rustc_hir_typeck/src/coercion.rs#L1334-L1335) // First try to coerce the new expression to the type of the previous ones, // but only if the new expression has no coercion already applied to it. - if expr.is_none_or(|expr| !ctx.result.expr_adjustments.contains_key(&expr)) { - if let Ok(res) = ctx.coerce(expr, &expr_ty, &self.merged_ty(), CoerceNever::Yes) { - self.final_ty = Some(res); - if let Some(expr) = expr { - self.expressions.push(expr); - } - return; + if expr.is_none_or(|expr| !ctx.result.expr_adjustments.contains_key(&expr)) + && let Ok(res) = ctx.coerce(expr, &expr_ty, &self.merged_ty(), CoerceNever::Yes) + { + self.final_ty = Some(res); + if let Some(expr) = expr { + self.expressions.push(expr); } + return; } if let Ok((adjustments, res)) = @@ -322,18 +322,13 @@ impl InferenceTable<'_> { // If we are coercing into a TAIT, coerce into its proxy inference var, instead. let mut to_ty = to_ty; let _to; - if let Some(tait_table) = &self.tait_coercion_table { - if let TyKind::OpaqueType(opaque_ty_id, _) = to_ty.kind(Interner) { - if !matches!( - from_ty.kind(Interner), - TyKind::InferenceVar(..) | TyKind::OpaqueType(..) - ) { - if let Some(ty) = tait_table.get(opaque_ty_id) { - _to = ty.clone(); - to_ty = &_to; - } - } - } + if let Some(tait_table) = &self.tait_coercion_table + && let TyKind::OpaqueType(opaque_ty_id, _) = to_ty.kind(Interner) + && !matches!(from_ty.kind(Interner), TyKind::InferenceVar(..) | TyKind::OpaqueType(..)) + && let Some(ty) = tait_table.get(opaque_ty_id) + { + _to = ty.clone(); + to_ty = &_to; } // Consider coercing the subtype to a DST @@ -594,14 +589,13 @@ impl InferenceTable<'_> { F: FnOnce(Ty) -> Vec, G: FnOnce(Ty) -> Vec, { - if let TyKind::Function(to_fn_ptr) = to_ty.kind(Interner) { - if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) = + if let TyKind::Function(to_fn_ptr) = to_ty.kind(Interner) + && let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) = (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety) - { - let from_unsafe = - TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(Interner); - return self.unify_and(&from_unsafe, to_ty, to_unsafe); - } + { + let from_unsafe = + TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(Interner); + return self.unify_and(&from_unsafe, to_ty, to_unsafe); } self.unify_and(&from_ty, to_ty, normal) } diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index d43c99fc2827..16fc2bfc0631 100644 --- a/crates/hir-ty/src/infer/expr.rs +++ b/crates/hir-ty/src/infer/expr.rs @@ -653,19 +653,18 @@ impl InferenceContext<'_> { // FIXME: Note down method resolution her match op { UnaryOp::Deref => { - if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) { - if let Some(deref_fn) = deref_trait + if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) + && let Some(deref_fn) = deref_trait .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::deref)) - { - // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that - // the mutability is not wrong, and will be fixed in `self.infer_mut`). - self.write_method_resolution( - tgt_expr, - deref_fn, - Substitution::empty(Interner), - ); - } + { + // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that + // the mutability is not wrong, and will be fixed in `self.infer_mut`). + self.write_method_resolution( + tgt_expr, + deref_fn, + Substitution::empty(Interner), + ); } if let Some(derefed) = builtin_deref(self.table.db, &inner_ty, true) { self.resolve_ty_shallow(derefed) @@ -1387,28 +1386,28 @@ impl InferenceContext<'_> { let ret_ty = match method_ty.callable_sig(self.db) { Some(sig) => { let p_left = &sig.params()[0]; - if matches!(op, BinaryOp::CmpOp(..) | BinaryOp::Assignment { .. }) { - if let TyKind::Ref(mtbl, lt, _) = p_left.kind(Interner) { - self.write_expr_adj( - lhs, - Box::new([Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), - target: p_left.clone(), - }]), - ); - } + if matches!(op, BinaryOp::CmpOp(..) | BinaryOp::Assignment { .. }) + && let TyKind::Ref(mtbl, lt, _) = p_left.kind(Interner) + { + self.write_expr_adj( + lhs, + Box::new([Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), + target: p_left.clone(), + }]), + ); } let p_right = &sig.params()[1]; - if matches!(op, BinaryOp::CmpOp(..)) { - if let TyKind::Ref(mtbl, lt, _) = p_right.kind(Interner) { - self.write_expr_adj( - rhs, - Box::new([Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), - target: p_right.clone(), - }]), - ); - } + if matches!(op, BinaryOp::CmpOp(..)) + && let TyKind::Ref(mtbl, lt, _) = p_right.kind(Interner) + { + self.write_expr_adj( + rhs, + Box::new([Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), + target: p_right.clone(), + }]), + ); } sig.ret().clone() } @@ -1664,14 +1663,12 @@ impl InferenceContext<'_> { Some((ty, field_id, adjustments, is_public)) => { self.write_expr_adj(receiver, adjustments.into_boxed_slice()); self.result.field_resolutions.insert(tgt_expr, field_id); - if !is_public { - if let Either::Left(field) = field_id { - // FIXME: Merge this diagnostic into UnresolvedField? - self.push_diagnostic(InferenceDiagnostic::PrivateField { - expr: tgt_expr, - field, - }); - } + if !is_public && let Either::Left(field) = field_id { + // FIXME: Merge this diagnostic into UnresolvedField? + self.push_diagnostic(InferenceDiagnostic::PrivateField { + expr: tgt_expr, + field, + }); } ty } diff --git a/crates/hir-ty/src/infer/mutability.rs b/crates/hir-ty/src/infer/mutability.rs index 3f7eba9dd18c..c798e9e050a1 100644 --- a/crates/hir-ty/src/infer/mutability.rs +++ b/crates/hir-ty/src/infer/mutability.rs @@ -124,53 +124,41 @@ impl InferenceContext<'_> { self.infer_mut_not_expr_iter(fields.iter().map(|it| it.expr).chain(*spread)) } &Expr::Index { base, index } => { - if mutability == Mutability::Mut { - if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) { - if let Some(index_trait) = - LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate) - { - if let Some(index_fn) = index_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::index_mut)) - { - *f = index_fn; - let mut base_ty = None; - let base_adjustments = self - .result - .expr_adjustments - .get_mut(&base) - .and_then(|it| it.last_mut()); - if let Some(Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(_, mutability)), - target, - }) = base_adjustments - { - if let TyKind::Ref(_, _, ty) = target.kind(Interner) { - base_ty = Some(ty.clone()); - } - *mutability = Mutability::Mut; - } - - // Apply `IndexMut` obligation for non-assignee expr - if let Some(base_ty) = base_ty { - let index_ty = - if let Some(ty) = self.result.type_of_expr.get(index) { - ty.clone() - } else { - self.infer_expr( - index, - &Expectation::none(), - ExprIsRead::Yes, - ) - }; - let trait_ref = TyBuilder::trait_ref(self.db, index_trait) - .push(base_ty) - .fill(|_| index_ty.clone().cast(Interner)) - .build(); - self.push_obligation(trait_ref.cast(Interner)); - } - } + if mutability == Mutability::Mut + && let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) + && let Some(index_trait) = + LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate) + && let Some(index_fn) = index_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::index_mut)) + { + *f = index_fn; + let mut base_ty = None; + let base_adjustments = + self.result.expr_adjustments.get_mut(&base).and_then(|it| it.last_mut()); + if let Some(Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(_, mutability)), + target, + }) = base_adjustments + { + if let TyKind::Ref(_, _, ty) = target.kind(Interner) { + base_ty = Some(ty.clone()); } + *mutability = Mutability::Mut; + } + + // Apply `IndexMut` obligation for non-assignee expr + if let Some(base_ty) = base_ty { + let index_ty = if let Some(ty) = self.result.type_of_expr.get(index) { + ty.clone() + } else { + self.infer_expr(index, &Expectation::none(), ExprIsRead::Yes) + }; + let trait_ref = TyBuilder::trait_ref(self.db, index_trait) + .push(base_ty) + .fill(|_| index_ty.clone().cast(Interner)) + .build(); + self.push_obligation(trait_ref.cast(Interner)); } } self.infer_mut_expr(base, mutability); @@ -178,28 +166,23 @@ impl InferenceContext<'_> { } Expr::UnaryOp { expr, op: UnaryOp::Deref } => { let mut mutability = mutability; - if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) { - if mutability == Mutability::Mut { - if let Some(deref_trait) = - LangItem::DerefMut.resolve_trait(self.db, self.table.trait_env.krate) - { - let ty = self.result.type_of_expr.get(*expr); - let is_mut_ptr = ty.is_some_and(|ty| { - let ty = self.table.resolve_ty_shallow(ty); - matches!( - ty.kind(Interner), - chalk_ir::TyKind::Raw(Mutability::Mut, _) - ) - }); - if is_mut_ptr { - mutability = Mutability::Not; - } else if let Some(deref_fn) = deref_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - *f = deref_fn; - } - } + if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) + && mutability == Mutability::Mut + && let Some(deref_trait) = + LangItem::DerefMut.resolve_trait(self.db, self.table.trait_env.krate) + { + let ty = self.result.type_of_expr.get(*expr); + let is_mut_ptr = ty.is_some_and(|ty| { + let ty = self.table.resolve_ty_shallow(ty); + matches!(ty.kind(Interner), chalk_ir::TyKind::Raw(Mutability::Mut, _)) + }); + if is_mut_ptr { + mutability = Mutability::Not; + } else if let Some(deref_fn) = deref_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::deref_mut)) + { + *f = deref_fn; } } self.infer_mut_expr(*expr, mutability); diff --git a/crates/hir-ty/src/infer/pat.rs b/crates/hir-ty/src/infer/pat.rs index 18288b718f76..707bec0fce4c 100644 --- a/crates/hir-ty/src/infer/pat.rs +++ b/crates/hir-ty/src/infer/pat.rs @@ -498,12 +498,12 @@ impl InferenceContext<'_> { // If `expected` is an infer ty, we try to equate it to an array if the given pattern // allows it. See issue #16609 - if self.pat_is_irrefutable(decl) && expected.is_ty_var() { - if let Some(resolved_array_ty) = + if self.pat_is_irrefutable(decl) + && expected.is_ty_var() + && let Some(resolved_array_ty) = self.try_resolve_slice_ty_to_array_ty(prefix, suffix, slice) - { - self.unify(&expected, &resolved_array_ty); - } + { + self.unify(&expected, &resolved_array_ty); } let expected = self.resolve_ty_shallow(&expected); @@ -539,17 +539,16 @@ impl InferenceContext<'_> { fn infer_lit_pat(&mut self, expr: ExprId, expected: &Ty) -> Ty { // Like slice patterns, byte string patterns can denote both `&[u8; N]` and `&[u8]`. - if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] { - if let Some((inner, ..)) = expected.as_reference() { - let inner = self.resolve_ty_shallow(inner); - if matches!(inner.kind(Interner), TyKind::Slice(_)) { - let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner); - let slice_ty = TyKind::Slice(elem_ty).intern(Interner); - let ty = - TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty).intern(Interner); - self.write_expr_ty(expr, ty.clone()); - return ty; - } + if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] + && let Some((inner, ..)) = expected.as_reference() + { + let inner = self.resolve_ty_shallow(inner); + if matches!(inner.kind(Interner), TyKind::Slice(_)) { + let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner); + let slice_ty = TyKind::Slice(elem_ty).intern(Interner); + let ty = TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty).intern(Interner); + self.write_expr_ty(expr, ty.clone()); + return ty; } } diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index d61e7de6672f..afee9606bd5f 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -830,10 +830,10 @@ fn named_associated_type_shorthand_candidates( let data = t.hir_trait_id().trait_items(db); for (name, assoc_id) in &data.items { - if let AssocItemId::TypeAliasId(alias) = assoc_id { - if let Some(result) = cb(name, &t, *alias) { - return Some(result); - } + if let AssocItemId::TypeAliasId(alias) = assoc_id + && let Some(result) = cb(name, &t, *alias) + { + return Some(result); } } None diff --git a/crates/hir-ty/src/lower/path.rs b/crates/hir-ty/src/lower/path.rs index 5c06234fa077..9519c38eeddf 100644 --- a/crates/hir-ty/src/lower/path.rs +++ b/crates/hir-ty/src/lower/path.rs @@ -360,15 +360,14 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { } } - if let Some(enum_segment) = enum_segment { - if segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) - && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) - { - self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { - segment: (enum_segment + 1) as u32, - reason: GenericArgsProhibitedReason::EnumVariant, - }); - } + if let Some(enum_segment) = enum_segment + && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) + && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) + { + self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { + segment: (enum_segment + 1) as u32, + reason: GenericArgsProhibitedReason::EnumVariant, + }); } self.handle_type_ns_resolution(&resolution); @@ -417,15 +416,14 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { } } - if let Some(enum_segment) = enum_segment { - if segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) - && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) - { - self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { - segment: (enum_segment + 1) as u32, - reason: GenericArgsProhibitedReason::EnumVariant, - }); - } + if let Some(enum_segment) = enum_segment + && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) + && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) + { + self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { + segment: (enum_segment + 1) as u32, + reason: GenericArgsProhibitedReason::EnumVariant, + }); } match &res { @@ -576,13 +574,12 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { // This simplifies the code a bit. let penultimate_idx = self.current_segment_idx.wrapping_sub(1); let penultimate = self.segments.get(penultimate_idx); - if let Some(penultimate) = penultimate { - if self.current_or_prev_segment.args_and_bindings.is_none() - && penultimate.args_and_bindings.is_some() - { - self.current_segment_idx = penultimate_idx; - self.current_or_prev_segment = penultimate; - } + if let Some(penultimate) = penultimate + && self.current_or_prev_segment.args_and_bindings.is_none() + && penultimate.args_and_bindings.is_some() + { + self.current_segment_idx = penultimate_idx; + self.current_or_prev_segment = penultimate; } var.lookup(self.ctx.db).parent.into() } @@ -607,37 +604,36 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { ) -> Substitution { let mut lifetime_elision = self.ctx.lifetime_elision.clone(); - if let Some(args) = self.current_or_prev_segment.args_and_bindings { - if args.parenthesized != GenericArgsParentheses::No { - let prohibit_parens = match def { - GenericDefId::TraitId(trait_) => { - // RTN is prohibited anyways if we got here. - let is_rtn = - args.parenthesized == GenericArgsParentheses::ReturnTypeNotation; - let is_fn_trait = self - .ctx - .db - .trait_signature(trait_) - .flags - .contains(TraitFlags::RUSTC_PAREN_SUGAR); - is_rtn || !is_fn_trait - } - _ => true, - }; - - if prohibit_parens { - let segment = self.current_segment_u32(); - self.on_diagnostic( - PathLoweringDiagnostic::ParenthesizedGenericArgsWithoutFnTrait { segment }, - ); - - return TyBuilder::unknown_subst(self.ctx.db, def); + if let Some(args) = self.current_or_prev_segment.args_and_bindings + && args.parenthesized != GenericArgsParentheses::No + { + let prohibit_parens = match def { + GenericDefId::TraitId(trait_) => { + // RTN is prohibited anyways if we got here. + let is_rtn = args.parenthesized == GenericArgsParentheses::ReturnTypeNotation; + let is_fn_trait = self + .ctx + .db + .trait_signature(trait_) + .flags + .contains(TraitFlags::RUSTC_PAREN_SUGAR); + is_rtn || !is_fn_trait } + _ => true, + }; - // `Fn()`-style generics are treated like functions for the purpose of lifetime elision. - lifetime_elision = - LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false }; + if prohibit_parens { + let segment = self.current_segment_u32(); + self.on_diagnostic( + PathLoweringDiagnostic::ParenthesizedGenericArgsWithoutFnTrait { segment }, + ); + + return TyBuilder::unknown_subst(self.ctx.db, def); } + + // `Fn()`-style generics are treated like functions for the purpose of lifetime elision. + lifetime_elision = + LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false }; } self.substs_from_args_and_bindings( @@ -753,18 +749,20 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { match param { GenericParamDataRef::LifetimeParamData(_) => error_lifetime().cast(Interner), GenericParamDataRef::TypeParamData(param) => { - if !infer_args && param.default.is_some() { - if let Some(default) = default() { - return default; - } + if !infer_args + && param.default.is_some() + && let Some(default) = default() + { + return default; } TyKind::Error.intern(Interner).cast(Interner) } GenericParamDataRef::ConstParamData(param) => { - if !infer_args && param.default.is_some() { - if let Some(default) = default() { - return default; - } + if !infer_args + && param.default.is_some() + && let Some(default) = default() + { + return default; } let GenericParamId::ConstParamId(const_id) = param_id else { unreachable!("non-const param ID for const param"); diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index a6150a9bc172..b22781e94701 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -581,15 +581,15 @@ impl ReceiverAdjustments { } if self.unsize_array { ty = 'it: { - if let TyKind::Ref(m, l, inner) = ty.kind(Interner) { - if let TyKind::Array(inner, _) = inner.kind(Interner) { - break 'it TyKind::Ref( - *m, - l.clone(), - TyKind::Slice(inner.clone()).intern(Interner), - ) - .intern(Interner); - } + if let TyKind::Ref(m, l, inner) = ty.kind(Interner) + && let TyKind::Array(inner, _) = inner.kind(Interner) + { + break 'it TyKind::Ref( + *m, + l.clone(), + TyKind::Slice(inner.clone()).intern(Interner), + ) + .intern(Interner); } // FIXME: report diagnostic if array unsizing happens without indirection. ty @@ -1549,11 +1549,11 @@ fn is_valid_impl_method_candidate( check_that!(receiver_ty.is_none()); check_that!(name.is_none_or(|n| n == item_name)); - if let Some(from_module) = visible_from_module { - if !db.assoc_visibility(c.into()).is_visible_from(db, from_module) { - cov_mark::hit!(const_candidate_not_visible); - return IsValidCandidate::NotVisible; - } + if let Some(from_module) = visible_from_module + && !db.assoc_visibility(c.into()).is_visible_from(db, from_module) + { + cov_mark::hit!(const_candidate_not_visible); + return IsValidCandidate::NotVisible; } let self_ty_matches = table.run_in_snapshot(|table| { let expected_self_ty = @@ -1638,11 +1638,11 @@ fn is_valid_impl_fn_candidate( let db = table.db; let data = db.function_signature(fn_id); - if let Some(from_module) = visible_from_module { - if !db.assoc_visibility(fn_id.into()).is_visible_from(db, from_module) { - cov_mark::hit!(autoderef_candidate_not_visible); - return IsValidCandidate::NotVisible; - } + if let Some(from_module) = visible_from_module + && !db.assoc_visibility(fn_id.into()).is_visible_from(db, from_module) + { + cov_mark::hit!(autoderef_candidate_not_visible); + return IsValidCandidate::NotVisible; } table.run_in_snapshot(|table| { let _p = tracing::info_span!("subst_for_def").entered(); diff --git a/crates/hir-ty/src/mir/borrowck.rs b/crates/hir-ty/src/mir/borrowck.rs index fb0c0dee095f..52df851c30d1 100644 --- a/crates/hir-ty/src/mir/borrowck.rs +++ b/crates/hir-ty/src/mir/borrowck.rs @@ -559,10 +559,9 @@ fn mutability_of_locals( }, p, ) = value + && place_case(db, body, p) != ProjectionCase::Indirect { - if place_case(db, body, p) != ProjectionCase::Indirect { - push_mut_span(p.local, statement.span, &mut result); - } + push_mut_span(p.local, statement.span, &mut result); } } StatementKind::FakeRead(p) => { diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index 9a97bd6dbe29..dfb8ae704b99 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -1082,18 +1082,18 @@ impl Evaluator<'_> { let stack_size = { let mut stack_ptr = self.stack.len(); for (id, it) in body.locals.iter() { - if id == return_slot() { - if let Some(destination) = destination { - locals.ptr.insert(id, destination); - continue; - } + if id == return_slot() + && let Some(destination) = destination + { + locals.ptr.insert(id, destination); + continue; } let (size, align) = self.size_align_of_sized( &it.ty, &locals, "no unsized local in extending stack", )?; - while stack_ptr % align != 0 { + while !stack_ptr.is_multiple_of(align) { stack_ptr += 1; } let my_ptr = stack_ptr; @@ -1673,14 +1673,14 @@ impl Evaluator<'_> { if let Some(it) = goal(kind) { return Ok(it); } - if let TyKind::Adt(id, subst) = kind { - if let AdtId::StructId(struct_id) = id.0 { - let field_types = self.db.field_types(struct_id.into()); - if let Some(ty) = - field_types.iter().last().map(|it| it.1.clone().substitute(Interner, subst)) - { - return self.coerce_unsized_look_through_fields(&ty, goal); - } + if let TyKind::Adt(id, subst) = kind + && let AdtId::StructId(struct_id) = id.0 + { + let field_types = self.db.field_types(struct_id.into()); + if let Some(ty) = + field_types.iter().last().map(|it| it.1.clone().substitute(Interner, subst)) + { + return self.coerce_unsized_look_through_fields(&ty, goal); } } Err(MirEvalError::CoerceUnsizedError(ty.clone())) @@ -1778,17 +1778,15 @@ impl Evaluator<'_> { locals: &Locals, ) -> Result<(usize, Arc, Option<(usize, usize, i128)>)> { let adt = it.adt_id(self.db); - if let DefWithBodyId::VariantId(f) = locals.body.owner { - if let VariantId::EnumVariantId(it) = it { - if let AdtId::EnumId(e) = adt { - if f.lookup(self.db).parent == e { - // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and - // infinite sized type errors) we use a dummy layout - let i = self.const_eval_discriminant(it)?; - return Ok((16, self.layout(&TyBuilder::unit())?, Some((0, 16, i)))); - } - } - } + if let DefWithBodyId::VariantId(f) = locals.body.owner + && let VariantId::EnumVariantId(it) = it + && let AdtId::EnumId(e) = adt + && f.lookup(self.db).parent == e + { + // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and + // infinite sized type errors) we use a dummy layout + let i = self.const_eval_discriminant(it)?; + return Ok((16, self.layout(&TyBuilder::unit())?, Some((0, 16, i)))); } let layout = self.layout_adt(adt, subst)?; Ok(match &layout.variants { @@ -1909,10 +1907,10 @@ impl Evaluator<'_> { let name = const_id.name(self.db); MirEvalError::ConstEvalError(name, Box::new(e)) })?; - if let chalk_ir::ConstValue::Concrete(c) = &result_owner.data(Interner).value { - if let ConstScalar::Bytes(v, mm) = &c.interned { - break 'b (v, mm); - } + if let chalk_ir::ConstValue::Concrete(c) = &result_owner.data(Interner).value + && let ConstScalar::Bytes(v, mm) = &c.interned + { + break 'b (v, mm); } not_supported!("unevaluatable constant"); } @@ -2055,14 +2053,13 @@ impl Evaluator<'_> { .is_sized() .then(|| (layout.size.bytes_usize(), layout.align.abi.bytes() as usize))); } - if let DefWithBodyId::VariantId(f) = locals.body.owner { - if let Some((AdtId::EnumId(e), _)) = ty.as_adt() { - if f.lookup(self.db).parent == e { - // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and - // infinite sized type errors) we use a dummy size - return Ok(Some((16, 16))); - } - } + if let DefWithBodyId::VariantId(f) = locals.body.owner + && let Some((AdtId::EnumId(e), _)) = ty.as_adt() + && f.lookup(self.db).parent == e + { + // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and + // infinite sized type errors) we use a dummy size + return Ok(Some((16, 16))); } let layout = self.layout(ty); if self.assert_placeholder_ty_is_unused @@ -2103,7 +2100,7 @@ impl Evaluator<'_> { if !align.is_power_of_two() || align > 10000 { return Err(MirEvalError::UndefinedBehavior(format!("Alignment {align} is invalid"))); } - while self.heap.len() % align != 0 { + while !self.heap.len().is_multiple_of(align) { self.heap.push(0); } if size.checked_add(self.heap.len()).is_none_or(|x| x > self.memory_limit) { diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs index e9665d5ae9cf..bb4c963a8ae1 100644 --- a/crates/hir-ty/src/mir/eval/shim.rs +++ b/crates/hir-ty/src/mir/eval/shim.rs @@ -119,25 +119,25 @@ impl Evaluator<'_> { destination.write_from_bytes(self, &result)?; return Ok(true); } - if let ItemContainerId::TraitId(t) = def.lookup(self.db).container { - if self.db.lang_attr(t.into()) == Some(LangItem::Clone) { - let [self_ty] = generic_args.as_slice(Interner) else { - not_supported!("wrong generic arg count for clone"); - }; - let Some(self_ty) = self_ty.ty(Interner) else { - not_supported!("wrong generic arg kind for clone"); - }; - // Clone has special impls for tuples and function pointers - if matches!( - self_ty.kind(Interner), - TyKind::Function(_) | TyKind::Tuple(..) | TyKind::Closure(..) - ) { - self.exec_clone(def, args, self_ty.clone(), locals, destination, span)?; - return Ok(true); - } - // Return early to prevent caching clone as non special fn. - return Ok(false); + if let ItemContainerId::TraitId(t) = def.lookup(self.db).container + && self.db.lang_attr(t.into()) == Some(LangItem::Clone) + { + let [self_ty] = generic_args.as_slice(Interner) else { + not_supported!("wrong generic arg count for clone"); + }; + let Some(self_ty) = self_ty.ty(Interner) else { + not_supported!("wrong generic arg kind for clone"); + }; + // Clone has special impls for tuples and function pointers + if matches!( + self_ty.kind(Interner), + TyKind::Function(_) | TyKind::Tuple(..) | TyKind::Closure(..) + ) { + self.exec_clone(def, args, self_ty.clone(), locals, destination, span)?; + return Ok(true); } + // Return early to prevent caching clone as non special fn. + return Ok(false); } self.not_special_fn_cache.borrow_mut().insert(def); Ok(false) @@ -1256,23 +1256,22 @@ impl Evaluator<'_> { let addr = tuple.interval.addr.offset(offset); args.push(IntervalAndTy::new(addr, field, self, locals)?); } - if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) { - if let Some(def) = target + if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) + && let Some(def) = target .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::call_once)) - { - self.exec_fn_trait( - def, - &args, - // FIXME: wrong for manual impls of `FnOnce` - Substitution::empty(Interner), - locals, - destination, - None, - span, - )?; - return Ok(true); - } + { + self.exec_fn_trait( + def, + &args, + // FIXME: wrong for manual impls of `FnOnce` + Substitution::empty(Interner), + locals, + destination, + None, + span, + )?; + return Ok(true); } not_supported!("FnOnce was not available for executing const_eval_select"); } @@ -1367,12 +1366,11 @@ impl Evaluator<'_> { break; } } - if signed { - if let Some((&l, &r)) = lhs.iter().zip(rhs).next_back() { - if l != r { - result = (l as i8).cmp(&(r as i8)); - } - } + if signed + && let Some((&l, &r)) = lhs.iter().zip(rhs).next_back() + && l != r + { + result = (l as i8).cmp(&(r as i8)); } if let Some(e) = LangItem::Ordering.resolve_enum(self.db, self.crate_id) { let ty = self.db.ty(e.into()); diff --git a/crates/hir-ty/src/mir/eval/shim/simd.rs b/crates/hir-ty/src/mir/eval/shim/simd.rs index bc331a23d98e..f55477290453 100644 --- a/crates/hir-ty/src/mir/eval/shim/simd.rs +++ b/crates/hir-ty/src/mir/eval/shim/simd.rs @@ -114,12 +114,11 @@ impl Evaluator<'_> { break; } } - if is_signed { - if let Some((&l, &r)) = l.iter().zip(r).next_back() { - if l != r { - result = (l as i8).cmp(&(r as i8)); - } - } + if is_signed + && let Some((&l, &r)) = l.iter().zip(r).next_back() + && l != r + { + result = (l as i8).cmp(&(r as i8)); } let result = match result { Ordering::Less => ["lt", "le", "ne"].contains(&name), diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index 07d814727293..eb80e8706fa0 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -320,11 +320,11 @@ impl<'ctx> MirLowerCtx<'ctx> { expr_id: ExprId, current: BasicBlockId, ) -> Result> { - if !self.has_adjustments(expr_id) { - if let Expr::Literal(l) = &self.body[expr_id] { - let ty = self.expr_ty_without_adjust(expr_id); - return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); - } + if !self.has_adjustments(expr_id) + && let Expr::Literal(l) = &self.body[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 { return Ok(None); @@ -1039,18 +1039,18 @@ impl<'ctx> MirLowerCtx<'ctx> { && rhs_ty.is_scalar() && (lhs_ty == rhs_ty || builtin_inequal_impls) }; - if !is_builtin { - if let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) { - let func = Operand::from_fn(self.db, func_id, generic_args); - return self.lower_call_and_args( - func, - [*lhs, *rhs].into_iter(), - place, - current, - self.is_uninhabited(expr_id), - expr_id.into(), - ); - } + if !is_builtin + && let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) + { + let func = Operand::from_fn(self.db, func_id, generic_args); + return self.lower_call_and_args( + func, + [*lhs, *rhs].into_iter(), + place, + current, + self.is_uninhabited(expr_id), + expr_id.into(), + ); } if let hir_def::hir::BinaryOp::Assignment { op: Some(op) } = op { // last adjustment is `&mut` which we don't want it. @@ -1596,10 +1596,10 @@ impl<'ctx> MirLowerCtx<'ctx> { fn expr_ty_after_adjustments(&self, e: ExprId) -> Ty { let mut ty = None; - if let Some(it) = self.infer.expr_adjustments.get(&e) { - if let Some(it) = it.last() { - ty = Some(it.target.clone()); - } + if let Some(it) = self.infer.expr_adjustments.get(&e) + && let Some(it) = it.last() + { + ty = Some(it.target.clone()); } ty.unwrap_or_else(|| self.expr_ty_without_adjust(e)) } @@ -1848,13 +1848,13 @@ impl<'ctx> MirLowerCtx<'ctx> { self.result.param_locals.extend(params.clone().map(|(it, ty)| { let local_id = self.result.locals.alloc(Local { ty }); self.drop_scopes.last_mut().unwrap().locals.push(local_id); - if let Pat::Bind { id, subpat: None } = self.body[it] { - if matches!( + if let Pat::Bind { id, subpat: None } = self.body[it] + && matches!( self.body[id].mode, BindingAnnotation::Unannotated | BindingAnnotation::Mutable - ) { - self.result.binding_locals.insert(id, local_id); - } + ) + { + self.result.binding_locals.insert(id, local_id); } local_id })); @@ -1887,10 +1887,10 @@ impl<'ctx> MirLowerCtx<'ctx> { .into_iter() .skip(base_param_count + self_binding.is_some() as usize); for ((param, _), local) in params.zip(local_params) { - if let Pat::Bind { id, .. } = self.body[param] { - if local == self.binding_local(id)? { - continue; - } + if let Pat::Bind { id, .. } = self.body[param] + && local == self.binding_local(id)? + { + continue; } let r = self.pattern_match(current, None, local.into(), param)?; if let Some(b) = r.1 { diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs index e074c2d558e8..42a14664626f 100644 --- a/crates/hir-ty/src/mir/lower/as_place.rs +++ b/crates/hir-ty/src/mir/lower/as_place.rs @@ -189,17 +189,14 @@ impl MirLowerCtx<'_> { 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) = + if let Some((f, _)) = self.infer.method_resolution(expr_id) + && let Some(deref_trait) = self.resolve_lang_item(LangItem::DerefMut)?.as_trait() - { - if let Some(deref_fn) = deref_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - break 'b deref_fn == f; - } - } + && let Some(deref_fn) = deref_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::deref_mut)) + { + break 'b deref_fn == f; } false }, diff --git a/crates/hir-ty/src/mir/lower/pattern_matching.rs b/crates/hir-ty/src/mir/lower/pattern_matching.rs index 3325226b1d36..0440d8502232 100644 --- a/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -317,27 +317,26 @@ impl MirLowerCtx<'_> { (current, current_else) = self.pattern_match_inner(current, current_else, next_place, pat, mode)?; } - if let &Some(slice) = slice { - if mode != MatchingMode::Check { - if let Pat::Bind { id, subpat: _ } = self.body[slice] { - let next_place = cond_place.project( - ProjectionElem::Subslice { - from: prefix.len() as u64, - to: suffix.len() as u64, - }, - &mut self.result.projection_store, - ); - let mode = self.infer.binding_modes[slice]; - (current, current_else) = self.pattern_match_binding( - id, - mode, - next_place, - (slice).into(), - current, - current_else, - )?; - } - } + if let &Some(slice) = slice + && mode != MatchingMode::Check + && let Pat::Bind { id, subpat: _ } = self.body[slice] + { + let next_place = cond_place.project( + ProjectionElem::Subslice { + from: prefix.len() as u64, + to: suffix.len() as u64, + }, + &mut self.result.projection_store, + ); + let mode = self.infer.binding_modes[slice]; + (current, current_else) = self.pattern_match_binding( + id, + mode, + next_place, + (slice).into(), + current, + current_else, + )?; } for (i, &pat) in suffix.iter().enumerate() { let next_place = cond_place.project( @@ -391,10 +390,10 @@ impl MirLowerCtx<'_> { return Ok((current, current_else)); } let (c, subst) = 'b: { - if let Some(x) = self.infer.assoc_resolutions_for_pat(pattern) { - if let AssocItemId::ConstId(c) = x.0 { - break 'b (c, x.1); - } + if let Some(x) = self.infer.assoc_resolutions_for_pat(pattern) + && let AssocItemId::ConstId(c) = x.0 + { + break 'b (c, x.1); } if let ResolveValueResult::ValueNs(ValueNs::ConstId(c), _) = pr { break 'b (c, Substitution::empty(Interner)); diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index 7414b4fc6070..08b9d242e71d 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -125,11 +125,10 @@ pub(crate) fn trait_solve_query( alias: AliasTy::Projection(projection_ty), .. }))) = &goal.value.goal.data(Interner) + && let TyKind::BoundVar(_) = projection_ty.self_type_parameter(db).kind(Interner) { - if let TyKind::BoundVar(_) = projection_ty.self_type_parameter(db).kind(Interner) { - // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible - return Some(Solution::Ambig(Guidance::Unknown)); - } + // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible + return Some(Solution::Ambig(Guidance::Unknown)); } // Chalk see `UnevaluatedConst` as a unique concrete value, but we see it as an alias for another const. So diff --git a/crates/hir-ty/src/utils.rs b/crates/hir-ty/src/utils.rs index d07c1aa33b40..209ec7926e82 100644 --- a/crates/hir-ty/src/utils.rs +++ b/crates/hir-ty/src/utils.rs @@ -333,13 +333,13 @@ impl FallibleTypeFolder for UnevaluatedConstEvaluatorFolder<'_> { constant: Const, _outer_binder: DebruijnIndex, ) -> Result { - if let chalk_ir::ConstValue::Concrete(c) = &constant.data(Interner).value { - if let ConstScalar::UnevaluatedConst(id, subst) = &c.interned { - if let Ok(eval) = self.db.const_eval(*id, subst.clone(), None) { - return Ok(eval); - } else { - return Ok(unknown_const(constant.data(Interner).ty.clone())); - } + if let chalk_ir::ConstValue::Concrete(c) = &constant.data(Interner).value + && let ConstScalar::UnevaluatedConst(id, subst) = &c.interned + { + if let Ok(eval) = self.db.const_eval(*id, subst.clone(), None) { + return Ok(eval); + } else { + return Ok(unknown_const(constant.data(Interner).ty.clone())); } } Ok(constant) diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index c1e814ec223e..fca0162765ec 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs @@ -604,13 +604,13 @@ impl<'db> AnyDiagnostic<'db> { } } BodyValidationDiagnostic::RemoveUnnecessaryElse { if_expr } => { - if let Ok(source_ptr) = source_map.expr_syntax(if_expr) { - if let Some(ptr) = source_ptr.value.cast::() { - return Some( - RemoveUnnecessaryElse { if_expr: InFile::new(source_ptr.file_id, ptr) } - .into(), - ); - } + if let Ok(source_ptr) = source_map.expr_syntax(if_expr) + && let Some(ptr) = source_ptr.value.cast::() + { + return Some( + RemoveUnnecessaryElse { if_expr: InFile::new(source_ptr.file_id, ptr) } + .into(), + ); } } } diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 4ddb04b24f7f..a323f97997c6 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1020,21 +1020,21 @@ fn emit_macro_def_diagnostics<'db>( m: Macro, ) { let id = db.macro_def(m.id); - if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) { - if let Some(e) = expander.mac.err() { - let Some(ast) = id.ast_id().left() else { - never!("declarative expander for non decl-macro: {:?}", e); - return; - }; - let krate = HasModule::krate(&m.id, db); - let edition = krate.data(db).edition; - emit_def_diagnostic_( - db, - acc, - &DefDiagnosticKind::MacroDefError { ast, message: e.to_string() }, - edition, - ); - } + if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) + && let Some(e) = expander.mac.err() + { + let Some(ast) = id.ast_id().left() else { + never!("declarative expander for non decl-macro: {:?}", e); + return; + }; + let krate = HasModule::krate(&m.id, db); + let edition = krate.data(db).edition; + emit_def_diagnostic_( + db, + acc, + &DefDiagnosticKind::MacroDefError { ast, message: e.to_string() }, + edition, + ); } } @@ -2564,10 +2564,10 @@ impl<'db> Param<'db> { Callee::Closure(closure, _) => { let c = db.lookup_intern_closure(closure.into()); let body = db.body(c.0); - if let Expr::Closure { args, .. } = &body[c.1] { - if let Pat::Bind { id, .. } = &body[args[self.idx]] { - return Some(Local { parent: c.0, binding_id: *id }); - } + if let Expr::Closure { args, .. } = &body[c.1] + && let Pat::Bind { id, .. } = &body[args[self.idx]] + { + return Some(Local { parent: c.0, binding_id: *id }); } None } @@ -2761,26 +2761,20 @@ impl EvaluatedConst { pub fn render_debug(&self, db: &dyn HirDatabase) -> Result { let data = self.const_.data(Interner); - if let TyKind::Scalar(s) = data.ty.kind(Interner) { - if matches!(s, Scalar::Int(_) | Scalar::Uint(_)) { - if let hir_ty::ConstValue::Concrete(c) = &data.value { - if let hir_ty::ConstScalar::Bytes(b, _) = &c.interned { - let value = u128::from_le_bytes(mir::pad16(b, false)); - let value_signed = - i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_)))); - let mut result = if let Scalar::Int(_) = s { - value_signed.to_string() - } else { - value.to_string() - }; - if value >= 10 { - format_to!(result, " ({value:#X})"); - return Ok(result); - } else { - return Ok(result); - } - } - } + if let TyKind::Scalar(s) = data.ty.kind(Interner) + && matches!(s, Scalar::Int(_) | Scalar::Uint(_)) + && let hir_ty::ConstValue::Concrete(c) = &data.value + && let hir_ty::ConstScalar::Bytes(b, _) = &c.interned + { + let value = u128::from_le_bytes(mir::pad16(b, false)); + let value_signed = i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_)))); + let mut result = + if let Scalar::Int(_) = s { value_signed.to_string() } else { value.to_string() }; + if value >= 10 { + format_to!(result, " ({value:#X})"); + return Ok(result); + } else { + return Ok(result); } } mir::render_const_using_debug_impl(db, self.def, &self.const_) @@ -4421,10 +4415,10 @@ impl Impl { let impls = db.trait_impls_in_crate(id); all.extend(impls.for_trait(trait_.id).map(Self::from)) } - if let Some(block) = module.id.containing_block() { - if let Some(trait_impls) = db.trait_impls_in_block(block) { - all.extend(trait_impls.for_trait(trait_.id).map(Self::from)); - } + if let Some(block) = module.id.containing_block() + && let Some(trait_impls) = db.trait_impls_in_block(block) + { + all.extend(trait_impls.for_trait(trait_.id).map(Self::from)); } all } diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index adba59236a40..d207305b4c61 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -933,19 +933,18 @@ impl<'db> SemanticsImpl<'db> { InFile::new(file.file_id, last), false, &mut |InFile { value: last, file_id: last_fid }, _ctx| { - if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() { - if first_fid == last_fid { - if let Some(p) = first.parent() { - let range = first.text_range().cover(last.text_range()); - let node = find_root(&p) - .covering_element(range) - .ancestors() - .take_while(|it| it.text_range() == range) - .find_map(N::cast); - if let Some(node) = node { - res.push(node); - } - } + if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() + && first_fid == last_fid + && let Some(p) = first.parent() + { + let range = first.text_range().cover(last.text_range()); + let node = find_root(&p) + .covering_element(range) + .ancestors() + .take_while(|it| it.text_range() == range) + .find_map(N::cast); + if let Some(node) = node { + res.push(node); } } }, @@ -1391,10 +1390,10 @@ impl<'db> SemanticsImpl<'db> { } })() .is_none(); - if was_not_remapped { - if let ControlFlow::Break(b) = f(InFile::new(expansion, token), ctx) { - return Some(b); - } + if was_not_remapped + && let ControlFlow::Break(b) = f(InFile::new(expansion, token), ctx) + { + return Some(b); } } } @@ -2068,14 +2067,12 @@ impl<'db> SemanticsImpl<'db> { break false; } - if let Some(parent) = ast::Expr::cast(parent.clone()) { - if let Some(ExprOrPatId::ExprId(expr_id)) = + if let Some(parent) = ast::Expr::cast(parent.clone()) + && let Some(ExprOrPatId::ExprId(expr_id)) = source_map.node_expr(InFile { file_id, value: &parent }) - { - if let Expr::Unsafe { .. } = body[expr_id] { - break true; - } - } + && let Expr::Unsafe { .. } = body[expr_id] + { + break true; } let Some(parent_) = parent.parent() else { break false }; @@ -2354,32 +2351,30 @@ struct RenameConflictsVisitor<'a> { impl RenameConflictsVisitor<'_> { fn resolve_path(&mut self, node: ExprOrPatId, path: &Path) { - if let Path::BarePath(path) = path { - if let Some(name) = path.as_ident() { - if *name.symbol() == self.new_name { - if let Some(conflicting) = self.resolver.rename_will_conflict_with_renamed( - self.db, - name, - path, - self.body.expr_or_pat_path_hygiene(node), - self.to_be_renamed, - ) { - self.conflicts.insert(conflicting); - } - } else if *name.symbol() == self.old_name { - if let Some(conflicting) = - self.resolver.rename_will_conflict_with_another_variable( - self.db, - name, - path, - self.body.expr_or_pat_path_hygiene(node), - &self.new_name, - self.to_be_renamed, - ) - { - self.conflicts.insert(conflicting); - } + if let Path::BarePath(path) = path + && let Some(name) = path.as_ident() + { + if *name.symbol() == self.new_name { + if let Some(conflicting) = self.resolver.rename_will_conflict_with_renamed( + self.db, + name, + path, + self.body.expr_or_pat_path_hygiene(node), + self.to_be_renamed, + ) { + self.conflicts.insert(conflicting); } + } else if *name.symbol() == self.old_name + && let Some(conflicting) = self.resolver.rename_will_conflict_with_another_variable( + self.db, + name, + path, + self.body.expr_or_pat_path_hygiene(node), + &self.new_name, + self.to_be_renamed, + ) + { + self.conflicts.insert(conflicting); } } } diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 0b554a9d4e37..d25fb1d8cdb7 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -995,11 +995,11 @@ impl<'db> SourceAnalyzer<'db> { // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are // trying to resolve foo::bar. - if let Some(use_tree) = parent().and_then(ast::UseTree::cast) { - if use_tree.coloncolon_token().is_some() { - return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) - .map(|it| (it, None)); - } + if let Some(use_tree) = parent().and_then(ast::UseTree::cast) + && use_tree.coloncolon_token().is_some() + { + return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) + .map(|it| (it, None)); } let meta_path = path @@ -1035,24 +1035,19 @@ impl<'db> SourceAnalyzer<'db> { // } // ``` Some(it) if matches!(it, PathResolution::Def(ModuleDef::BuiltinType(_))) => { - if let Some(mod_path) = hir_path.mod_path() { - if let Some(ModuleDefId::ModuleId(id)) = + if let Some(mod_path) = hir_path.mod_path() + && let Some(ModuleDefId::ModuleId(id)) = self.resolver.resolve_module_path_in_items(db, mod_path).take_types() + { + let parent_hir_name = parent_hir_path.segments().get(1).map(|it| it.name); + let module = crate::Module { id }; + if module + .scope(db, None) + .into_iter() + .any(|(name, _)| Some(&name) == parent_hir_name) { - let parent_hir_name = - parent_hir_path.segments().get(1).map(|it| it.name); - let module = crate::Module { id }; - if module - .scope(db, None) - .into_iter() - .any(|(name, _)| Some(&name) == parent_hir_name) - { - return Some(( - PathResolution::Def(ModuleDef::Module(module)), - None, - )); - }; - } + return Some((PathResolution::Def(ModuleDef::Module(module)), None)); + }; } Some((it, None)) } @@ -1282,22 +1277,22 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, macro_expr: InFile<&ast::MacroExpr>, ) -> bool { - if let Some((def, body, sm, Some(infer))) = self.body_() { - if let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr) { - let mut is_unsafe = false; - let mut walk_expr = |expr_id| { - unsafe_operations(db, infer, def, body, expr_id, &mut |inside_unsafe_block| { - is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No - }) - }; - match expanded_expr { - ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr), - ExprOrPatId::PatId(expanded_pat) => { - body.walk_exprs_in_pat(expanded_pat, &mut walk_expr) - } + if let Some((def, body, sm, Some(infer))) = self.body_() + && let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr) + { + let mut is_unsafe = false; + let mut walk_expr = |expr_id| { + unsafe_operations(db, infer, def, body, expr_id, &mut |inside_unsafe_block| { + is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No + }) + }; + match expanded_expr { + ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr), + ExprOrPatId::PatId(expanded_pat) => { + body.walk_exprs_in_pat(expanded_pat, &mut walk_expr) } - return is_unsafe; } + return is_unsafe; } false } @@ -1575,12 +1570,11 @@ fn resolve_hir_path_( // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type // within the trait's associated types. - if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { - if let Some(type_alias_id) = + if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) + && let Some(type_alias_id) = trait_id.trait_items(db).associated_type_by_name(unresolved.name) - { - return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); - } + { + return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); } let res = match ty { @@ -1726,12 +1720,11 @@ fn resolve_hir_path_qualifier( // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type // within the trait's associated types. - if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { - if let Some(type_alias_id) = + if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) + && let Some(type_alias_id) = trait_id.trait_items(db).associated_type_by_name(unresolved.name) - { - return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); - } + { + return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); } let res = match ty { diff --git a/crates/hir/src/term_search.rs b/crates/hir/src/term_search.rs index 4b354e640628..e4089218305c 100644 --- a/crates/hir/src/term_search.rs +++ b/crates/hir/src/term_search.rs @@ -122,10 +122,10 @@ impl<'db> LookupTable<'db> { } // Collapse suggestions if there are many - if let Some(res) = &res { - if res.len() > self.many_threshold { - return Some(vec![Expr::Many(ty.clone())]); - } + if let Some(res) = &res + && res.len() > self.many_threshold + { + return Some(vec![Expr::Many(ty.clone())]); } res @@ -160,10 +160,10 @@ impl<'db> LookupTable<'db> { } // Collapse suggestions if there are many - if let Some(res) = &res { - if res.len() > self.many_threshold { - return Some(vec![Expr::Many(ty.clone())]); - } + if let Some(res) = &res + && res.len() > self.many_threshold + { + return Some(vec![Expr::Many(ty.clone())]); } res diff --git a/crates/hir/src/term_search/expr.rs b/crates/hir/src/term_search/expr.rs index 843831948adc..78f534d014b9 100644 --- a/crates/hir/src/term_search/expr.rs +++ b/crates/hir/src/term_search/expr.rs @@ -336,10 +336,10 @@ impl<'db> Expr<'db> { if let Expr::Method { func, params, .. } = self { res.extend(params.iter().flat_map(|it| it.traits_used(db))); - if let Some(it) = func.as_assoc_item(db) { - if let Some(it) = it.container_or_implemented_trait(db) { - res.push(it); - } + if let Some(it) = func.as_assoc_item(db) + && let Some(it) = it.container_or_implemented_trait(db) + { + res.push(it); } } diff --git a/crates/ide-assists/src/handlers/add_lifetime_to_type.rs b/crates/ide-assists/src/handlers/add_lifetime_to_type.rs index dcdc7ea9cdce..27dbdcf2c4d5 100644 --- a/crates/ide-assists/src/handlers/add_lifetime_to_type.rs +++ b/crates/ide-assists/src/handlers/add_lifetime_to_type.rs @@ -82,10 +82,10 @@ fn fetch_borrowed_types(node: &ast::Adt) -> Option> { record_field_list .fields() .filter_map(|r_field| { - if let ast::Type::RefType(ref_type) = r_field.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = r_field.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None @@ -102,10 +102,10 @@ fn find_ref_types_from_field_list(field_list: &ast::FieldList) -> Option record_list .fields() .filter_map(|f| { - if let ast::Type::RefType(ref_type) = f.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = f.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None @@ -114,10 +114,10 @@ fn find_ref_types_from_field_list(field_list: &ast::FieldList) -> Option tuple_field_list .fields() .filter_map(|f| { - if let ast::Type::RefType(ref_type) = f.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = f.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None diff --git a/crates/ide-assists/src/handlers/add_missing_impl_members.rs b/crates/ide-assists/src/handlers/add_missing_impl_members.rs index ab183ac70895..7f1e7ccb4487 100644 --- a/crates/ide-assists/src/handlers/add_missing_impl_members.rs +++ b/crates/ide-assists/src/handlers/add_missing_impl_members.rs @@ -201,14 +201,12 @@ fn add_missing_impl_members_inner( if let Some(cap) = ctx.config.snippet_cap { let mut placeholder = None; - if let DefaultMethods::No = mode { - if let Some(ast::AssocItem::Fn(func)) = &first_new_item { - if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) - && m.syntax().text() == "todo!()" - { - placeholder = Some(m); - } - } + if let DefaultMethods::No = mode + && let Some(ast::AssocItem::Fn(func)) = &first_new_item + && let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) + && m.syntax().text() == "todo!()" + { + placeholder = Some(m); } if let Some(macro_call) = placeholder { diff --git a/crates/ide-assists/src/handlers/apply_demorgan.rs b/crates/ide-assists/src/handlers/apply_demorgan.rs index 3b447d1f6d57..753a9e56c35a 100644 --- a/crates/ide-assists/src/handlers/apply_demorgan.rs +++ b/crates/ide-assists/src/handlers/apply_demorgan.rs @@ -207,10 +207,10 @@ pub(crate) fn apply_demorgan_iterator(acc: &mut Assists, ctx: &AssistContext<'_> // negate all tail expressions in the closure body let tail_cb = &mut |e: &_| tail_cb_impl(&mut editor, &make, e); walk_expr(&closure_body, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&closure_body, tail_cb); diff --git a/crates/ide-assists/src/handlers/convert_bool_then.rs b/crates/ide-assists/src/handlers/convert_bool_then.rs index d7b7e8d9cad0..9d5d3f223707 100644 --- a/crates/ide-assists/src/handlers/convert_bool_then.rs +++ b/crates/ide-assists/src/handlers/convert_bool_then.rs @@ -86,12 +86,11 @@ pub(crate) fn convert_if_to_bool_then(acc: &mut Assists, ctx: &AssistContext<'_> e @ ast::Expr::CallExpr(_) => Some(e.clone()), _ => None, }; - if let Some(ast::Expr::CallExpr(call)) = e { - if let Some(arg_list) = call.arg_list() { - if let Some(arg) = arg_list.args().next() { - editor.replace(call.syntax(), arg.syntax()); - } - } + if let Some(ast::Expr::CallExpr(call)) = e + && let Some(arg_list) = call.arg_list() + && let Some(arg) = arg_list.args().next() + { + editor.replace(call.syntax(), arg.syntax()); } }); let edit = editor.finish(); @@ -276,12 +275,12 @@ fn is_invalid_body( e @ ast::Expr::CallExpr(_) => Some(e.clone()), _ => None, }; - if let Some(ast::Expr::CallExpr(call)) = e { - if let Some(ast::Expr::PathExpr(p)) = call.expr() { - let res = p.path().and_then(|p| sema.resolve_path(&p)); - if let Some(hir::PathResolution::Def(hir::ModuleDef::Variant(v))) = res { - return invalid |= v != some_variant; - } + if let Some(ast::Expr::CallExpr(call)) = e + && let Some(ast::Expr::PathExpr(p)) = call.expr() + { + let res = p.path().and_then(|p| sema.resolve_path(&p)); + if let Some(hir::PathResolution::Def(hir::ModuleDef::Variant(v))) = res { + return invalid |= v != some_variant; } } invalid = true diff --git a/crates/ide-assists/src/handlers/convert_closure_to_fn.rs b/crates/ide-assists/src/handlers/convert_closure_to_fn.rs index 43515de71e20..916bb67ebb40 100644 --- a/crates/ide-assists/src/handlers/convert_closure_to_fn.rs +++ b/crates/ide-assists/src/handlers/convert_closure_to_fn.rs @@ -101,21 +101,21 @@ pub(crate) fn convert_closure_to_fn(acc: &mut Assists, ctx: &AssistContext<'_>) // but we need to locate `AstPtr`s inside the body. let mut wrap_body_in_block = true; if let ast::Expr::BlockExpr(block) = &body { - if let Some(async_token) = block.async_token() { - if !is_async { - is_async = true; - ret_ty = ret_ty.future_output(ctx.db())?; - let token_idx = async_token.index(); - let whitespace_tokens_after_count = async_token - .siblings_with_tokens(Direction::Next) - .skip(1) - .take_while(|token| token.kind() == SyntaxKind::WHITESPACE) - .count(); - body.syntax().splice_children( - token_idx..token_idx + whitespace_tokens_after_count + 1, - Vec::new(), - ); - } + if let Some(async_token) = block.async_token() + && !is_async + { + is_async = true; + ret_ty = ret_ty.future_output(ctx.db())?; + let token_idx = async_token.index(); + let whitespace_tokens_after_count = async_token + .siblings_with_tokens(Direction::Next) + .skip(1) + .take_while(|token| token.kind() == SyntaxKind::WHITESPACE) + .count(); + body.syntax().splice_children( + token_idx..token_idx + whitespace_tokens_after_count + 1, + Vec::new(), + ); } if let Some(gen_token) = block.gen_token() { is_gen = true; @@ -513,10 +513,10 @@ fn capture_as_arg(ctx: &AssistContext<'_>, capture: &ClosureCapture) -> ast::Exp CaptureKind::MutableRef | CaptureKind::UniqueSharedRef => true, CaptureKind::Move => return place, }; - if let ast::Expr::PrefixExpr(expr) = &place { - if expr.op_kind() == Some(ast::UnaryOp::Deref) { - return expr.expr().expect("`display_place_source_code()` produced an invalid expr"); - } + if let ast::Expr::PrefixExpr(expr) = &place + && expr.op_kind() == Some(ast::UnaryOp::Deref) + { + return expr.expr().expect("`display_place_source_code()` produced an invalid expr"); } make::expr_ref(place, needs_mut) } @@ -642,11 +642,11 @@ fn peel_blocks_and_refs_and_parens(mut expr: ast::Expr) -> ast::Expr { expr = ast::Expr::cast(parent).unwrap(); continue; } - if let Some(stmt_list) = ast::StmtList::cast(parent) { - if let Some(block) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) { - expr = ast::Expr::BlockExpr(block); - continue; - } + if let Some(stmt_list) = ast::StmtList::cast(parent) + && let Some(block) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) + { + expr = ast::Expr::BlockExpr(block); + continue; } break; } @@ -662,12 +662,11 @@ fn expr_of_pat(pat: ast::Pat) -> Option { if let Some(let_stmt) = ast::LetStmt::cast(ancestor.clone()) { break 'find_expr let_stmt.initializer(); } - if ast::MatchArm::can_cast(ancestor.kind()) { - if let Some(match_) = + if ast::MatchArm::can_cast(ancestor.kind()) + && let Some(match_) = ancestor.parent().and_then(|it| it.parent()).and_then(ast::MatchExpr::cast) - { - break 'find_expr match_.expr(); - } + { + break 'find_expr match_.expr(); } if ast::ExprStmt::can_cast(ancestor.kind()) { break; diff --git a/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs b/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs index db41927f1df2..a4742bc7bded 100644 --- a/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs +++ b/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs @@ -50,10 +50,10 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> let associated_items = impl_.assoc_item_list()?; let from_fn = associated_items.assoc_items().find_map(|item| { - if let ast::AssocItem::Fn(f) = item { - if f.name()?.text() == "from" { - return Some(f); - } + if let ast::AssocItem::Fn(f) = item + && f.name()?.text() == "from" + { + return Some(f); }; None })?; @@ -110,12 +110,11 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> )) .clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let ast::AssocItem::TypeAlias(type_alias) = &error_type { - if let Some(ty) = type_alias.ty() { - builder.add_placeholder_snippet(cap, ty); - } - } + if let Some(cap) = ctx.config.snippet_cap + && let ast::AssocItem::TypeAlias(type_alias) = &error_type + && let Some(ty) = type_alias.ty() + { + builder.add_placeholder_snippet(cap, ty); } associated_items.add_item_at_start(error_type); diff --git a/crates/ide-assists/src/handlers/convert_into_to_from.rs b/crates/ide-assists/src/handlers/convert_into_to_from.rs index b80276a95fbf..3d9cde0e0a67 100644 --- a/crates/ide-assists/src/handlers/convert_into_to_from.rs +++ b/crates/ide-assists/src/handlers/convert_into_to_from.rs @@ -65,10 +65,10 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) - }; let into_fn = impl_.assoc_item_list()?.assoc_items().find_map(|item| { - if let ast::AssocItem::Fn(f) = item { - if f.name()?.text() == "into" { - return Some(f); - } + if let ast::AssocItem::Fn(f) = item + && f.name()?.text() == "into" + { + return Some(f); }; None })?; diff --git a/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs b/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs index cca4cb9d8f77..247c1011589b 100644 --- a/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs +++ b/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs @@ -265,10 +265,10 @@ fn replace_body_return_values(body: ast::Expr, struct_name: &str) { let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); walk_expr(&body, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body, tail_cb); diff --git a/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index b27ebcaa4edf..3d78895477b3 100644 --- a/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -192,7 +192,7 @@ fn edit_struct_references( ).syntax().clone() ) }, - _ => return None, + _ => None, } } }; diff --git a/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs b/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs index e582aa814ae1..1af5db17f040 100644 --- a/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs +++ b/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs @@ -100,10 +100,10 @@ fn is_bool_literal_expr( sema: &Semantics<'_, RootDatabase>, expr: &ast::Expr, ) -> Option { - if let ast::Expr::Literal(lit) = expr { - if let ast::LiteralKind::Bool(b) = lit.kind() { - return Some(ArmBodyExpression::Literal(b)); - } + if let ast::Expr::Literal(lit) = expr + && let ast::LiteralKind::Bool(b) = lit.kind() + { + return Some(ArmBodyExpression::Literal(b)); } if !sema.type_of_expr(expr)?.original.is_bool() { diff --git a/crates/ide-assists/src/handlers/desugar_try_expr.rs b/crates/ide-assists/src/handlers/desugar_try_expr.rs index efadde9e3648..9976e34e730c 100644 --- a/crates/ide-assists/src/handlers/desugar_try_expr.rs +++ b/crates/ide-assists/src/handlers/desugar_try_expr.rs @@ -106,73 +106,73 @@ pub(crate) fn desugar_try_expr(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op }, ); - if let Some(let_stmt) = try_expr.syntax().parent().and_then(ast::LetStmt::cast) { - if let_stmt.let_else().is_none() { - let pat = let_stmt.pat()?; - acc.add( - AssistId::refactor_rewrite("desugar_try_expr_let_else"), - "Replace try expression with let else", - target, - |builder| { - let make = SyntaxFactory::with_mappings(); - let mut editor = builder.make_editor(let_stmt.syntax()); + if let Some(let_stmt) = try_expr.syntax().parent().and_then(ast::LetStmt::cast) + && let_stmt.let_else().is_none() + { + let pat = let_stmt.pat()?; + acc.add( + AssistId::refactor_rewrite("desugar_try_expr_let_else"), + "Replace try expression with let else", + target, + |builder| { + let make = SyntaxFactory::with_mappings(); + let mut editor = builder.make_editor(let_stmt.syntax()); - let indent_level = IndentLevel::from_node(let_stmt.syntax()); - let new_let_stmt = make.let_else_stmt( - try_enum.happy_pattern(pat), - let_stmt.ty(), - expr, - make.block_expr( - iter::once( - make.expr_stmt( - make.expr_return(Some(match try_enum { - TryEnum::Option => make.expr_path(make.ident_path("None")), - TryEnum::Result => make - .expr_call( - make.expr_path(make.ident_path("Err")), - make.arg_list(iter::once( - match ctx.config.expr_fill_default { - ExprFillDefaultMode::Todo => make - .expr_macro( - make.ident_path("todo"), - make.token_tree( - syntax::SyntaxKind::L_PAREN, - [], - ), - ) - .into(), - ExprFillDefaultMode::Underscore => { - make.expr_underscore().into() - } - ExprFillDefaultMode::Default => make - .expr_macro( - make.ident_path("todo"), - make.token_tree( - syntax::SyntaxKind::L_PAREN, - [], - ), - ) - .into(), - }, - )), - ) - .into(), - })) - .indent(indent_level + 1) - .into(), - ) + let indent_level = IndentLevel::from_node(let_stmt.syntax()); + let new_let_stmt = make.let_else_stmt( + try_enum.happy_pattern(pat), + let_stmt.ty(), + expr, + make.block_expr( + iter::once( + make.expr_stmt( + make.expr_return(Some(match try_enum { + TryEnum::Option => make.expr_path(make.ident_path("None")), + TryEnum::Result => make + .expr_call( + make.expr_path(make.ident_path("Err")), + make.arg_list(iter::once( + match ctx.config.expr_fill_default { + ExprFillDefaultMode::Todo => make + .expr_macro( + make.ident_path("todo"), + make.token_tree( + syntax::SyntaxKind::L_PAREN, + [], + ), + ) + .into(), + ExprFillDefaultMode::Underscore => { + make.expr_underscore().into() + } + ExprFillDefaultMode::Default => make + .expr_macro( + make.ident_path("todo"), + make.token_tree( + syntax::SyntaxKind::L_PAREN, + [], + ), + ) + .into(), + }, + )), + ) + .into(), + })) + .indent(indent_level + 1) .into(), - ), - None, - ) - .indent(indent_level), - ); - editor.replace(let_stmt.syntax(), new_let_stmt.syntax()); - editor.add_mappings(make.finish_with_mappings()); - builder.add_file_edits(ctx.vfs_file_id(), editor); - }, - ); - } + ) + .into(), + ), + None, + ) + .indent(indent_level), + ); + editor.replace(let_stmt.syntax(), new_let_stmt.syntax()); + editor.add_mappings(make.finish_with_mappings()); + builder.add_file_edits(ctx.vfs_file_id(), editor); + }, + ); } Some(()) } diff --git a/crates/ide-assists/src/handlers/expand_glob_import.rs b/crates/ide-assists/src/handlers/expand_glob_import.rs index 307414c79715..66552dd65f56 100644 --- a/crates/ide-assists/src/handlers/expand_glob_import.rs +++ b/crates/ide-assists/src/handlers/expand_glob_import.rs @@ -272,16 +272,16 @@ impl Refs { .clone() .into_iter() .filter(|r| { - if let Definition::Trait(tr) = r.def { - if tr.items(ctx.db()).into_iter().any(|ai| { + if let Definition::Trait(tr) = r.def + && tr.items(ctx.db()).into_iter().any(|ai| { if let AssocItem::Function(f) = ai { def_is_referenced_in(Definition::Function(f), ctx) } else { false } - }) { - return true; - } + }) + { + return true; } def_is_referenced_in(r.def, ctx) diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index 00cbef1c01c0..890b8dd64126 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -175,10 +175,10 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op let fn_def = format_function(ctx, module, &fun, old_indent).clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = fn_def.name() { - builder.add_tabstop_before(cap, name); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = fn_def.name() + { + builder.add_tabstop_before(cap, name); } let fn_def = match fun.self_param_adt(ctx) { @@ -289,10 +289,10 @@ fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option { let func = sema.to_def(&fn_)?; let mut ret_ty = func.ret_type(sema.db); - if func.is_async(sema.db) { - if let Some(async_ret) = func.async_ret_type(sema.db) { + if func.is_async(sema.db) + && let Some(async_ret) = func.async_ret_type(sema.db) { ret_ty = async_ret; } - } (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty)) }, ast::Static(statik) => { @@ -1172,19 +1171,19 @@ impl GenericParent { /// Search `parent`'s ancestors for items with potentially applicable generic parameters fn generic_parents(parent: &SyntaxNode) -> Vec { let mut list = Vec::new(); - if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) { - if let ast::Item::Fn(ref fn_) = parent_item { - if let Some(parent_parent) = - parent_item.syntax().parent().and_then(|it| it.parent()).and_then(ast::Item::cast) - { - match parent_parent { - ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)), - ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)), - _ => (), - } + if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) + && let ast::Item::Fn(ref fn_) = parent_item + { + if let Some(parent_parent) = + parent_item.syntax().parent().and_then(|it| it.parent()).and_then(ast::Item::cast) + { + match parent_parent { + ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)), + ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)), + _ => (), } - list.push(GenericParent::Fn(fn_.clone())); } + list.push(GenericParent::Fn(fn_.clone())); } list } @@ -1337,10 +1336,10 @@ fn locals_defined_in_body( // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550 let mut res = FxIndexSet::default(); body.walk_pat(&mut |pat| { - if let ast::Pat::IdentPat(pat) = pat { - if let Some(local) = sema.to_def(&pat) { - res.insert(local); - } + if let ast::Pat::IdentPat(pat) = pat + && let Some(local) = sema.to_def(&pat) + { + res.insert(local); } }); res @@ -1445,11 +1444,11 @@ fn impl_type_name(impl_node: &ast::Impl) -> Option { fn fixup_call_site(builder: &mut SourceChangeBuilder, body: &FunctionBody) { let parent_match_arm = body.parent().and_then(ast::MatchArm::cast); - if let Some(parent_match_arm) = parent_match_arm { - if parent_match_arm.comma_token().is_none() { - let parent_match_arm = builder.make_mut(parent_match_arm); - ted::append_child_raw(parent_match_arm.syntax(), make::token(T![,])); - } + if let Some(parent_match_arm) = parent_match_arm + && parent_match_arm.comma_token().is_none() + { + let parent_match_arm = builder.make_mut(parent_match_arm); + ted::append_child_raw(parent_match_arm.syntax(), make::token(T![,])); } } @@ -2120,30 +2119,30 @@ fn update_external_control_flow(handler: &FlowHandler<'_>, syntax: &SyntaxNode) _ => {} }, WalkEvent::Leave(e) => { - if nested_scope.is_none() { - if let Some(expr) = ast::Expr::cast(e.clone()) { - match expr { - ast::Expr::ReturnExpr(return_expr) => { - let expr = return_expr.expr(); - if let Some(replacement) = make_rewritten_flow(handler, expr) { - ted::replace(return_expr.syntax(), replacement.syntax()) - } - } - ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => { - let expr = break_expr.expr(); - if let Some(replacement) = make_rewritten_flow(handler, expr) { - ted::replace(break_expr.syntax(), replacement.syntax()) - } + if nested_scope.is_none() + && let Some(expr) = ast::Expr::cast(e.clone()) + { + match expr { + ast::Expr::ReturnExpr(return_expr) => { + let expr = return_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + ted::replace(return_expr.syntax(), replacement.syntax()) } - ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => { - if let Some(replacement) = make_rewritten_flow(handler, None) { - ted::replace(continue_expr.syntax(), replacement.syntax()) - } + } + ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => { + let expr = break_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + ted::replace(break_expr.syntax(), replacement.syntax()) } - _ => { - // do nothing + } + ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => { + if let Some(replacement) = make_rewritten_flow(handler, None) { + ted::replace(continue_expr.syntax(), replacement.syntax()) } } + _ => { + // do nothing + } } } diff --git a/crates/ide-assists/src/handlers/extract_module.rs b/crates/ide-assists/src/handlers/extract_module.rs index b82b7984d4a4..c6a6b97df824 100644 --- a/crates/ide-assists/src/handlers/extract_module.rs +++ b/crates/ide-assists/src/handlers/extract_module.rs @@ -69,13 +69,12 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti let mut impl_parent: Option = None; let mut impl_child_count: usize = 0; - if let Some(parent_assoc_list) = node.parent() { - if let Some(parent_impl) = parent_assoc_list.parent() { - if let Some(impl_) = ast::Impl::cast(parent_impl) { - impl_child_count = parent_assoc_list.children().count(); - impl_parent = Some(impl_); - } - } + if let Some(parent_assoc_list) = node.parent() + && let Some(parent_impl) = parent_assoc_list.parent() + && let Some(impl_) = ast::Impl::cast(parent_impl) + { + impl_child_count = parent_assoc_list.children().count(); + impl_parent = Some(impl_); } let mut curr_parent_module: Option = None; @@ -436,10 +435,10 @@ impl Module { } }) .for_each(|(node, def)| { - if node_set.insert(node.to_string()) { - if let Some(import) = self.process_def_in_sel(def, &node, &module, ctx) { - check_intersection_and_push(&mut imports_to_remove, import); - } + if node_set.insert(node.to_string()) + && let Some(import) = self.process_def_in_sel(def, &node, &module, ctx) + { + check_intersection_and_push(&mut imports_to_remove, import); } }) } @@ -542,15 +541,16 @@ impl Module { import_path_to_be_removed = Some(text_range); } - if def_in_mod && def_out_sel { - if let Some(first_path_in_use_tree) = use_tree_str.last() { - let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); - if !first_path_in_use_tree_str.contains("super") - && !first_path_in_use_tree_str.contains("crate") - { - let super_path = make::ext::ident_path("super"); - use_tree_str.push(super_path); - } + if def_in_mod + && def_out_sel + && let Some(first_path_in_use_tree) = use_tree_str.last() + { + let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); + if !first_path_in_use_tree_str.contains("super") + && !first_path_in_use_tree_str.contains("crate") + { + let super_path = make::ext::ident_path("super"); + use_tree_str.push(super_path); } } @@ -563,12 +563,11 @@ impl Module { if let Some(mut use_tree_paths) = use_tree_paths { use_tree_paths.reverse(); - if uses_exist_out_sel || !uses_exist_in_sel || !def_in_mod || !def_out_sel { - if let Some(first_path_in_use_tree) = use_tree_paths.first() { - if first_path_in_use_tree.to_string().contains("super") { - use_tree_paths.insert(0, make::ext::ident_path("super")); - } - } + if (uses_exist_out_sel || !uses_exist_in_sel || !def_in_mod || !def_out_sel) + && let Some(first_path_in_use_tree) = use_tree_paths.first() + && first_path_in_use_tree.to_string().contains("super") + { + use_tree_paths.insert(0, make::ext::ident_path("super")); } let is_item = matches!( @@ -691,11 +690,9 @@ fn check_def_in_mod_and_out_sel( _ => source.file_id.original_file(ctx.db()).file_id(ctx.db()) == curr_file_id, }; - if have_same_parent { - if let ModuleSource::Module(module_) = source.value { - let in_sel = !selection_range.contains_range(module_.syntax().text_range()); - return (have_same_parent, in_sel); - } + if have_same_parent && let ModuleSource::Module(module_) = source.value { + let in_sel = !selection_range.contains_range(module_.syntax().text_range()); + return (have_same_parent, in_sel); } return (have_same_parent, false); @@ -772,12 +769,12 @@ fn get_use_tree_paths_from_path( .filter(|x| x.to_string() != path.to_string()) .filter_map(ast::UseTree::cast) .find_map(|use_tree| { - if let Some(upper_tree_path) = use_tree.path() { - if upper_tree_path.to_string() != path.to_string() { - use_tree_str.push(upper_tree_path.clone()); - get_use_tree_paths_from_path(upper_tree_path, use_tree_str); - return Some(use_tree); - } + if let Some(upper_tree_path) = use_tree.path() + && upper_tree_path.to_string() != path.to_string() + { + use_tree_str.push(upper_tree_path.clone()); + get_use_tree_paths_from_path(upper_tree_path, use_tree_str); + return Some(use_tree); } None })?; @@ -786,11 +783,11 @@ fn get_use_tree_paths_from_path( } fn add_change_vis(vis: Option, node_or_token_opt: Option) { - if vis.is_none() { - if let Some(node_or_token) = node_or_token_opt { - let pub_crate_vis = make::visibility_pub_crate().clone_for_update(); - ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax()); - } + if vis.is_none() + && let Some(node_or_token) = node_or_token_opt + { + let pub_crate_vis = make::visibility_pub_crate().clone_for_update(); + ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax()); } } diff --git a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index 9095b1825f5f..c56d0b3de5d6 100644 --- a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -215,12 +215,12 @@ fn tag_generics_in_variant(ty: &ast::Type, generics: &mut [(ast::GenericParam, b ast::GenericParam::LifetimeParam(lt) if matches!(token.kind(), T![lifetime_ident]) => { - if let Some(lt) = lt.lifetime() { - if lt.text().as_str() == token.text() { - *tag = true; - tagged_one = true; - break; - } + if let Some(lt) = lt.lifetime() + && lt.text().as_str() == token.text() + { + *tag = true; + tagged_one = true; + break; } } param if matches!(token.kind(), T![ident]) => { diff --git a/crates/ide-assists/src/handlers/extract_type_alias.rs b/crates/ide-assists/src/handlers/extract_type_alias.rs index d843ac64567a..79f22381952a 100644 --- a/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -72,10 +72,10 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) -> let ty_alias = make::ty_alias("Type", generic_params, None, None, Some((ty, None))) .clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = ty_alias.name() { - edit.add_annotation(name.syntax(), builder.make_tabstop_before(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = ty_alias.name() + { + edit.add_annotation(name.syntax(), builder.make_tabstop_before(cap)); } let indent = IndentLevel::from_node(node); @@ -111,17 +111,17 @@ fn collect_used_generics<'gp>( match ty { ast::Type::PathType(ty) => { if let Some(path) = ty.path() { - if let Some(name_ref) = path.as_single_name_ref() { - if let Some(param) = known_generics.iter().find(|gp| { + if let Some(name_ref) = path.as_single_name_ref() + && let Some(param) = known_generics.iter().find(|gp| { match gp { ast::GenericParam::ConstParam(cp) => cp.name(), ast::GenericParam::TypeParam(tp) => tp.name(), _ => None, } .is_some_and(|n| n.text() == name_ref.text()) - }) { - generics.push(param); - } + }) + { + generics.push(param); } generics.extend( path.segments() @@ -160,20 +160,18 @@ fn collect_used_generics<'gp>( .and_then(|lt| known_generics.iter().find(find_lifetime(<.text()))), ), ast::Type::ArrayType(ar) => { - if let Some(ast::Expr::PathExpr(p)) = ar.const_arg().and_then(|x| x.expr()) { - if let Some(path) = p.path() { - 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().is_some_and(|n| n.text() == name_ref.text()) - } else { - false - } - }) { - generics.push(param); - } + if let Some(ast::Expr::PathExpr(p)) = ar.const_arg().and_then(|x| x.expr()) + && let Some(path) = p.path() + && let Some(name_ref) = path.as_single_name_ref() + && let Some(param) = known_generics.iter().find(|gp| { + if let ast::GenericParam::ConstParam(cp) = gp { + cp.name().is_some_and(|n| n.text() == name_ref.text()) + } else { + false } - } + }) + { + generics.push(param); } } _ => (), diff --git a/crates/ide-assists/src/handlers/extract_variable.rs b/crates/ide-assists/src/handlers/extract_variable.rs index db2d316d58ee..c9c1969b9e02 100644 --- a/crates/ide-assists/src/handlers/extract_variable.rs +++ b/crates/ide-assists/src/handlers/extract_variable.rs @@ -404,11 +404,10 @@ impl Anchor { } if let Some(expr) = node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr()) + && expr.syntax() == &node { - if expr.syntax() == &node { - cov_mark::hit!(test_extract_var_last_expr); - return Some(Anchor::Before(node)); - } + cov_mark::hit!(test_extract_var_last_expr); + return Some(Anchor::Before(node)); } if let Some(parent) = node.parent() { @@ -427,10 +426,10 @@ impl Anchor { } if let Some(stmt) = ast::Stmt::cast(node.clone()) { - if let ast::Stmt::ExprStmt(stmt) = stmt { - if stmt.expr().as_ref() == Some(to_extract) { - return Some(Anchor::Replace(stmt)); - } + if let ast::Stmt::ExprStmt(stmt) = stmt + && stmt.expr().as_ref() == Some(to_extract) + { + return Some(Anchor::Replace(stmt)); } return Some(Anchor::Before(node)); } diff --git a/crates/ide-assists/src/handlers/generate_documentation_template.rs b/crates/ide-assists/src/handlers/generate_documentation_template.rs index 68587f0cb5bc..77232dfebdfe 100644 --- a/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -148,11 +148,11 @@ fn make_example_for_fn(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option) -> Option) ], ); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = ty_alias.name() { - edit.add_annotation(name.syntax(), builder.make_placeholder_snippet(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = ty_alias.name() + { + edit.add_annotation(name.syntax(), builder.make_placeholder_snippet(cap)); } builder.add_file_edits(ctx.vfs_file_id(), edit); diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs index 3290a70e1c69..613b32fcc165 100644 --- a/crates/ide-assists/src/handlers/generate_function.rs +++ b/crates/ide-assists/src/handlers/generate_function.rs @@ -70,10 +70,10 @@ fn gen_fn(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let TargetInfo { target_module, adt_info, target, file } = fn_target_info(ctx, path, &call, fn_name)?; - if let Some(m) = target_module { - if !is_editable_crate(m.krate(), ctx.db()) { - return None; - } + if let Some(m) = target_module + && !is_editable_crate(m.krate(), ctx.db()) + { + return None; } let function_builder = 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 20ee9253d379..807b9194b2df 100644 --- a/crates/ide-assists/src/handlers/generate_getter_or_setter.rs +++ b/crates/ide-assists/src/handlers/generate_getter_or_setter.rs @@ -433,12 +433,11 @@ fn build_source_change( new_fn.indent(1.into()); // Insert a tabstop only for last method we generate - if i == record_fields_count - 1 { - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = new_fn.name() { - builder.add_tabstop_before(cap, name); - } - } + if i == record_fields_count - 1 + && let Some(cap) = ctx.config.snippet_cap + && let Some(name) = new_fn.name() + { + builder.add_tabstop_before(cap, name); } assoc_item_list.add_item(new_fn.clone().into()); diff --git a/crates/ide-assists/src/handlers/generate_impl.rs b/crates/ide-assists/src/handlers/generate_impl.rs index 31cadcf5ea86..fcb81d239ff3 100644 --- a/crates/ide-assists/src/handlers/generate_impl.rs +++ b/crates/ide-assists/src/handlers/generate_impl.rs @@ -58,11 +58,11 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio let mut editor = edit.make_editor(nominal.syntax()); // Add a tabstop after the left curly brace - if let Some(cap) = ctx.config.snippet_cap { - if let Some(l_curly) = impl_.assoc_item_list().and_then(|it| it.l_curly_token()) { - let tabstop = edit.make_tabstop_after(cap); - editor.add_annotation(l_curly, tabstop); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(l_curly) = impl_.assoc_item_list().and_then(|it| it.l_curly_token()) + { + let tabstop = edit.make_tabstop_after(cap); + editor.add_annotation(l_curly, tabstop); } insert_impl(&mut editor, &impl_, &nominal); 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 92a4bd35b3e7..dc3dc73701f3 100644 --- a/crates/ide-assists/src/handlers/generate_trait_from_impl.rs +++ b/crates/ide-assists/src/handlers/generate_trait_from_impl.rs @@ -175,18 +175,18 @@ fn remove_items_visibility(item: &ast::AssocItem) { } fn strip_body(item: &ast::AssocItem) { - if let ast::AssocItem::Fn(f) = item { - if let Some(body) = f.body() { - // In contrast 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()); + if let ast::AssocItem::Fn(f) = item + && let Some(body) = f.body() + { + // In contrast 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() + && prev.kind() == SyntaxKind::WHITESPACE + { + ted::remove(prev); } + + 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 1549b414dcc1..5367350052cb 100644 --- a/crates/ide-assists/src/handlers/inline_call.rs +++ b/crates/ide-assists/src/handlers/inline_call.rs @@ -393,19 +393,17 @@ fn inline( // `FileReference` incorrect if let Some(imp) = sema.ancestors_with_macros(fn_body.syntax().clone()).find_map(ast::Impl::cast) + && !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) + && let Some(t) = imp.self_ty() { - if !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) { - if let Some(t) = imp.self_ty() { - while let Some(self_tok) = body - .syntax() - .descendants_with_tokens() - .filter_map(NodeOrToken::into_token) - .find(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW) - { - let replace_with = t.clone_subtree().syntax().clone_for_update(); - ted::replace(self_tok, replace_with); - } - } + while let Some(self_tok) = body + .syntax() + .descendants_with_tokens() + .filter_map(NodeOrToken::into_token) + .find(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW) + { + let replace_with = t.clone_subtree().syntax().clone_for_update(); + ted::replace(self_tok, replace_with); } } @@ -415,10 +413,10 @@ fn inline( for stmt in fn_body.statements() { if let Some(let_stmt) = ast::LetStmt::cast(stmt.syntax().to_owned()) { for has_token in let_stmt.syntax().children_with_tokens() { - if let Some(node) = has_token.as_node() { - if let Some(ident_pat) = ast::IdentPat::cast(node.to_owned()) { - func_let_vars.insert(ident_pat.syntax().text().to_string()); - } + if let Some(node) = has_token.as_node() + && let Some(ident_pat) = ast::IdentPat::cast(node.to_owned()) + { + func_let_vars.insert(ident_pat.syntax().text().to_string()); } } } @@ -534,16 +532,15 @@ fn inline( } } - if let Some(generic_arg_list) = generic_arg_list.clone() { - if let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax())) - { - body.reindent_to(IndentLevel(0)); - if let Some(new_body) = ast::BlockExpr::cast( - PathTransform::function_call(target, source, function, generic_arg_list) - .apply(body.syntax()), - ) { - body = new_body; - } + if let Some(generic_arg_list) = generic_arg_list.clone() + && let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax())) + { + body.reindent_to(IndentLevel(0)); + if let Some(new_body) = ast::BlockExpr::cast( + PathTransform::function_call(target, source, function, generic_arg_list) + .apply(body.syntax()), + ) { + body = new_body; } } diff --git a/crates/ide-assists/src/handlers/move_const_to_impl.rs b/crates/ide-assists/src/handlers/move_const_to_impl.rs index 0c1dc9eb9349..a645c8b90afc 100644 --- a/crates/ide-assists/src/handlers/move_const_to_impl.rs +++ b/crates/ide-assists/src/handlers/move_const_to_impl.rs @@ -43,10 +43,10 @@ pub(crate) fn move_const_to_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> let db = ctx.db(); let const_: ast::Const = ctx.find_node_at_offset()?; // Don't show the assist when the cursor is at the const's body. - if let Some(body) = const_.body() { - if body.syntax().text_range().contains(ctx.offset()) { - return None; - } + if let Some(body) = const_.body() + && body.syntax().text_range().contains(ctx.offset()) + { + return None; } let parent_fn = const_.syntax().ancestors().find_map(ast::Fn::cast)?; diff --git a/crates/ide-assists/src/handlers/pull_assignment_up.rs b/crates/ide-assists/src/handlers/pull_assignment_up.rs index 1b0c31393537..21debf6745a6 100644 --- a/crates/ide-assists/src/handlers/pull_assignment_up.rs +++ b/crates/ide-assists/src/handlers/pull_assignment_up.rs @@ -62,10 +62,10 @@ pub(crate) fn pull_assignment_up(acc: &mut Assists, ctx: &AssistContext<'_>) -> return None; }; - if let Some(parent) = tgt.syntax().parent() { - if matches!(parent.kind(), syntax::SyntaxKind::BIN_EXPR | syntax::SyntaxKind::LET_STMT) { - return None; - } + if let Some(parent) = tgt.syntax().parent() + && matches!(parent.kind(), syntax::SyntaxKind::BIN_EXPR | syntax::SyntaxKind::LET_STMT) + { + return None; } let target = tgt.syntax().text_range(); @@ -90,10 +90,10 @@ pub(crate) fn pull_assignment_up(acc: &mut Assists, ctx: &AssistContext<'_>) -> let mut editor = SyntaxEditor::new(edit_tgt); for (stmt, rhs) in assignments { let mut stmt = stmt.syntax().clone(); - if let Some(parent) = stmt.parent() { - if ast::ExprStmt::cast(parent.clone()).is_some() { - stmt = parent.clone(); - } + if let Some(parent) = stmt.parent() + && ast::ExprStmt::cast(parent.clone()).is_some() + { + stmt = parent.clone(); } editor.replace(stmt, rhs.syntax()); } diff --git a/crates/ide-assists/src/handlers/raw_string.rs b/crates/ide-assists/src/handlers/raw_string.rs index 94b49c5df091..2cbb24a64fd5 100644 --- a/crates/ide-assists/src/handlers/raw_string.rs +++ b/crates/ide-assists/src/handlers/raw_string.rs @@ -80,15 +80,15 @@ pub(crate) fn make_usual_string(acc: &mut Assists, ctx: &AssistContext<'_>) -> O // parse inside string to escape `"` let escaped = value.escape_default().to_string(); let suffix = string_suffix(token.text()).unwrap_or_default(); - if let Some(offsets) = token.quote_offsets() { - if token.text()[offsets.contents - token.syntax().text_range().start()] == escaped { - let end_quote = offsets.quotes.1; - let end_quote = - TextRange::new(end_quote.start(), end_quote.end() - TextSize::of(suffix)); - edit.replace(offsets.quotes.0, "\""); - edit.replace(end_quote, "\""); - return; - } + if let Some(offsets) = token.quote_offsets() + && token.text()[offsets.contents - token.syntax().text_range().start()] == escaped + { + let end_quote = offsets.quotes.1; + let end_quote = + TextRange::new(end_quote.start(), end_quote.end() - TextSize::of(suffix)); + edit.replace(offsets.quotes.0, "\""); + edit.replace(end_quote, "\""); + return; } edit.replace(token.syntax().text_range(), format!("\"{escaped}\"{suffix}")); diff --git a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs index fa005a411d36..9f742131e5cb 100644 --- a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs +++ b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs @@ -102,10 +102,10 @@ pub(crate) fn replace_qualified_name_with_use( fn drop_generic_args(path: &ast::Path) -> ast::Path { let path = path.clone_for_update(); - if let Some(segment) = path.segment() { - if let Some(generic_args) = segment.generic_arg_list() { - ted::remove(generic_args.syntax()); - } + if let Some(segment) = path.segment() + && let Some(generic_args) = segment.generic_arg_list() + { + ted::remove(generic_args.syntax()); } path } diff --git a/crates/ide-assists/src/handlers/unnecessary_async.rs b/crates/ide-assists/src/handlers/unnecessary_async.rs index ac10a829bbf1..b9385775b476 100644 --- a/crates/ide-assists/src/handlers/unnecessary_async.rs +++ b/crates/ide-assists/src/handlers/unnecessary_async.rs @@ -41,10 +41,10 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_>) -> O 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 impl_.trait_().is_some() { - return None; - } + if let Some(impl_) = function.syntax().ancestors().nth(2).and_then(ast::Impl::cast) + && impl_.trait_().is_some() + { + return None; } // Remove the `async` keyword plus whitespace after it, if any. diff --git a/crates/ide-assists/src/handlers/unwrap_return_type.rs b/crates/ide-assists/src/handlers/unwrap_return_type.rs index cf38262fbf44..eea6c85e8df0 100644 --- a/crates/ide-assists/src/handlers/unwrap_return_type.rs +++ b/crates/ide-assists/src/handlers/unwrap_return_type.rs @@ -72,20 +72,20 @@ pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> let mut exprs_to_unwrap = Vec::new(); let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); walk_expr(&body_expr, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body_expr, tail_cb); let is_unit_type = is_unit_type(&happy_type); if is_unit_type { - if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { - if token.kind() == SyntaxKind::WHITESPACE { - editor.delete(token); - } + if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() + && token.kind() == SyntaxKind::WHITESPACE + { + editor.delete(token); } editor.delete(ret_type.syntax()); @@ -162,10 +162,10 @@ pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> } } - if let Some(cap) = ctx.config.snippet_cap { - if let Some(final_placeholder) = final_placeholder { - editor.add_annotation(final_placeholder.syntax(), builder.make_tabstop_after(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(final_placeholder) = final_placeholder + { + editor.add_annotation(final_placeholder.syntax(), builder.make_tabstop_after(cap)); } editor.add_mappings(make.finish_with_mappings()); diff --git a/crates/ide-assists/src/handlers/unwrap_tuple.rs b/crates/ide-assists/src/handlers/unwrap_tuple.rs index ecfecbb04ff2..46f3e85e1234 100644 --- a/crates/ide-assists/src/handlers/unwrap_tuple.rs +++ b/crates/ide-assists/src/handlers/unwrap_tuple.rs @@ -47,10 +47,10 @@ pub(crate) fn unwrap_tuple(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option if tuple_pat.fields().count() != tuple_init.fields().count() { return None; } - if let Some(tys) = &tuple_ty { - if tuple_pat.fields().count() != tys.fields().count() { - return None; - } + if let Some(tys) = &tuple_ty + && tuple_pat.fields().count() != tys.fields().count() + { + return None; } let parent = let_kw.parent()?; diff --git a/crates/ide-assists/src/handlers/wrap_return_type.rs b/crates/ide-assists/src/handlers/wrap_return_type.rs index d7189aa5dbbd..0f089c9b66eb 100644 --- a/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -101,24 +101,24 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op let mut exprs_to_wrap = Vec::new(); let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); walk_expr(&body_expr, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body_expr, tail_cb); for ret_expr_arg in exprs_to_wrap { - if let Some(ty) = ctx.sema.type_of_expr(&ret_expr_arg) { - if ty.adjusted().could_unify_with(ctx.db(), &semantic_new_return_ty) { - // The type is already correct, don't wrap it. - // We deliberately don't use `could_unify_with_deeply()`, because as long as the outer - // enum matches it's okay for us, as we don't trigger the assist if the return type - // is already `Option`/`Result`, so mismatched exact type is more likely a mistake - // than something intended. - continue; - } + if let Some(ty) = ctx.sema.type_of_expr(&ret_expr_arg) + && ty.adjusted().could_unify_with(ctx.db(), &semantic_new_return_ty) + { + // The type is already correct, don't wrap it. + // We deliberately don't use `could_unify_with_deeply()`, because as long as the outer + // enum matches it's okay for us, as we don't trigger the assist if the return type + // is already `Option`/`Result`, so mismatched exact type is more likely a mistake + // than something intended. + continue; } let happy_wrapped = make.expr_call( @@ -147,13 +147,13 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op ast::GenericArg::LifetimeArg(_) => false, _ => true, }); - if let Some(error_type_arg) = error_type_arg { - if let Some(cap) = ctx.config.snippet_cap { - editor.add_annotation( - error_type_arg.syntax(), - builder.make_placeholder_snippet(cap), - ); - } + if let Some(error_type_arg) = error_type_arg + && let Some(cap) = ctx.config.snippet_cap + { + editor.add_annotation( + error_type_arg.syntax(), + builder.make_placeholder_snippet(cap), + ); } } diff --git a/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs b/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs index 5183566d136b..7d5740b748be 100644 --- a/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs +++ b/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs @@ -200,13 +200,12 @@ fn wrap_derive( ], ); - if let Some(snippet_cap) = ctx.config.snippet_cap { - if let Some(first_meta) = + if let Some(snippet_cap) = ctx.config.snippet_cap + && let Some(first_meta) = cfg_attr.meta().and_then(|meta| meta.token_tree()).and_then(|tt| tt.l_paren_token()) - { - let tabstop = edit.make_tabstop_after(snippet_cap); - editor.add_annotation(first_meta, tabstop); - } + { + let tabstop = edit.make_tabstop_after(snippet_cap); + editor.add_annotation(first_meta, tabstop); } editor.add_mappings(make.finish_with_mappings()); @@ -256,13 +255,12 @@ fn wrap_cfg_attr(acc: &mut Assists, ctx: &AssistContext<'_>, attr: ast::Attr) -> editor.replace(attr.syntax(), cfg_attr.syntax()); - if let Some(snippet_cap) = ctx.config.snippet_cap { - if let Some(first_meta) = + if let Some(snippet_cap) = ctx.config.snippet_cap + && let Some(first_meta) = cfg_attr.meta().and_then(|meta| meta.token_tree()).and_then(|tt| tt.l_paren_token()) - { - let tabstop = edit.make_tabstop_after(snippet_cap); - editor.add_annotation(first_meta, tabstop); - } + { + let tabstop = edit.make_tabstop_after(snippet_cap); + editor.add_annotation(first_meta, tabstop); } editor.add_mappings(make.finish_with_mappings()); diff --git a/crates/ide-assists/src/utils.rs b/crates/ide-assists/src/utils.rs index 15c7a6a3fc26..77d471e5a748 100644 --- a/crates/ide-assists/src/utils.rs +++ b/crates/ide-assists/src/utils.rs @@ -131,10 +131,10 @@ pub fn filter_assoc_items( if ignore_items == IgnoreAssocItems::DocHiddenAttrPresent && assoc_item.attrs(sema.db).has_doc_hidden() { - if let hir::AssocItem::Function(f) = assoc_item { - if !f.has_body(sema.db) { - return true; - } + if let hir::AssocItem::Function(f) = assoc_item + && !f.has_body(sema.db) + { + return true; } return false; } @@ -514,10 +514,10 @@ pub(crate) fn find_struct_impl( if !(same_ty && not_trait_impl) { None } else { Some(impl_blk) } }); - if let Some(ref impl_blk) = block { - if has_any_fn(impl_blk, names) { - return None; - } + if let Some(ref impl_blk) = block + && has_any_fn(impl_blk, names) + { + return None; } Some(block) @@ -526,12 +526,11 @@ pub(crate) fn find_struct_impl( fn has_any_fn(imp: &ast::Impl, names: &[String]) -> bool { if let Some(il) = imp.assoc_item_list() { for item in il.assoc_items() { - if let ast::AssocItem::Fn(f) = item { - if let Some(name) = f.name() { - if names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) { - return true; - } - } + if let ast::AssocItem::Fn(f) = item + && let Some(name) = f.name() + && names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) + { + return true; } } } @@ -1021,12 +1020,12 @@ pub(crate) fn trimmed_text_range(source_file: &SourceFile, initial_range: TextRa pub(crate) fn convert_param_list_to_arg_list(list: ast::ParamList) -> ast::ArgList { let mut args = vec![]; for param in list.params() { - if let Some(ast::Pat::IdentPat(pat)) = param.pat() { - if let Some(name) = pat.name() { - let name = name.to_string(); - let expr = make::expr_path(make::ext::ident_path(&name)); - args.push(expr); - } + if let Some(ast::Pat::IdentPat(pat)) = param.pat() + && let Some(name) = pat.name() + { + let name = name.to_string(); + let expr = make::expr_path(make::ext::ident_path(&name)); + args.push(expr); } } make::arg_list(args) @@ -1138,12 +1137,11 @@ pub fn is_body_const(sema: &Semantics<'_, RootDatabase>, expr: &ast::Expr) -> bo }; match expr { ast::Expr::CallExpr(call) => { - if let Some(ast::Expr::PathExpr(path_expr)) = call.expr() { - if let Some(PathResolution::Def(ModuleDef::Function(func))) = + if let Some(ast::Expr::PathExpr(path_expr)) = call.expr() + && let Some(PathResolution::Def(ModuleDef::Function(func))) = path_expr.path().and_then(|path| sema.resolve_path(&path)) - { - is_const &= func.is_const(sema.db); - } + { + is_const &= func.is_const(sema.db); } } ast::Expr::MethodCallExpr(call) => { diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index 65072d936f63..11d26228ba20 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -111,10 +111,11 @@ impl Completions { ctx: &CompletionContext<'_>, super_chain_len: Option, ) { - if let Some(len) = super_chain_len { - if len > 0 && len < ctx.depth_from_crate_root { - self.add_keyword(ctx, "super::"); - } + if let Some(len) = super_chain_len + && len > 0 + && len < ctx.depth_from_crate_root + { + self.add_keyword(ctx, "super::"); } } @@ -643,10 +644,10 @@ fn enum_variants_with_paths( let variants = enum_.variants(ctx.db); - if let Some(impl_) = impl_.as_ref().and_then(|impl_| ctx.sema.to_def(impl_)) { - if impl_.self_ty(ctx.db).as_adt() == Some(hir::Adt::Enum(enum_)) { - variants.iter().for_each(|variant| process_variant(*variant)); - } + if let Some(impl_) = impl_.as_ref().and_then(|impl_| ctx.sema.to_def(impl_)) + && impl_.self_ty(ctx.db).as_adt() == Some(hir::Adt::Enum(enum_)) + { + variants.iter().for_each(|variant| process_variant(*variant)); } for variant in variants { diff --git a/crates/ide-completion/src/completions/dot.rs b/crates/ide-completion/src/completions/dot.rs index 5340d65a142d..f75123324f37 100644 --- a/crates/ide-completion/src/completions/dot.rs +++ b/crates/ide-completion/src/completions/dot.rs @@ -258,12 +258,11 @@ fn complete_methods( fn on_trait_method(&mut self, func: hir::Function) -> ControlFlow<()> { // This needs to come before the `seen_methods` test, so that if we see the same method twice, // once as inherent and once not, we will include it. - if let ItemContainer::Trait(trait_) = func.container(self.ctx.db) { - if self.ctx.exclude_traits.contains(&trait_) - || trait_.complete(self.ctx.db) == Complete::IgnoreMethods - { - return ControlFlow::Continue(()); - } + if let ItemContainer::Trait(trait_) = func.container(self.ctx.db) + && (self.ctx.exclude_traits.contains(&trait_) + || trait_.complete(self.ctx.db) == Complete::IgnoreMethods) + { + return ControlFlow::Continue(()); } if func.self_param(self.ctx.db).is_some() diff --git a/crates/ide-completion/src/completions/fn_param.rs b/crates/ide-completion/src/completions/fn_param.rs index 809e71cc119e..fb78386976d6 100644 --- a/crates/ide-completion/src/completions/fn_param.rs +++ b/crates/ide-completion/src/completions/fn_param.rs @@ -128,10 +128,10 @@ fn params_from_stmt_list_scope( { let module = scope.module().into(); scope.process_all_names(&mut |name, def| { - if let hir::ScopeDef::Local(local) = def { - if let Ok(ty) = local.ty(ctx.db).display_source_code(ctx.db, module, true) { - cb(name, ty); - } + if let hir::ScopeDef::Local(local) = def + && let Ok(ty) = local.ty(ctx.db).display_source_code(ctx.db, module, true) + { + cb(name, ty); } }); } diff --git a/crates/ide-completion/src/completions/item_list/trait_impl.rs b/crates/ide-completion/src/completions/item_list/trait_impl.rs index bcf8c0ec527a..cdd77e79b5cd 100644 --- a/crates/ide-completion/src/completions/item_list/trait_impl.rs +++ b/crates/ide-completion/src/completions/item_list/trait_impl.rs @@ -228,24 +228,22 @@ fn add_function_impl_( .set_documentation(func.docs(ctx.db)) .set_relevance(CompletionRelevance { exact_name_match: true, ..Default::default() }); - if let Some(source) = ctx.sema.source(func) { - if let Some(transformed_fn) = + if let Some(source) = ctx.sema.source(func) + && let Some(transformed_fn) = get_transformed_fn(ctx, source.value, impl_def, async_sugaring) - { - let function_decl = - function_declaration(ctx, &transformed_fn, source.file_id.macro_file()); - match ctx.config.snippet_cap { - Some(cap) => { - let snippet = format!("{function_decl} {{\n $0\n}}"); - item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet)); - } - None => { - let header = format!("{function_decl} {{"); - item.text_edit(TextEdit::replace(replacement_range, header)); - } - }; - item.add_to(acc, ctx.db); - } + { + let function_decl = function_declaration(ctx, &transformed_fn, source.file_id.macro_file()); + match ctx.config.snippet_cap { + Some(cap) => { + let snippet = format!("{function_decl} {{\n $0\n}}"); + item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet)); + } + None => { + let header = format!("{function_decl} {{"); + item.text_edit(TextEdit::replace(replacement_range, header)); + } + }; + item.add_to(acc, ctx.db); } } @@ -447,36 +445,36 @@ fn add_const_impl( ) { let const_name = const_.name(ctx.db).map(|n| n.display_no_db(ctx.edition).to_smolstr()); - if let Some(const_name) = const_name { - if let Some(source) = ctx.sema.source(const_) { - let assoc_item = ast::AssocItem::Const(source.value); - if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) { - let transformed_const = match transformed_item { - ast::AssocItem::Const(const_) => const_, - _ => unreachable!(), - }; - - let label = - make_const_compl_syntax(ctx, &transformed_const, source.file_id.macro_file()); - let replacement = format!("{label} "); - - let mut item = - CompletionItem::new(SymbolKind::Const, replacement_range, label, ctx.edition); - item.lookup_by(format_smolstr!("const {const_name}")) - .set_documentation(const_.docs(ctx.db)) - .set_relevance(CompletionRelevance { - exact_name_match: true, - ..Default::default() - }); - match ctx.config.snippet_cap { - Some(cap) => item.snippet_edit( - cap, - TextEdit::replace(replacement_range, format!("{replacement}$0;")), - ), - None => item.text_edit(TextEdit::replace(replacement_range, replacement)), - }; - item.add_to(acc, ctx.db); - } + if let Some(const_name) = const_name + && let Some(source) = ctx.sema.source(const_) + { + let assoc_item = ast::AssocItem::Const(source.value); + if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) { + let transformed_const = match transformed_item { + ast::AssocItem::Const(const_) => const_, + _ => unreachable!(), + }; + + let label = + make_const_compl_syntax(ctx, &transformed_const, source.file_id.macro_file()); + let replacement = format!("{label} "); + + let mut item = + CompletionItem::new(SymbolKind::Const, replacement_range, label, ctx.edition); + item.lookup_by(format_smolstr!("const {const_name}")) + .set_documentation(const_.docs(ctx.db)) + .set_relevance(CompletionRelevance { + exact_name_match: true, + ..Default::default() + }); + match ctx.config.snippet_cap { + Some(cap) => item.snippet_edit( + cap, + TextEdit::replace(replacement_range, format!("{replacement}$0;")), + ), + None => item.text_edit(TextEdit::replace(replacement_range, replacement)), + }; + item.add_to(acc, ctx.db); } } } diff --git a/crates/ide-completion/src/completions/mod_.rs b/crates/ide-completion/src/completions/mod_.rs index 013747e4d0cc..333330004577 100644 --- a/crates/ide-completion/src/completions/mod_.rs +++ b/crates/ide-completion/src/completions/mod_.rs @@ -26,18 +26,17 @@ pub(crate) fn complete_mod( let mut current_module = ctx.module; // For `mod $0`, `ctx.module` is its parent, but for `mod f$0`, it's `mod f` itself, but we're // interested in its parent. - if ctx.original_token.kind() == SyntaxKind::IDENT { - if let Some(module) = + if ctx.original_token.kind() == SyntaxKind::IDENT + && let Some(module) = ctx.original_token.parent_ancestors().nth(1).and_then(ast::Module::cast) - { - match ctx.sema.to_def(&module) { - Some(module) if module == current_module => { - if let Some(parent) = current_module.parent(ctx.db) { - current_module = parent; - } + { + match ctx.sema.to_def(&module) { + Some(module) if module == current_module => { + if let Some(parent) = current_module.parent(ctx.db) { + current_module = parent; } - _ => {} } + _ => {} } } diff --git a/crates/ide-completion/src/completions/pattern.rs b/crates/ide-completion/src/completions/pattern.rs index 62fae1cb2374..815ce5145dbe 100644 --- a/crates/ide-completion/src/completions/pattern.rs +++ b/crates/ide-completion/src/completions/pattern.rs @@ -64,18 +64,17 @@ pub(crate) fn complete_pattern( if let Some(hir::Adt::Enum(e)) = ctx.expected_type.as_ref().and_then(|ty| ty.strip_references().as_adt()) + && (refutable || single_variant_enum(e)) { - if refutable || single_variant_enum(e) { - super::enum_variants_with_paths( - acc, - ctx, - e, - &pattern_ctx.impl_, - |acc, ctx, variant, path| { - acc.add_qualified_variant_pat(ctx, pattern_ctx, variant, path); - }, - ); - } + super::enum_variants_with_paths( + acc, + ctx, + e, + &pattern_ctx.impl_, + |acc, ctx, variant, path| { + acc.add_qualified_variant_pat(ctx, pattern_ctx, variant, path); + }, + ); } // FIXME: ideally, we should look at the type we are matching against and diff --git a/crates/ide-completion/src/completions/postfix.rs b/crates/ide-completion/src/completions/postfix.rs index d0023852acf9..0058611a6153 100644 --- a/crates/ide-completion/src/completions/postfix.rs +++ b/crates/ide-completion/src/completions/postfix.rs @@ -65,26 +65,19 @@ pub(crate) fn complete_postfix( let cfg = ctx.config.import_path_config(ctx.is_nightly); - if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() { - if receiver_ty.impls_trait(ctx.db, drop_trait, &[]) { - if let Some(drop_fn) = ctx.famous_defs().core_mem_drop() { - if let Some(path) = - ctx.module.find_path(ctx.db, ItemInNs::Values(drop_fn.into()), cfg) - { - cov_mark::hit!(postfix_drop_completion); - let mut item = postfix_snippet( - "drop", - "fn drop(&mut self)", - &format!( - "{path}($0{receiver_text})", - path = path.display(ctx.db, ctx.edition) - ), - ); - item.set_documentation(drop_fn.docs(ctx.db)); - item.add_to(acc, ctx.db); - } - } - } + if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() + && receiver_ty.impls_trait(ctx.db, drop_trait, &[]) + && let Some(drop_fn) = ctx.famous_defs().core_mem_drop() + && let Some(path) = ctx.module.find_path(ctx.db, ItemInNs::Values(drop_fn.into()), cfg) + { + cov_mark::hit!(postfix_drop_completion); + let mut item = postfix_snippet( + "drop", + "fn drop(&mut self)", + &format!("{path}($0{receiver_text})", path = path.display(ctx.db, ctx.edition)), + ); + item.set_documentation(drop_fn.docs(ctx.db)); + item.add_to(acc, ctx.db); } postfix_snippet("ref", "&expr", &format!("&{receiver_text}")).add_to(acc, ctx.db); @@ -117,56 +110,50 @@ pub(crate) fn complete_postfix( let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty.strip_references()); let mut is_in_cond = false; - if let Some(parent) = dot_receiver_including_refs.syntax().parent() { - if let Some(second_ancestor) = parent.parent() { - let sec_ancestor_kind = second_ancestor.kind(); - if let Some(expr) = >::cast(second_ancestor) { - is_in_cond = match expr { - Either::Left(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), - Either::Right(it) => { - it.condition().is_some_and(|cond| *cond.syntax() == parent) - } - } + if let Some(parent) = dot_receiver_including_refs.syntax().parent() + && let Some(second_ancestor) = parent.parent() + { + let sec_ancestor_kind = second_ancestor.kind(); + if let Some(expr) = >::cast(second_ancestor) { + is_in_cond = match expr { + Either::Left(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), + Either::Right(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), } - match &try_enum { - Some(try_enum) if is_in_cond => match try_enum { - TryEnum::Result => { - postfix_snippet( - "let", - "let Ok(_)", - &format!("let Ok($0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - postfix_snippet( - "letm", - "let Ok(mut _)", - &format!("let Ok(mut $0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - } - TryEnum::Option => { - postfix_snippet( - "let", - "let Some(_)", - &format!("let Some($0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - postfix_snippet( - "letm", - "let Some(mut _)", - &format!("let Some(mut $0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - } - }, - _ if matches!(sec_ancestor_kind, STMT_LIST | EXPR_STMT) => { - postfix_snippet("let", "let", &format!("let $0 = {receiver_text};")) - .add_to(acc, ctx.db); - postfix_snippet("letm", "let mut", &format!("let mut $0 = {receiver_text};")) + } + match &try_enum { + Some(try_enum) if is_in_cond => match try_enum { + TryEnum::Result => { + postfix_snippet("let", "let Ok(_)", &format!("let Ok($0) = {receiver_text}")) .add_to(acc, ctx.db); + postfix_snippet( + "letm", + "let Ok(mut _)", + &format!("let Ok(mut $0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); + } + TryEnum::Option => { + postfix_snippet( + "let", + "let Some(_)", + &format!("let Some($0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); + postfix_snippet( + "letm", + "let Some(mut _)", + &format!("let Some(mut $0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); } - _ => (), + }, + _ if matches!(sec_ancestor_kind, STMT_LIST | EXPR_STMT) => { + postfix_snippet("let", "let", &format!("let $0 = {receiver_text};")) + .add_to(acc, ctx.db); + postfix_snippet("letm", "let mut", &format!("let mut $0 = {receiver_text};")) + .add_to(acc, ctx.db); } + _ => (), } } @@ -258,25 +245,25 @@ pub(crate) fn complete_postfix( ) .add_to(acc, ctx.db); postfix_snippet("not", "!expr", &format!("!{receiver_text}")).add_to(acc, ctx.db); - } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() { - if receiver_ty.impls_trait(ctx.db, trait_, &[]) { - postfix_snippet( - "for", - "for ele in expr {}", - &format!("for ele in {receiver_text} {{\n $0\n}}"), - ) - .add_to(acc, ctx.db); - } + } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() + && receiver_ty.impls_trait(ctx.db, trait_, &[]) + { + postfix_snippet( + "for", + "for ele in expr {}", + &format!("for ele in {receiver_text} {{\n $0\n}}"), + ) + .add_to(acc, ctx.db); } } let mut block_should_be_wrapped = true; if dot_receiver.syntax().kind() == BLOCK_EXPR { block_should_be_wrapped = false; - if let Some(parent) = dot_receiver.syntax().parent() { - if matches!(parent.kind(), IF_EXPR | WHILE_EXPR | LOOP_EXPR | FOR_EXPR) { - block_should_be_wrapped = true; - } + if let Some(parent) = dot_receiver.syntax().parent() + && matches!(parent.kind(), IF_EXPR | WHILE_EXPR | LOOP_EXPR | FOR_EXPR) + { + block_should_be_wrapped = true; } }; { @@ -292,10 +279,10 @@ pub(crate) fn complete_postfix( postfix_snippet("const", "const {}", &const_completion_string).add_to(acc, ctx.db); } - if let ast::Expr::Literal(literal) = dot_receiver_including_refs.clone() { - if let Some(literal_text) = ast::String::cast(literal.token()) { - add_format_like_completions(acc, ctx, &dot_receiver_including_refs, cap, &literal_text); - } + if let ast::Expr::Literal(literal) = dot_receiver_including_refs.clone() + && let Some(literal_text) = ast::String::cast(literal.token()) + { + add_format_like_completions(acc, ctx, &dot_receiver_including_refs, cap, &literal_text); } postfix_snippet( diff --git a/crates/ide-completion/src/completions/use_.rs b/crates/ide-completion/src/completions/use_.rs index d2ab193ec3df..f39b64164932 100644 --- a/crates/ide-completion/src/completions/use_.rs +++ b/crates/ide-completion/src/completions/use_.rs @@ -54,12 +54,10 @@ pub(crate) fn complete_use_path( for (name, def) in module_scope { if let (Some(attrs), Some(defining_crate)) = (def.attrs(ctx.db), def.krate(ctx.db)) + && (!ctx.check_stability(Some(&attrs)) + || ctx.is_doc_hidden(&attrs, defining_crate)) { - if !ctx.check_stability(Some(&attrs)) - || ctx.is_doc_hidden(&attrs, defining_crate) - { - continue; - } + continue; } let is_name_already_imported = already_imported_names.contains(name.as_str()); diff --git a/crates/ide-completion/src/completions/vis.rs b/crates/ide-completion/src/completions/vis.rs index 38761f77a2c5..28d906d91ce5 100644 --- a/crates/ide-completion/src/completions/vis.rs +++ b/crates/ide-completion/src/completions/vis.rs @@ -20,11 +20,11 @@ pub(crate) fn complete_vis_path( // Try completing next child module of the path that is still a parent of the current module let next_towards_current = ctx.module.path_to_root(ctx.db).into_iter().take_while(|it| it != module).last(); - if let Some(next) = next_towards_current { - if let Some(name) = next.name(ctx.db) { - cov_mark::hit!(visibility_qualified); - acc.add_module(ctx, path_ctx, next, name, vec![]); - } + if let Some(next) = next_towards_current + && let Some(name) = next.name(ctx.db) + { + cov_mark::hit!(visibility_qualified); + acc.add_module(ctx, path_ctx, next, name, vec![]); } acc.add_super_keyword(ctx, *super_chain_len); diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs index ea5fb39338b2..2eabf99fc697 100644 --- a/crates/ide-completion/src/context/analysis.rs +++ b/crates/ide-completion/src/context/analysis.rs @@ -287,24 +287,22 @@ fn expand( &spec_attr, fake_ident_token.clone(), ), - ) { - if let Some((fake_mapped_token, _)) = - fake_mapped_tokens.into_iter().min_by_key(|(_, rank)| *rank) - { - return Some(ExpansionResult { - original_file: original_file.value, - speculative_file, - original_offset, - speculative_offset: fake_ident_token.text_range().start(), - fake_ident_token, - derive_ctx: Some(( - actual_expansion, - fake_expansion, - fake_mapped_token.text_range().start(), - orig_attr, - )), - }); - } + ) && let Some((fake_mapped_token, _)) = + fake_mapped_tokens.into_iter().min_by_key(|(_, rank)| *rank) + { + return Some(ExpansionResult { + original_file: original_file.value, + speculative_file, + original_offset, + speculative_offset: fake_ident_token.text_range().start(), + fake_ident_token, + derive_ctx: Some(( + actual_expansion, + fake_expansion, + fake_mapped_token.text_range().start(), + orig_attr, + )), + }); } if let Some(spec_adt) = @@ -535,14 +533,13 @@ fn analyze<'db>( NameRefKind::Path(PathCompletionCtx { kind: PathKind::Expr { .. }, path, .. }, ..), .. } = &nameref_ctx + && is_in_token_of_for_loop(path) { - if is_in_token_of_for_loop(path) { - // for pat $0 - // there is nothing to complete here except `in` keyword - // don't bother populating the context - // Ideally this special casing wouldn't be needed, but the parser recovers - return None; - } + // for pat $0 + // there is nothing to complete here except `in` keyword + // don't bother populating the context + // Ideally this special casing wouldn't be needed, but the parser recovers + return None; } qual_ctx = qualifier_ctx; @@ -951,29 +948,26 @@ fn classify_name_ref<'db>( let inbetween_body_and_decl_check = |node: SyntaxNode| { if let Some(NodeOrToken::Node(n)) = syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev) + && let Some(item) = ast::Item::cast(n) { - if let Some(item) = ast::Item::cast(n) { - let is_inbetween = match &item { - ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(), - ast::Item::Enum(it) => it.variant_list().is_none(), - ast::Item::ExternBlock(it) => it.extern_item_list().is_none(), - ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(), - ast::Item::Impl(it) => it.assoc_item_list().is_none(), - ast::Item::Module(it) => { - it.item_list().is_none() && it.semicolon_token().is_none() - } - ast::Item::Static(it) => it.body().is_none(), - ast::Item::Struct(it) => { - it.field_list().is_none() && it.semicolon_token().is_none() - } - ast::Item::Trait(it) => it.assoc_item_list().is_none(), - ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(), - ast::Item::Union(it) => it.record_field_list().is_none(), - _ => false, - }; - if is_inbetween { - return Some(item); + let is_inbetween = match &item { + ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(), + ast::Item::Enum(it) => it.variant_list().is_none(), + ast::Item::ExternBlock(it) => it.extern_item_list().is_none(), + ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(), + ast::Item::Impl(it) => it.assoc_item_list().is_none(), + ast::Item::Module(it) => it.item_list().is_none() && it.semicolon_token().is_none(), + ast::Item::Static(it) => it.body().is_none(), + ast::Item::Struct(it) => { + it.field_list().is_none() && it.semicolon_token().is_none() } + ast::Item::Trait(it) => it.assoc_item_list().is_none(), + ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(), + ast::Item::Union(it) => it.record_field_list().is_none(), + _ => false, + }; + if is_inbetween { + return Some(item); } } None @@ -1502,10 +1496,10 @@ fn classify_name_ref<'db>( } }; } - } else if let Some(segment) = path.segment() { - if segment.coloncolon_token().is_some() { - path_ctx.qualified = Qualified::Absolute; - } + } else if let Some(segment) = path.segment() + && segment.coloncolon_token().is_some() + { + path_ctx.qualified = Qualified::Absolute; } let mut qualifier_ctx = QualifierCtx::default(); @@ -1530,38 +1524,30 @@ fn classify_name_ref<'db>( if let Some(top) = top_node { if let Some(NodeOrToken::Node(error_node)) = syntax::algo::non_trivia_sibling(top.clone().into(), syntax::Direction::Prev) + && error_node.kind() == SyntaxKind::ERROR { - if error_node.kind() == SyntaxKind::ERROR { - for token in - error_node.children_with_tokens().filter_map(NodeOrToken::into_token) - { - match token.kind() { - SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token), - SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token), - SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token), - _ => {} - } + for token in error_node.children_with_tokens().filter_map(NodeOrToken::into_token) { + match token.kind() { + SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token), + SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token), + SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token), + _ => {} } - qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast); } + qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast); } - if let PathKind::Item { .. } = path_ctx.kind { - if qualifier_ctx.none() { - if let Some(t) = top.first_token() { - if let Some(prev) = t - .prev_token() - .and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev)) - { - if ![T![;], T!['}'], T!['{']].contains(&prev.kind()) { - // This was inferred to be an item position path, but it seems - // to be part of some other broken node which leaked into an item - // list - return None; - } - } - } - } + if let PathKind::Item { .. } = path_ctx.kind + && qualifier_ctx.none() + && let Some(t) = top.first_token() + && let Some(prev) = + t.prev_token().and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev)) + && ![T![;], T!['}'], T!['{']].contains(&prev.kind()) + { + // This was inferred to be an item position path, but it seems + // to be part of some other broken node which leaked into an item + // list + return None; } } } diff --git a/crates/ide-completion/src/item.rs b/crates/ide-completion/src/item.rs index dcaac3997b27..f27cd0781665 100644 --- a/crates/ide-completion/src/item.rs +++ b/crates/ide-completion/src/item.rs @@ -636,10 +636,10 @@ impl Builder { } pub(crate) fn set_detail(&mut self, detail: Option>) -> &mut Builder { self.detail = detail.map(Into::into); - if let Some(detail) = &self.detail { - if never!(detail.contains('\n'), "multiline detail:\n{}", detail) { - self.detail = Some(detail.split('\n').next().unwrap().to_owned()); - } + if let Some(detail) = &self.detail + && never!(detail.contains('\n'), "multiline detail:\n{}", detail) + { + self.detail = Some(detail.split('\n').next().unwrap().to_owned()); } self } diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs index 1fdd4cdb1c6b..a70a1138d2f4 100644 --- a/crates/ide-completion/src/lib.rs +++ b/crates/ide-completion/src/lib.rs @@ -208,9 +208,9 @@ pub fn completions( // when the user types a bare `_` (that is it does not belong to an identifier) // the user might just wanted to type a `_` for type inference or pattern discarding // so try to suppress completions in those cases - if trigger_character == Some('_') && ctx.original_token.kind() == syntax::SyntaxKind::UNDERSCORE - { - if let CompletionAnalysis::NameRef(NameRefContext { + if trigger_character == Some('_') + && ctx.original_token.kind() == syntax::SyntaxKind::UNDERSCORE + && let CompletionAnalysis::NameRef(NameRefContext { kind: NameRefKind::Path( path_ctx @ PathCompletionCtx { @@ -220,11 +220,9 @@ pub fn completions( ), .. }) = analysis - { - if path_ctx.is_trivial_path() { - return None; - } - } + && path_ctx.is_trivial_path() + { + return None; } { diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index c6b8af3c79a2..3d7a4067c2cd 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -164,19 +164,18 @@ pub(crate) fn render_field( let expected_fn_type = ctx.completion.expected_type.as_ref().is_some_and(|ty| ty.is_fn() || ty.is_closure()); - if !expected_fn_type { - if let Some(receiver) = &dot_access.receiver { - if let Some(receiver) = ctx.completion.sema.original_ast_node(receiver.clone()) { - builder.insert(receiver.syntax().text_range().start(), "(".to_owned()); - builder.insert(ctx.source_range().end(), ")".to_owned()); - - let is_parens_needed = - !matches!(dot_access.kind, DotAccessKind::Method { has_parens: true }); - - if is_parens_needed { - builder.insert(ctx.source_range().end(), "()".to_owned()); - } - } + if !expected_fn_type + && let Some(receiver) = &dot_access.receiver + && let Some(receiver) = ctx.completion.sema.original_ast_node(receiver.clone()) + { + builder.insert(receiver.syntax().text_range().start(), "(".to_owned()); + builder.insert(ctx.source_range().end(), ")".to_owned()); + + let is_parens_needed = + !matches!(dot_access.kind, DotAccessKind::Method { has_parens: true }); + + if is_parens_needed { + builder.insert(ctx.source_range().end(), "()".to_owned()); } } @@ -184,12 +183,11 @@ pub(crate) fn render_field( } else { item.insert_text(field_with_receiver(receiver.as_deref(), &escaped_name)); } - if let Some(receiver) = &dot_access.receiver { - if let Some(original) = ctx.completion.sema.original_ast_node(receiver.clone()) { - if let Some(ref_mode) = compute_ref_match(ctx.completion, ty) { - item.ref_match(ref_mode, original.syntax().text_range().start()); - } - } + if let Some(receiver) = &dot_access.receiver + && let Some(original) = ctx.completion.sema.original_ast_node(receiver.clone()) + && let Some(ref_mode) = compute_ref_match(ctx.completion, ty) + { + item.ref_match(ref_mode, original.syntax().text_range().start()); } item.doc_aliases(ctx.doc_aliases); item.build(db) @@ -437,26 +435,21 @@ fn render_resolution_path( path_ctx, PathCompletionCtx { kind: PathKind::Type { .. }, has_type_args: false, .. } ) && config.callable.is_some(); - if type_path_no_ty_args { - if let Some(cap) = cap { - let has_non_default_type_params = match resolution { - ScopeDef::ModuleDef(hir::ModuleDef::Adt(it)) => it.has_non_default_type_params(db), - ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(it)) => { - it.has_non_default_type_params(db) - } - _ => false, - }; - - if has_non_default_type_params { - cov_mark::hit!(inserts_angle_brackets_for_generics); - item.lookup_by(name.clone()) - .label(SmolStr::from_iter([&name, "<…>"])) - .trigger_call_info() - .insert_snippet( - cap, - format!("{}<$0>", local_name.display(db, completion.edition)), - ); + if type_path_no_ty_args && let Some(cap) = cap { + let has_non_default_type_params = match resolution { + ScopeDef::ModuleDef(hir::ModuleDef::Adt(it)) => it.has_non_default_type_params(db), + ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(it)) => { + it.has_non_default_type_params(db) } + _ => false, + }; + + if has_non_default_type_params { + cov_mark::hit!(inserts_angle_brackets_for_generics); + item.lookup_by(name.clone()) + .label(SmolStr::from_iter([&name, "<…>"])) + .trigger_call_info() + .insert_snippet(cap, format!("{}<$0>", local_name.display(db, completion.edition))); } } @@ -634,23 +627,24 @@ fn compute_ref_match( if expected_type.could_unify_with(ctx.db, completion_ty) { return None; } - if let Some(expected_without_ref) = &expected_without_ref { - if completion_ty.autoderef(ctx.db).any(|ty| ty == *expected_without_ref) { - cov_mark::hit!(suggest_ref); - let mutability = if expected_type.is_mutable_reference() { - hir::Mutability::Mut - } else { - hir::Mutability::Shared - }; - return Some(CompletionItemRefMode::Reference(mutability)); - } + if let Some(expected_without_ref) = &expected_without_ref + && completion_ty.autoderef(ctx.db).any(|ty| ty == *expected_without_ref) + { + cov_mark::hit!(suggest_ref); + let mutability = if expected_type.is_mutable_reference() { + hir::Mutability::Mut + } else { + hir::Mutability::Shared + }; + return Some(CompletionItemRefMode::Reference(mutability)); } - if let Some(completion_without_ref) = completion_without_ref { - if completion_without_ref == *expected_type && completion_without_ref.is_copy(ctx.db) { - cov_mark::hit!(suggest_deref); - return Some(CompletionItemRefMode::Dereference); - } + if let Some(completion_without_ref) = completion_without_ref + && completion_without_ref == *expected_type + && completion_without_ref.is_copy(ctx.db) + { + cov_mark::hit!(suggest_deref); + return Some(CompletionItemRefMode::Dereference); } None @@ -664,10 +658,10 @@ fn path_ref_match( ) { if let Some(original_path) = &path_ctx.original_path { // At least one char was typed by the user already, in that case look for the original path - if let Some(original_path) = completion.sema.original_ast_node(original_path.clone()) { - if let Some(ref_mode) = compute_ref_match(completion, ty) { - item.ref_match(ref_mode, original_path.syntax().text_range().start()); - } + if let Some(original_path) = completion.sema.original_ast_node(original_path.clone()) + && let Some(ref_mode) = compute_ref_match(completion, ty) + { + item.ref_match(ref_mode, original_path.syntax().text_range().start()); } } else { // completion requested on an empty identifier, there is no path here yet. diff --git a/crates/ide-completion/src/render/const_.rs b/crates/ide-completion/src/render/const_.rs index f11b3023679a..707a8aed4fb9 100644 --- a/crates/ide-completion/src/render/const_.rs +++ b/crates/ide-completion/src/render/const_.rs @@ -25,10 +25,10 @@ fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option .detail(detail) .set_relevance(ctx.completion_relevance()); - if let Some(actm) = const_.as_assoc_item(db) { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); - } + if let Some(actm) = const_.as_assoc_item(db) + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } item.insert_text(escaped_name); diff --git a/crates/ide-completion/src/render/function.rs b/crates/ide-completion/src/render/function.rs index 7669aec8f535..c466019f991f 100644 --- a/crates/ide-completion/src/render/function.rs +++ b/crates/ide-completion/src/render/function.rs @@ -132,10 +132,10 @@ fn render( super::path_ref_match(completion, path_ctx, &ret_type, &mut item); } FuncKind::Method(DotAccess { receiver: Some(receiver), .. }, _) => { - if let Some(original_expr) = completion.sema.original_ast_node(receiver.clone()) { - if let Some(ref_mode) = compute_ref_match(completion, &ret_type) { - item.ref_match(ref_mode, original_expr.syntax().text_range().start()); - } + if let Some(original_expr) = completion.sema.original_ast_node(receiver.clone()) + && let Some(ref_mode) = compute_ref_match(completion, &ret_type) + { + item.ref_match(ref_mode, original_expr.syntax().text_range().start()); } } _ => (), @@ -169,12 +169,10 @@ fn render( item.add_import(import_to_add); } None => { - if let Some(actm) = assoc_item { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name( - trt.name(db).display_no_db(ctx.completion.edition).to_smolstr(), - ); - } + if let Some(actm) = assoc_item + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } } } @@ -378,15 +376,13 @@ fn params<'db>( ctx.config.callable.as_ref()?; // Don't add parentheses if the expected type is a function reference with the same signature. - if let Some(expected) = ctx.expected_type.as_ref().filter(|e| e.is_fn()) { - if let Some(expected) = expected.as_callable(ctx.db) { - if let Some(completed) = func.ty(ctx.db).as_callable(ctx.db) { - if expected.sig() == completed.sig() { - cov_mark::hit!(no_call_parens_if_fn_ptr_needed); - return None; - } - } - } + if let Some(expected) = ctx.expected_type.as_ref().filter(|e| e.is_fn()) + && let Some(expected) = expected.as_callable(ctx.db) + && let Some(completed) = func.ty(ctx.db).as_callable(ctx.db) + && expected.sig() == completed.sig() + { + cov_mark::hit!(no_call_parens_if_fn_ptr_needed); + return None; } let self_param = if has_dot_receiver || matches!(func_kind, FuncKind::Method(_, Some(_))) { diff --git a/crates/ide-completion/src/render/type_alias.rs b/crates/ide-completion/src/render/type_alias.rs index d57feee4fa65..3fc0f369e5ad 100644 --- a/crates/ide-completion/src/render/type_alias.rs +++ b/crates/ide-completion/src/render/type_alias.rs @@ -51,10 +51,10 @@ fn render( .detail(detail) .set_relevance(ctx.completion_relevance()); - if let Some(actm) = type_alias.as_assoc_item(db) { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); - } + if let Some(actm) = type_alias.as_assoc_item(db) + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } item.insert_text(escaped_name); diff --git a/crates/ide-db/src/defs.rs b/crates/ide-db/src/defs.rs index a4a140ec57aa..2a4fcf6a2e5f 100644 --- a/crates/ide-db/src/defs.rs +++ b/crates/ide-db/src/defs.rs @@ -610,18 +610,16 @@ impl<'db> NameClass<'db> { let local = sema.to_def(&ident_pat)?; let pat_parent = ident_pat.syntax().parent(); - if let Some(record_pat_field) = pat_parent.and_then(ast::RecordPatField::cast) { - if record_pat_field.name_ref().is_none() { - if let Some((field, _, adt_subst)) = - sema.resolve_record_pat_field_with_subst(&record_pat_field) - { - return Some(NameClass::PatFieldShorthand { - local_def: local, - field_ref: field, - adt_subst, - }); - } - } + if let Some(record_pat_field) = pat_parent.and_then(ast::RecordPatField::cast) + && record_pat_field.name_ref().is_none() + && let Some((field, _, adt_subst)) = + sema.resolve_record_pat_field_with_subst(&record_pat_field) + { + return Some(NameClass::PatFieldShorthand { + local_def: local, + field_ref: field, + adt_subst, + }); } Some(NameClass::Definition(Definition::Local(local))) } @@ -755,30 +753,27 @@ impl<'db> NameRefClass<'db> { let parent = name_ref.syntax().parent()?; - if let Some(record_field) = ast::RecordExprField::for_field_name(name_ref) { - if let Some((field, local, _, adt_subst)) = + if let Some(record_field) = ast::RecordExprField::for_field_name(name_ref) + && let Some((field, local, _, adt_subst)) = sema.resolve_record_field_with_substitution(&record_field) - { - let res = match local { - None => NameRefClass::Definition(Definition::Field(field), Some(adt_subst)), - Some(local) => NameRefClass::FieldShorthand { - field_ref: field, - local_ref: local, - adt_subst, - }, - }; - return Some(res); - } + { + let res = match local { + None => NameRefClass::Definition(Definition::Field(field), Some(adt_subst)), + Some(local) => { + NameRefClass::FieldShorthand { field_ref: field, local_ref: local, adt_subst } + } + }; + return Some(res); } if let Some(path) = ast::PathSegment::cast(parent.clone()).map(|it| it.parent_path()) { - if path.parent_path().is_none() { - if let Some(macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - // Only use this to resolve to macro calls for last segments as qualifiers resolve - // to modules below. - if let Some(macro_def) = sema.resolve_macro_call(¯o_call) { - return Some(NameRefClass::Definition(Definition::Macro(macro_def), None)); - } + if path.parent_path().is_none() + && let Some(macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + // Only use this to resolve to macro calls for last segments as qualifiers resolve + // to modules below. + if let Some(macro_def) = sema.resolve_macro_call(¯o_call) { + return Some(NameRefClass::Definition(Definition::Macro(macro_def), None)); } } return sema @@ -820,8 +815,8 @@ impl<'db> NameRefClass<'db> { // ^^^^^ let containing_path = name_ref.syntax().ancestors().find_map(ast::Path::cast)?; let resolved = sema.resolve_path(&containing_path)?; - if let PathResolution::Def(ModuleDef::Trait(tr)) = resolved { - if let Some(ty) = tr + if let PathResolution::Def(ModuleDef::Trait(tr)) = resolved + && let Some(ty) = tr .items_with_supertraits(sema.db) .iter() .filter_map(|&assoc| match assoc { @@ -833,7 +828,6 @@ impl<'db> NameRefClass<'db> { // No substitution, this can only occur in type position. return Some(NameRefClass::Definition(Definition::TypeAlias(ty), None)); } - } None }, ast::UseBoundGenericArgs(_) => { diff --git a/crates/ide-db/src/helpers.rs b/crates/ide-db/src/helpers.rs index 340429037e67..1e54058dd16c 100644 --- a/crates/ide-db/src/helpers.rs +++ b/crates/ide-db/src/helpers.rs @@ -70,11 +70,11 @@ pub fn visit_file_defs( }; let mut defs: VecDeque<_> = module.declarations(db).into(); while let Some(def) = defs.pop_front() { - if let ModuleDef::Module(submodule) = def { - if submodule.is_inline(db) { - defs.extend(submodule.declarations(db)); - submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into())); - } + if let ModuleDef::Module(submodule) = def + && submodule.is_inline(db) + { + defs.extend(submodule.declarations(db)); + submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into())); } cb(def.into()); } diff --git a/crates/ide-db/src/imports/insert_use.rs b/crates/ide-db/src/imports/insert_use.rs index 813f38380f69..08cd8f28608c 100644 --- a/crates/ide-db/src/imports/insert_use.rs +++ b/crates/ide-db/src/imports/insert_use.rs @@ -97,12 +97,11 @@ impl ImportScope { .map(ImportScopeKind::Module) .map(|kind| ImportScope { kind, required_cfgs }); } else if let Some(has_attrs) = ast::AnyHasAttrs::cast(syntax) { - if block.is_none() { - if let Some(b) = ast::BlockExpr::cast(has_attrs.syntax().clone()) { - if let Some(b) = sema.original_ast_node(b) { - block = b.stmt_list(); - } - } + if block.is_none() + && let Some(b) = ast::BlockExpr::cast(has_attrs.syntax().clone()) + && let Some(b) = sema.original_ast_node(b) + { + block = b.stmt_list(); } if has_attrs .attrs() @@ -349,26 +348,24 @@ fn guess_granularity_from_scope(scope: &ImportScope) -> ImportGranularityGuess { seen_one_style_groups.push((curr_vis.clone(), curr_attrs.clone())); } else if eq_visibility(prev_vis, curr_vis.clone()) && eq_attrs(prev_attrs, curr_attrs.clone()) + && let Some((prev_path, curr_path)) = prev.path().zip(curr.path()) + && let Some((prev_prefix, _)) = common_prefix(&prev_path, &curr_path) { - if let Some((prev_path, curr_path)) = prev.path().zip(curr.path()) { - if let Some((prev_prefix, _)) = common_prefix(&prev_path, &curr_path) { - if prev.use_tree_list().is_none() && curr.use_tree_list().is_none() { - let prefix_c = prev_prefix.qualifiers().count(); - let curr_c = curr_path.qualifiers().count() - prefix_c; - let prev_c = prev_path.qualifiers().count() - prefix_c; - if curr_c == 1 && prev_c == 1 { - // Same prefix, only differing in the last segment and no use tree lists so this has to be of item style. - break ImportGranularityGuess::Item; - } else { - // Same prefix and no use tree list but differs in more than one segment at the end. This might be module style still. - res = ImportGranularityGuess::ModuleOrItem; - } - } else { - // Same prefix with item tree lists, has to be module style as it - // can't be crate style since the trees wouldn't share a prefix then. - break ImportGranularityGuess::Module; - } + if prev.use_tree_list().is_none() && curr.use_tree_list().is_none() { + let prefix_c = prev_prefix.qualifiers().count(); + let curr_c = curr_path.qualifiers().count() - prefix_c; + let prev_c = prev_path.qualifiers().count() - prefix_c; + if curr_c == 1 && prev_c == 1 { + // Same prefix, only differing in the last segment and no use tree lists so this has to be of item style. + break ImportGranularityGuess::Item; + } else { + // Same prefix and no use tree list but differs in more than one segment at the end. This might be module style still. + res = ImportGranularityGuess::ModuleOrItem; } + } else { + // Same prefix with item tree lists, has to be module style as it + // can't be crate style since the trees wouldn't share a prefix then. + break ImportGranularityGuess::Module; } } prev = curr; diff --git a/crates/ide-db/src/path_transform.rs b/crates/ide-db/src/path_transform.rs index b7432d89c7b7..5d88afec5095 100644 --- a/crates/ide-db/src/path_transform.rs +++ b/crates/ide-db/src/path_transform.rs @@ -193,13 +193,12 @@ impl<'a> PathTransform<'a> { } } (Either::Right(k), None) => { - if let Some(default) = k.default(db) { - if let Some(default) = + if let Some(default) = k.default(db) + && let Some(default) = &default.display_source_code(db, source_module.into(), false).ok() - { - type_substs.insert(k, make::ty(default).clone_for_update()); - defaulted_params.push(Either::Left(k)); - } + { + type_substs.insert(k, make::ty(default).clone_for_update()); + defaulted_params.push(Either::Left(k)); } } (Either::Left(k), Some(TypeOrConst::Either(v))) => { @@ -221,11 +220,10 @@ impl<'a> PathTransform<'a> { (Either::Left(k), None) => { if let Some(default) = k.default(db, target_module.krate().to_display_target(db)) + && let Some(default) = default.expr() { - if let Some(default) = default.expr() { - const_substs.insert(k, default.syntax().clone_for_update()); - defaulted_params.push(Either::Right(k)); - } + const_substs.insert(k, default.syntax().clone_for_update()); + defaulted_params.push(Either::Right(k)); } } _ => (), // ignore mismatching params @@ -427,14 +425,14 @@ impl Ctx<'_> { } } hir::PathResolution::Def(def) if def.as_assoc_item(self.source_scope.db).is_none() => { - if let hir::ModuleDef::Trait(_) = def { - if matches!(path.segment()?.kind()?, ast::PathSegmentKind::Type { .. }) { - // `speculative_resolve` resolves segments like `` into `Trait`, but just the trait name should - // not be used as the replacement of the original - // segment. - return None; - } + if let hir::ModuleDef::Trait(_) = def + && matches!(path.segment()?.kind()?, ast::PathSegmentKind::Type { .. }) + { + // `speculative_resolve` resolves segments like `` into `Trait`, but just the trait name should + // not be used as the replacement of the original + // segment. + return None; } let cfg = ImportPathConfig { @@ -446,19 +444,17 @@ impl Ctx<'_> { let found_path = self.target_module.find_path(self.source_scope.db, def, cfg)?; let res = mod_path_to_ast(&found_path, self.target_edition).clone_for_update(); let mut res_editor = SyntaxEditor::new(res.syntax().clone_subtree()); - if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) { - if let Some(segment) = res.segment() { - if let Some(old) = segment.generic_arg_list() { - res_editor.replace( - old.syntax(), - args.clone_subtree().syntax().clone_for_update(), - ) - } else { - res_editor.insert( - syntax_editor::Position::last_child_of(segment.syntax()), - args.clone_subtree().syntax().clone_for_update(), - ); - } + if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) + && let Some(segment) = res.segment() + { + if let Some(old) = segment.generic_arg_list() { + res_editor + .replace(old.syntax(), args.clone_subtree().syntax().clone_for_update()) + } else { + res_editor.insert( + syntax_editor::Position::last_child_of(segment.syntax()), + args.clone_subtree().syntax().clone_for_update(), + ); } } let res = res_editor.finish().new_root().clone(); @@ -485,27 +481,27 @@ impl Ctx<'_> { .ok()?; let ast_ty = make::ty(ty_str).clone_for_update(); - if let Some(adt) = ty.as_adt() { - if let ast::Type::PathType(path_ty) = &ast_ty { - let cfg = ImportPathConfig { - prefer_no_std: false, - prefer_prelude: true, - prefer_absolute: false, - allow_unstable: true, - }; - let found_path = self.target_module.find_path( - self.source_scope.db, - ModuleDef::from(adt), - cfg, - )?; - - if let Some(qual) = - mod_path_to_ast(&found_path, self.target_edition).qualifier() - { - let res = make::path_concat(qual, path_ty.path()?).clone_for_update(); - editor.replace(path.syntax(), res.syntax()); - return Some(()); - } + if let Some(adt) = ty.as_adt() + && let ast::Type::PathType(path_ty) = &ast_ty + { + let cfg = ImportPathConfig { + prefer_no_std: false, + prefer_prelude: true, + prefer_absolute: false, + allow_unstable: true, + }; + let found_path = self.target_module.find_path( + self.source_scope.db, + ModuleDef::from(adt), + cfg, + )?; + + if let Some(qual) = + mod_path_to_ast(&found_path, self.target_edition).qualifier() + { + let res = make::path_concat(qual, path_ty.path()?).clone_for_update(); + editor.replace(path.syntax(), res.syntax()); + return Some(()); } } diff --git a/crates/ide-db/src/rename.rs b/crates/ide-db/src/rename.rs index 4e737e27f050..424b27a398b2 100644 --- a/crates/ide-db/src/rename.rs +++ b/crates/ide-db/src/rename.rs @@ -442,17 +442,17 @@ fn source_edit_from_name( name: &ast::Name, new_name: &dyn Display, ) -> bool { - if ast::RecordPatField::for_field_name(name).is_some() { - if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) { - cov_mark::hit!(rename_record_pat_field_name_split); - // Foo { ref mut field } -> Foo { new_name: ref mut field } - // ^ insert `new_name: ` - - // FIXME: instead of splitting the shorthand, recursively trigger a rename of the - // other name https://github.com/rust-lang/rust-analyzer/issues/6547 - edit.insert(ident_pat.syntax().text_range().start(), format!("{new_name}: ")); - return true; - } + if ast::RecordPatField::for_field_name(name).is_some() + && let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) + { + cov_mark::hit!(rename_record_pat_field_name_split); + // Foo { ref mut field } -> Foo { new_name: ref mut field } + // ^ insert `new_name: ` + + // FIXME: instead of splitting the shorthand, recursively trigger a rename of the + // other name https://github.com/rust-lang/rust-analyzer/issues/6547 + edit.insert(ident_pat.syntax().text_range().start(), format!("{new_name}: ")); + return true; } false diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index 9cf0bcf91901..4dd64229d274 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -295,10 +295,10 @@ impl Definition { } // def is crate root - if let &Definition::Module(module) = self { - if module.is_crate_root() { - return SearchScope::reverse_dependencies(db, module.krate()); - } + if let &Definition::Module(module) = self + && module.is_crate_root() + { + return SearchScope::reverse_dependencies(db, module.krate()); } let module = match self.module(db) { @@ -683,51 +683,47 @@ impl<'a> FindUsages<'a> { } } else if let Some(alias) = usage.ancestors().find_map(ast::TypeAlias::cast) + && let Some(name) = alias.name() + && seen + .insert(InFileWrapper::new(file_id, name.syntax().text_range())) { - if let Some(name) = alias.name() { - if seen.insert(InFileWrapper::new( - file_id, - name.syntax().text_range(), - )) { - if let Some(def) = is_alias(&alias) { - cov_mark::hit!(container_type_alias); - insert_type_alias( - sema.db, - &mut to_process, - name.text().as_str(), - def.into(), - ); - } else { - cov_mark::hit!(same_name_different_def_type_alias); - } - } + if let Some(def) = is_alias(&alias) { + cov_mark::hit!(container_type_alias); + insert_type_alias( + sema.db, + &mut to_process, + name.text().as_str(), + def.into(), + ); + } else { + cov_mark::hit!(same_name_different_def_type_alias); } } // We need to account for `Self`. It can only refer to our type inside an impl. let impl_ = 'impl_: { for ancestor in usage.ancestors() { - if let Some(parent) = ancestor.parent() { - if let Some(parent) = ast::Impl::cast(parent) { - // Only if the GENERIC_PARAM_LIST is directly under impl, otherwise it may be in the self ty. - if matches!( - ancestor.kind(), - SyntaxKind::ASSOC_ITEM_LIST - | SyntaxKind::WHERE_CLAUSE - | SyntaxKind::GENERIC_PARAM_LIST - ) { - break; - } - if parent - .trait_() - .is_some_and(|trait_| *trait_.syntax() == ancestor) - { - break; - } - - // Otherwise, found an impl where its self ty may be our type. - break 'impl_ Some(parent); + if let Some(parent) = ancestor.parent() + && let Some(parent) = ast::Impl::cast(parent) + { + // Only if the GENERIC_PARAM_LIST is directly under impl, otherwise it may be in the self ty. + if matches!( + ancestor.kind(), + SyntaxKind::ASSOC_ITEM_LIST + | SyntaxKind::WHERE_CLAUSE + | SyntaxKind::GENERIC_PARAM_LIST + ) { + break; + } + if parent + .trait_() + .is_some_and(|trait_| *trait_.syntax() == ancestor) + { + break; } + + // Otherwise, found an impl where its self ty may be our type. + break 'impl_ Some(parent); } } None @@ -1356,11 +1352,10 @@ impl ReferenceCategory { if matches!(expr.op_kind()?, ast::BinaryOp::Assignment { .. }) { // If the variable or field ends on the LHS's end then it's a Write // (covers fields and locals). FIXME: This is not terribly accurate. - if let Some(lhs) = expr.lhs() { - if lhs.syntax().text_range().end() == r.syntax().text_range().end() { + if let Some(lhs) = expr.lhs() + && lhs.syntax().text_range().end() == r.syntax().text_range().end() { return Some(ReferenceCategory::WRITE) } - } } Some(ReferenceCategory::READ) }, diff --git a/crates/ide-db/src/symbol_index.rs b/crates/ide-db/src/symbol_index.rs index c15cade84a50..9c4e6f5cbf82 100644 --- a/crates/ide-db/src/symbol_index.rs +++ b/crates/ide-db/src/symbol_index.rs @@ -252,10 +252,10 @@ impl SymbolIndex { let mut last_batch_start = 0; for idx in 0..symbols.len() { - if let Some(next_symbol) = symbols.get(idx + 1) { - if cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal { - continue; - } + if let Some(next_symbol) = symbols.get(idx + 1) + && cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal + { + continue; } let start = last_batch_start; @@ -371,10 +371,10 @@ impl Query { if self.exclude_imports && symbol.is_import { continue; } - if self.mode.check(&self.query, self.case_sensitive, symbol_name) { - if let Some(b) = cb(symbol).break_value() { - return Some(b); - } + if self.mode.check(&self.query, self.case_sensitive, symbol_name) + && let Some(b) = cb(symbol).break_value() + { + return Some(b); } } } diff --git a/crates/ide-db/src/syntax_helpers/format_string.rs b/crates/ide-db/src/syntax_helpers/format_string.rs index 7e8c921d9ed3..1d4d8decf541 100644 --- a/crates/ide-db/src/syntax_helpers/format_string.rs +++ b/crates/ide-db/src/syntax_helpers/format_string.rs @@ -230,11 +230,11 @@ pub fn lex_format_specifiers( skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback); } continue; - } else if let '}' = first_char { - if let Some((_, '}')) = chars.peek() { - // Escaped format specifier, `}}` - read_escaped_format_specifier(&mut chars, &mut callback); - } + } else if let '}' = first_char + && let Some((_, '}')) = chars.peek() + { + // Escaped format specifier, `}}` + read_escaped_format_specifier(&mut chars, &mut callback); } } diff --git a/crates/ide-db/src/syntax_helpers/node_ext.rs b/crates/ide-db/src/syntax_helpers/node_ext.rs index bdff64dd0812..cefd8fd49676 100644 --- a/crates/ide-db/src/syntax_helpers/node_ext.rs +++ b/crates/ide-db/src/syntax_helpers/node_ext.rs @@ -79,14 +79,13 @@ pub fn preorder_expr_with_ctx_checker( continue; } }; - if let Some(let_stmt) = node.parent().and_then(ast::LetStmt::cast) { - if let_stmt.initializer().map(|it| it.syntax() != &node).unwrap_or(true) - && let_stmt.let_else().map(|it| it.syntax() != &node).unwrap_or(true) - { - // skipping potential const pat expressions in let statements - preorder.skip_subtree(); - continue; - } + if let Some(let_stmt) = node.parent().and_then(ast::LetStmt::cast) + && let_stmt.initializer().map(|it| it.syntax() != &node).unwrap_or(true) + && let_stmt.let_else().map(|it| it.syntax() != &node).unwrap_or(true) + { + // skipping potential const pat expressions in let statements + preorder.skip_subtree(); + continue; } match ast::Stmt::cast(node.clone()) { @@ -306,10 +305,10 @@ pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) { Some(ast::BlockModifier::AsyncGen(_)) => (), None => (), } - if let Some(stmt_list) = b.stmt_list() { - if let Some(e) = stmt_list.tail_expr() { - for_each_tail_expr(&e, cb); - } + if let Some(stmt_list) = b.stmt_list() + && let Some(e) = stmt_list.tail_expr() + { + for_each_tail_expr(&e, cb); } } ast::Expr::IfExpr(if_) => { diff --git a/crates/ide-db/src/use_trivial_constructor.rs b/crates/ide-db/src/use_trivial_constructor.rs index f63cd92694b3..a91d436afcfb 100644 --- a/crates/ide-db/src/use_trivial_constructor.rs +++ b/crates/ide-db/src/use_trivial_constructor.rs @@ -16,17 +16,17 @@ pub fn use_trivial_constructor( ) -> Option { match ty.as_adt() { Some(hir::Adt::Enum(x)) => { - if let &[variant] = &*x.variants(db) { - if variant.kind(db) == hir::StructKind::Unit { - let path = make::path_qualified( - path, - make::path_segment(make::name_ref( - &variant.name(db).display_no_db(edition).to_smolstr(), - )), - ); + if let &[variant] = &*x.variants(db) + && variant.kind(db) == hir::StructKind::Unit + { + let path = make::path_qualified( + path, + make::path_segment(make::name_ref( + &variant.name(db).display_no_db(edition).to_smolstr(), + )), + ); - return Some(make::expr_path(path)); - } + return Some(make::expr_path(path)); } } Some(hir::Adt::Struct(x)) if x.kind(db) == StructKind::Unit => { diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index bf7dddacd8c5..742d614bc567 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -148,37 +148,27 @@ pub(crate) fn json_in_items( allow_unstable: true, }; - if !scope_has("Serialize") { - if let Some(PathResolution::Def(it)) = serialize_resolved { - if let Some(it) = current_module.find_use_path( - sema.db, - it, - config.insert_use.prefix_kind, - cfg, - ) { - insert_use( - &scope, - mod_path_to_ast(&it, edition), - &config.insert_use, - ); - } - } + if !scope_has("Serialize") + && let Some(PathResolution::Def(it)) = serialize_resolved + && let Some(it) = current_module.find_use_path( + sema.db, + it, + config.insert_use.prefix_kind, + cfg, + ) + { + insert_use(&scope, mod_path_to_ast(&it, edition), &config.insert_use); } - if !scope_has("Deserialize") { - if let Some(PathResolution::Def(it)) = deserialize_resolved { - if let Some(it) = current_module.find_use_path( - sema.db, - it, - config.insert_use.prefix_kind, - cfg, - ) { - insert_use( - &scope, - mod_path_to_ast(&it, edition), - &config.insert_use, - ); - } - } + if !scope_has("Deserialize") + && let Some(PathResolution::Def(it)) = deserialize_resolved + && let Some(it) = current_module.find_use_path( + sema.db, + it, + config.insert_use.prefix_kind, + cfg, + ) + { + insert_use(&scope, mod_path_to_ast(&it, edition), &config.insert_use); } let mut sc = scb.finish(); sc.insert_source_edit(vfs_file_id, edit.finish()); diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index 7da799e0d490..893bfca6a129 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -227,12 +227,11 @@ fn get_default_constructor( // Look for a ::new() associated function let has_new_func = ty .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| { - if let AssocItem::Function(func) = assoc_item { - if func.name(ctx.sema.db) == sym::new - && func.assoc_fn_params(ctx.sema.db).is_empty() - { - return Some(()); - } + if let AssocItem::Function(func) = assoc_item + && func.name(ctx.sema.db) == sym::new + && func.assoc_fn_params(ctx.sema.db).is_empty() + { + return Some(()); } None diff --git a/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/crates/ide-diagnostics/src/handlers/mutability_errors.rs index 8831efa31172..6e30bf92dbaa 100644 --- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -12,14 +12,14 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option let root = ctx.sema.db.parse_or_expand(d.span.file_id); let node = d.span.value.to_node(&root); let mut span = d.span; - if let Some(parent) = node.parent() { - if ast::BinExpr::can_cast(parent.kind()) { - // In case of an assignment, the diagnostic is provided on the variable name. - // We want to expand it to include the whole assignment, but only when this - // is an ordinary assignment, not a destructuring assignment. So, the direct - // parent is an assignment expression. - span = d.span.with_value(SyntaxNodePtr::new(&parent)); - } + if let Some(parent) = node.parent() + && ast::BinExpr::can_cast(parent.kind()) + { + // In case of an assignment, the diagnostic is provided on the variable name. + // We want to expand it to include the whole assignment, but only when this + // is an ordinary assignment, not a destructuring assignment. So, the direct + // parent is an assignment expression. + span = d.span.with_value(SyntaxNodePtr::new(&parent)); }; let fixes = (|| { @@ -73,10 +73,10 @@ pub(crate) fn unused_mut(ctx: &DiagnosticsContext<'_>, d: &hir::UnusedMut) -> Op let ast = source.syntax(); let Some(mut_token) = token(ast, T![mut]) else { continue }; edit_builder.delete(mut_token.text_range()); - if let Some(token) = mut_token.next_token() { - if token.kind() == SyntaxKind::WHITESPACE { - edit_builder.delete(token.text_range()); - } + if let Some(token) = mut_token.next_token() + && token.kind() == SyntaxKind::WHITESPACE + { + edit_builder.delete(token.text_range()); } } let edit = edit_builder.finish(); diff --git a/crates/ide-diagnostics/src/handlers/unlinked_file.rs b/crates/ide-diagnostics/src/handlers/unlinked_file.rs index d96c658d7b04..3a6e480f55ed 100644 --- a/crates/ide-diagnostics/src/handlers/unlinked_file.rs +++ b/crates/ide-diagnostics/src/handlers/unlinked_file.rs @@ -231,13 +231,13 @@ fn make_fixes( // If there's an existing `mod m;` statement matching the new one, don't emit a fix (it's // probably `#[cfg]`d out). for item in items.clone() { - if let ast::Item::Module(m) = item { - if let Some(name) = m.name() { - if m.item_list().is_none() && name.to_string() == new_mod_name { - cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists); - return None; - } - } + if let ast::Item::Module(m) = item + && let Some(name) = m.name() + && m.item_list().is_none() + && name.to_string() == new_mod_name + { + cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists); + return None; } } diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs index 72bd66d1c8bb..a1db92641f5e 100644 --- a/crates/ide-diagnostics/src/lib.rs +++ b/crates/ide-diagnostics/src/lib.rs @@ -568,10 +568,10 @@ fn handle_diag_from_macros( diag.fixes = None; // All Clippy lints report in macros, see https://github.com/rust-lang/rust-clippy/blob/903293b199364/declare_clippy_lint/src/lib.rs#L172. - if let DiagnosticCode::RustcLint(lint) = diag.code { - if !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint) { - return false; - } + if let DiagnosticCode::RustcLint(lint) = diag.code + && !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint) + { + return false; }; } true @@ -760,35 +760,35 @@ fn cfg_attr_lint_attrs( } while let Some(value) = iter.next() { - if let Some(token) = value.as_token() { - if token.kind() == SyntaxKind::IDENT { - let severity = match token.text() { - "allow" | "expect" => Some(Severity::Allow), - "warn" => Some(Severity::Warning), - "forbid" | "deny" => Some(Severity::Error), - "cfg_attr" => { - if let Some(NodeOrToken::Node(value)) = iter.next() { - cfg_attr_lint_attrs(sema, &value, lint_attrs); - } - None - } - _ => None, - }; - if let Some(severity) = severity { - let lints = iter.next(); - if let Some(NodeOrToken::Node(lints)) = lints { - lint_attrs.push((severity, lints)); + if let Some(token) = value.as_token() + && token.kind() == SyntaxKind::IDENT + { + let severity = match token.text() { + "allow" | "expect" => Some(Severity::Allow), + "warn" => Some(Severity::Warning), + "forbid" | "deny" => Some(Severity::Error), + "cfg_attr" => { + if let Some(NodeOrToken::Node(value)) = iter.next() { + cfg_attr_lint_attrs(sema, &value, lint_attrs); } + None + } + _ => None, + }; + if let Some(severity) = severity { + let lints = iter.next(); + if let Some(NodeOrToken::Node(lints)) = lints { + lint_attrs.push((severity, lints)); } } } } - if prev_len != lint_attrs.len() { - if let Some(false) | None = sema.check_cfg_attr(value) { - // Discard the attributes when the condition is false. - lint_attrs.truncate(prev_len); - } + if prev_len != lint_attrs.len() + && let Some(false) | None = sema.check_cfg_attr(value) + { + // Discard the attributes when the condition is false. + lint_attrs.truncate(prev_len); } } diff --git a/crates/ide-ssr/src/lib.rs b/crates/ide-ssr/src/lib.rs index e4b20f3f1aad..138af22089eb 100644 --- a/crates/ide-ssr/src/lib.rs +++ b/crates/ide-ssr/src/lib.rs @@ -283,17 +283,16 @@ impl<'db> MatchFinder<'db> { node: node.clone(), }); } - } else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) { - if let Some(expanded) = self.sema.expand_macro_call(¯o_call) { - if let Some(tt) = macro_call.token_tree() { - self.output_debug_for_nodes_at_range( - &expanded.value, - range, - &Some(self.sema.original_range(tt.syntax())), - out, - ); - } - } + } else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) + && let Some(expanded) = self.sema.expand_macro_call(¯o_call) + && let Some(tt) = macro_call.token_tree() + { + self.output_debug_for_nodes_at_range( + &expanded.value, + range, + &Some(self.sema.original_range(tt.syntax())), + out, + ); } self.output_debug_for_nodes_at_range(&node, range, restrict_range, out); } diff --git a/crates/ide-ssr/src/matching.rs b/crates/ide-ssr/src/matching.rs index b350315ba548..f21132c297ee 100644 --- a/crates/ide-ssr/src/matching.rs +++ b/crates/ide-ssr/src/matching.rs @@ -156,12 +156,11 @@ impl<'db, 'sema> Matcher<'db, 'sema> { /// processing a macro expansion and we want to fail the match if we're working with a node that /// didn't originate from the token tree of the macro call. fn validate_range(&self, range: &FileRange) -> Result<(), MatchFailed> { - if let Some(restrict_range) = &self.restrict_range { - if restrict_range.file_id != range.file_id - || !restrict_range.range.contains_range(range.range) - { - fail_match!("Node originated from a macro"); - } + if let Some(restrict_range) = &self.restrict_range + && (restrict_range.file_id != range.file_id + || !restrict_range.range.contains_range(range.range)) + { + fail_match!("Node originated from a macro"); } Ok(()) } @@ -404,30 +403,27 @@ impl<'db, 'sema> Matcher<'db, 'sema> { // Build a map keyed by field name. let mut fields_by_name: FxHashMap = FxHashMap::default(); for child in code.children() { - if let Some(record) = ast::RecordExprField::cast(child.clone()) { - if let Some(name) = record.field_name() { - fields_by_name.insert(name.text().into(), child.clone()); - } + if let Some(record) = ast::RecordExprField::cast(child.clone()) + && let Some(name) = record.field_name() + { + fields_by_name.insert(name.text().into(), child.clone()); } } for p in pattern.children_with_tokens() { - if let SyntaxElement::Node(p) = p { - if let Some(name_element) = p.first_child_or_token() { - if self.get_placeholder(&name_element).is_some() { - // If the pattern is using placeholders for field names then order - // independence doesn't make sense. Fall back to regular ordered - // matching. - return self.attempt_match_node_children(phase, pattern, code); - } - if let Some(ident) = only_ident(name_element) { - let code_record = fields_by_name.remove(ident.text()).ok_or_else(|| { - match_error!( - "Placeholder has record field '{}', but code doesn't", - ident - ) - })?; - self.attempt_match_node(phase, &p, &code_record)?; - } + if let SyntaxElement::Node(p) = p + && let Some(name_element) = p.first_child_or_token() + { + if self.get_placeholder(&name_element).is_some() { + // If the pattern is using placeholders for field names then order + // independence doesn't make sense. Fall back to regular ordered + // matching. + return self.attempt_match_node_children(phase, pattern, code); + } + if let Some(ident) = only_ident(name_element) { + let code_record = fields_by_name.remove(ident.text()).ok_or_else(|| { + match_error!("Placeholder has record field '{}', but code doesn't", ident) + })?; + self.attempt_match_node(phase, &p, &code_record)?; } } } @@ -476,14 +472,13 @@ impl<'db, 'sema> Matcher<'db, 'sema> { } } SyntaxElement::Node(n) => { - if let Some(first_token) = n.first_token() { - if Some(first_token.text()) == next_pattern_token.as_deref() { - if let Some(SyntaxElement::Node(p)) = pattern.next() { - // We have a subtree that starts with the next token in our pattern. - self.attempt_match_token_tree(phase, &p, n)?; - break; - } - } + if let Some(first_token) = n.first_token() + && Some(first_token.text()) == next_pattern_token.as_deref() + && let Some(SyntaxElement::Node(p)) = pattern.next() + { + // We have a subtree that starts with the next token in our pattern. + self.attempt_match_token_tree(phase, &p, n)?; + break; } } }; @@ -562,23 +557,22 @@ impl<'db, 'sema> Matcher<'db, 'sema> { let deref_count = self.check_expr_type(pattern_type, expr)?; let pattern_receiver = pattern_args.next(); self.attempt_match_opt(phase, pattern_receiver.clone(), code.receiver())?; - if let Phase::Second(match_out) = phase { - if let Some(placeholder_value) = pattern_receiver + if let Phase::Second(match_out) = phase + && let Some(placeholder_value) = pattern_receiver .and_then(|n| self.get_placeholder_for_node(n.syntax())) .and_then(|placeholder| { match_out.placeholder_values.get_mut(&placeholder.ident) }) - { - placeholder_value.autoderef_count = deref_count; - placeholder_value.autoref_kind = self - .sema - .resolve_method_call_as_callable(code) - .and_then(|callable| { - let (self_param, _) = callable.receiver_param(self.sema.db)?; - Some(self.sema.source(self_param)?.value.kind()) - }) - .unwrap_or(ast::SelfParamKind::Owned); - } + { + placeholder_value.autoderef_count = deref_count; + placeholder_value.autoref_kind = self + .sema + .resolve_method_call_as_callable(code) + .and_then(|callable| { + let (self_param, _) = callable.receiver_param(self.sema.db)?; + Some(self.sema.source(self_param)?.value.kind()) + }) + .unwrap_or(ast::SelfParamKind::Owned); } } } else { @@ -698,12 +692,11 @@ impl Phase<'_> { } fn record_ignored_comments(&mut self, token: &SyntaxToken) { - if token.kind() == SyntaxKind::COMMENT { - if let Phase::Second(match_out) = self { - if let Some(comment) = ast::Comment::cast(token.clone()) { - match_out.ignored_comments.push(comment); - } - } + if token.kind() == SyntaxKind::COMMENT + && let Phase::Second(match_out) = self + && let Some(comment) = ast::Comment::cast(token.clone()) + { + match_out.ignored_comments.push(comment); } } } diff --git a/crates/ide-ssr/src/replacing.rs b/crates/ide-ssr/src/replacing.rs index 752edd6535a6..16287a439c35 100644 --- a/crates/ide-ssr/src/replacing.rs +++ b/crates/ide-ssr/src/replacing.rs @@ -112,12 +112,12 @@ impl<'db> ReplacementRenderer<'_, 'db> { self.out.push_str(&mod_path.display(self.db, self.edition).to_string()); // Emit everything except for the segment's name-ref, since we already effectively // emitted that as part of `mod_path`. - if let Some(path) = ast::Path::cast(node.clone()) { - if let Some(segment) = path.segment() { - for node_or_token in segment.syntax().children_with_tokens() { - if node_or_token.kind() != SyntaxKind::NAME_REF { - self.render_node_or_token(&node_or_token); - } + if let Some(path) = ast::Path::cast(node.clone()) + && let Some(segment) = path.segment() + { + for node_or_token in segment.syntax().children_with_tokens() { + if node_or_token.kind() != SyntaxKind::NAME_REF { + self.render_node_or_token(&node_or_token); } } } @@ -242,15 +242,15 @@ fn token_is_method_call_receiver(token: &SyntaxToken) -> bool { } fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option { - if ast::Expr::can_cast(kind) { - if let Ok(expr) = fragments::expr(code) { - return Some(expr); - } + if ast::Expr::can_cast(kind) + && let Ok(expr) = fragments::expr(code) + { + return Some(expr); } - if ast::Item::can_cast(kind) { - if let Ok(item) = fragments::item(code) { - return Some(item); - } + if ast::Item::can_cast(kind) + && let Ok(item) = fragments::item(code) + { + return Some(item); } None } diff --git a/crates/ide-ssr/src/resolving.rs b/crates/ide-ssr/src/resolving.rs index 8f28a1cd3a62..a4e2cfbaee27 100644 --- a/crates/ide-ssr/src/resolving.rs +++ b/crates/ide-ssr/src/resolving.rs @@ -83,21 +83,17 @@ impl<'db> Resolver<'_, 'db> { let ufcs_function_calls = resolved_paths .iter() .filter_map(|(path_node, resolved)| { - if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) { - if let Some(call_expr) = ast::CallExpr::cast(grandparent.clone()) { - if let hir::PathResolution::Def(hir::ModuleDef::Function(function)) = - resolved.resolution - { - if function.as_assoc_item(self.resolution_scope.scope.db).is_some() { - let qualifier_type = - self.resolution_scope.qualifier_type(path_node); - return Some(( - grandparent, - UfcsCallInfo { call_expr, function, qualifier_type }, - )); - } - } - } + if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) + && let Some(call_expr) = ast::CallExpr::cast(grandparent.clone()) + && let hir::PathResolution::Def(hir::ModuleDef::Function(function)) = + resolved.resolution + && function.as_assoc_item(self.resolution_scope.scope.db).is_some() + { + let qualifier_type = self.resolution_scope.qualifier_type(path_node); + return Some(( + grandparent, + UfcsCallInfo { call_expr, function, qualifier_type }, + )); } None }) @@ -153,12 +149,11 @@ impl<'db> Resolver<'_, 'db> { /// Returns whether `path` contains a placeholder, but ignores any placeholders within type /// arguments. fn path_contains_placeholder(&self, path: &ast::Path) -> bool { - if let Some(segment) = path.segment() { - if let Some(name_ref) = segment.name_ref() { - if self.placeholders_by_stand_in.contains_key(name_ref.text().as_str()) { - return true; - } - } + if let Some(segment) = path.segment() + && let Some(name_ref) = segment.name_ref() + && self.placeholders_by_stand_in.contains_key(name_ref.text().as_str()) + { + return true; } if let Some(qualifier) = path.qualifier() { return self.path_contains_placeholder(&qualifier); @@ -252,14 +247,12 @@ impl<'db> ResolutionScope<'db> { fn qualifier_type(&self, path: &SyntaxNode) -> Option> { use syntax::ast::AstNode; - if let Some(path) = ast::Path::cast(path.clone()) { - if let Some(qualifier) = path.qualifier() { - if let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) = - self.resolve_path(&qualifier) - { - return Some(adt.ty(self.scope.db)); - } - } + if let Some(path) = ast::Path::cast(path.clone()) + && let Some(qualifier) = path.qualifier() + && let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) = + self.resolve_path(&qualifier) + { + return Some(adt.ty(self.scope.db)); } None } @@ -299,11 +292,11 @@ fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode { /// Returns whether `path` or any of its qualifiers contains type arguments. fn path_contains_type_arguments(path: Option) -> bool { if let Some(path) = path { - if let Some(segment) = path.segment() { - if segment.generic_arg_list().is_some() { - cov_mark::hit!(type_arguments_within_path); - return true; - } + if let Some(segment) = path.segment() + && segment.generic_arg_list().is_some() + { + cov_mark::hit!(type_arguments_within_path); + return true; } return path_contains_type_arguments(path.qualifier()); } diff --git a/crates/ide-ssr/src/search.rs b/crates/ide-ssr/src/search.rs index 99a98fb2a713..72f857ceda90 100644 --- a/crates/ide-ssr/src/search.rs +++ b/crates/ide-ssr/src/search.rs @@ -187,16 +187,15 @@ impl<'db> MatchFinder<'db> { self.try_add_match(rule, code, restrict_range, matches_out); // If we've got a macro call, we already tried matching it pre-expansion, which is the only // way to match the whole macro, now try expanding it and matching the expansion. - if let Some(macro_call) = ast::MacroCall::cast(code.clone()) { - if let Some(expanded) = self.sema.expand_macro_call(¯o_call) { - if let Some(tt) = macro_call.token_tree() { - // When matching within a macro expansion, we only want to allow matches of - // nodes that originated entirely from within the token tree of the macro call. - // i.e. we don't want to match something that came from the macro itself. - if let Some(range) = self.sema.original_range_opt(tt.syntax()) { - self.slow_scan_node(&expanded.value, rule, &Some(range), matches_out); - } - } + if let Some(macro_call) = ast::MacroCall::cast(code.clone()) + && let Some(expanded) = self.sema.expand_macro_call(¯o_call) + && let Some(tt) = macro_call.token_tree() + { + // When matching within a macro expansion, we only want to allow matches of + // nodes that originated entirely from within the token tree of the macro call. + // i.e. we don't want to match something that came from the macro itself. + if let Some(range) = self.sema.original_range_opt(tt.syntax()) { + self.slow_scan_node(&expanded.value, rule, &Some(range), matches_out); } } for child in code.children() { @@ -241,10 +240,10 @@ impl<'db> MatchFinder<'db> { /// Returns whether we support matching within `node` and all of its ancestors. fn is_search_permitted_ancestors(node: &SyntaxNode) -> bool { - if let Some(parent) = node.parent() { - if !is_search_permitted_ancestors(&parent) { - return false; - } + if let Some(parent) = node.parent() + && !is_search_permitted_ancestors(&parent) + { + return false; } is_search_permitted(node) } diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index 05196ac98c03..dec1889926da 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -159,10 +159,10 @@ pub(crate) fn annotations( node.value.syntax().text_range(), Some(name), ); - if res.call_site.0.file_id == source_file_id { - if let Some(name_range) = res.call_site.1 { - return Some((res.call_site.0.range, Some(name_range))); - } + if res.call_site.0.file_id == source_file_id + && let Some(name_range) = res.call_site.1 + { + return Some((res.call_site.0.range, Some(name_range))); } }; // otherwise try upmapping the entire node out of attributes diff --git a/crates/ide/src/expand_macro.rs b/crates/ide/src/expand_macro.rs index f31886b96976..ad84eacfb3e8 100644 --- a/crates/ide/src/expand_macro.rs +++ b/crates/ide/src/expand_macro.rs @@ -96,14 +96,14 @@ pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option< let (name, expanded, kind) = loop { let node = anc.next()?; - if let Some(item) = ast::Item::cast(node.clone()) { - if let Some(def) = sema.resolve_attr_macro_call(&item) { - break ( - def.name(db).display(db, file_id.edition(db)).to_string(), - expand_macro_recur(&sema, &item, &mut error, &mut span_map, TextSize::new(0))?, - SyntaxKind::MACRO_ITEMS, - ); - } + if let Some(item) = ast::Item::cast(node.clone()) + && let Some(def) = sema.resolve_attr_macro_call(&item) + { + break ( + def.name(db).display(db, file_id.edition(db)).to_string(), + expand_macro_recur(&sema, &item, &mut error, &mut span_map, TextSize::new(0))?, + SyntaxKind::MACRO_ITEMS, + ); } if let Some(mac) = ast::MacroCall::cast(node) { let mut name = mac.path()?.segment()?.name_ref()?.to_string(); diff --git a/crates/ide/src/extend_selection.rs b/crates/ide/src/extend_selection.rs index a374f9752fcf..2926384c4078 100644 --- a/crates/ide/src/extend_selection.rs +++ b/crates/ide/src/extend_selection.rs @@ -81,10 +81,10 @@ fn try_extend_selection( if token.text_range() != range { return Some(token.text_range()); } - if let Some(comment) = ast::Comment::cast(token.clone()) { - if let Some(range) = extend_comments(comment) { - return Some(range); - } + if let Some(comment) = ast::Comment::cast(token.clone()) + && let Some(range) = extend_comments(comment) + { + return Some(range); } token.parent()? } @@ -92,12 +92,11 @@ fn try_extend_selection( }; // if we are in single token_tree, we maybe live in macro or attr - if node.kind() == TOKEN_TREE { - if let Some(macro_call) = node.ancestors().find_map(ast::MacroCall::cast) { - if let Some(range) = extend_tokens_from_range(sema, macro_call, range) { - return Some(range); - } - } + if node.kind() == TOKEN_TREE + && let Some(macro_call) = node.ancestors().find_map(ast::MacroCall::cast) + && let Some(range) = extend_tokens_from_range(sema, macro_call, range) + { + return Some(range); } if node.text_range() != range { @@ -106,10 +105,10 @@ fn try_extend_selection( let node = shallowest_node(&node); - if node.parent().is_some_and(|n| list_kinds.contains(&n.kind())) { - if let Some(range) = extend_list_item(&node) { - return Some(range); - } + if node.parent().is_some_and(|n| list_kinds.contains(&n.kind())) + && let Some(range) = extend_list_item(&node) + { + return Some(range); } node.parent().map(|it| it.text_range()) @@ -221,19 +220,20 @@ fn extend_ws(root: &SyntaxNode, ws: SyntaxToken, offset: TextSize) -> TextRange let prefix = TextRange::new(ws.text_range().start(), offset) - ws.text_range().start(); let ws_suffix = &ws_text[suffix]; let ws_prefix = &ws_text[prefix]; - if ws_text.contains('\n') && !ws_suffix.contains('\n') { - if let Some(node) = ws.next_sibling_or_token() { - let start = match ws_prefix.rfind('\n') { - Some(idx) => ws.text_range().start() + TextSize::from((idx + 1) as u32), - None => node.text_range().start(), - }; - let end = if root.text().char_at(node.text_range().end()) == Some('\n') { - node.text_range().end() + TextSize::of('\n') - } else { - node.text_range().end() - }; - return TextRange::new(start, end); - } + if ws_text.contains('\n') + && !ws_suffix.contains('\n') + && let Some(node) = ws.next_sibling_or_token() + { + let start = match ws_prefix.rfind('\n') { + Some(idx) => ws.text_range().start() + TextSize::from((idx + 1) as u32), + None => node.text_range().start(), + }; + let end = if root.text().char_at(node.text_range().end()) == Some('\n') { + node.text_range().end() + TextSize::of('\n') + } else { + node.text_range().end() + }; + return TextRange::new(start, end); } ws.text_range() } diff --git a/crates/ide/src/folding_ranges.rs b/crates/ide/src/folding_ranges.rs index 1901bcc797e7..ac64413effeb 100755 --- a/crates/ide/src/folding_ranges.rs +++ b/crates/ide/src/folding_ranges.rs @@ -61,30 +61,29 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec { }; if is_multiline { // for the func with multiline param list - if matches!(element.kind(), FN) { - if let NodeOrToken::Node(node) = &element { - if let Some(fn_node) = ast::Fn::cast(node.clone()) { - if !fn_node - .param_list() - .map(|param_list| param_list.syntax().text().contains_char('\n')) - .unwrap_or(false) - { - continue; - } + if matches!(element.kind(), FN) + && let NodeOrToken::Node(node) = &element + && let Some(fn_node) = ast::Fn::cast(node.clone()) + { + if !fn_node + .param_list() + .map(|param_list| param_list.syntax().text().contains_char('\n')) + .unwrap_or(false) + { + continue; + } - if fn_node.body().is_some() { - // Get the actual start of the function (excluding doc comments) - let fn_start = fn_node - .fn_token() - .map(|token| token.text_range().start()) - .unwrap_or(node.text_range().start()); - res.push(Fold { - range: TextRange::new(fn_start, node.text_range().end()), - kind: FoldKind::Function, - }); - continue; - } - } + if fn_node.body().is_some() { + // Get the actual start of the function (excluding doc comments) + let fn_start = fn_node + .fn_token() + .map(|token| token.text_range().start()) + .unwrap_or(node.text_range().start()); + res.push(Fold { + range: TextRange::new(fn_start, node.text_range().end()), + kind: FoldKind::Function, + }); + continue; } } res.push(Fold { range: element.text_range(), kind }); @@ -120,14 +119,13 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec { match_ast! { match node { ast::Module(module) => { - if module.item_list().is_none() { - if let Some(range) = contiguous_range_for_item_group( + if module.item_list().is_none() + && let Some(range) = contiguous_range_for_item_group( module, &mut visited_nodes, ) { res.push(Fold { range, kind: FoldKind::Modules }) } - } }, ast::Use(use_) => { if let Some(range) = contiguous_range_for_item_group(use_, &mut visited_nodes) { @@ -212,11 +210,11 @@ where for element in first.syntax().siblings_with_tokens(Direction::Next) { let node = match element { NodeOrToken::Token(token) => { - if let Some(ws) = ast::Whitespace::cast(token) { - if !ws.spans_multiple_lines() { - // Ignore whitespace without blank lines - continue; - } + if let Some(ws) = ast::Whitespace::cast(token) + && !ws.spans_multiple_lines() + { + // Ignore whitespace without blank lines + continue; } // There is a blank line or another token, which means that the // group ends here @@ -270,21 +268,21 @@ fn contiguous_range_for_comment( for element in first.syntax().siblings_with_tokens(Direction::Next) { match element { NodeOrToken::Token(token) => { - if let Some(ws) = ast::Whitespace::cast(token.clone()) { - if !ws.spans_multiple_lines() { - // Ignore whitespace without blank lines - continue; - } + if let Some(ws) = ast::Whitespace::cast(token.clone()) + && !ws.spans_multiple_lines() + { + // Ignore whitespace without blank lines + continue; } - if let Some(c) = ast::Comment::cast(token) { - if c.kind() == group_kind { - let text = c.text().trim_start(); - // regions are not real comments - if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) { - visited.insert(c.clone()); - last = c; - continue; - } + if let Some(c) = ast::Comment::cast(token) + && c.kind() == group_kind + { + let text = c.text().trim_start(); + // regions are not real comments + if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) { + visited.insert(c.clone()); + last = c; + continue; } } // The comment group ends because either: diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index 29fc68bb50f1..84e41277390f 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs @@ -94,18 +94,17 @@ pub(crate) fn goto_definition( let parent = token.value.parent()?; let token_file_id = token.file_id; - if let Some(token) = ast::String::cast(token.value.clone()) { - if let Some(x) = + if let Some(token) = ast::String::cast(token.value.clone()) + && let Some(x) = try_lookup_include_path(sema, InFile::new(token_file_id, token), file_id) - { - return Some(vec![x]); - } + { + return Some(vec![x]); } - if ast::TokenTree::can_cast(parent.kind()) { - if let Some(x) = try_lookup_macro_def_in_macro_use(sema, token.value) { - return Some(vec![x]); - } + if ast::TokenTree::can_cast(parent.kind()) + && let Some(x) = try_lookup_macro_def_in_macro_use(sema, token.value) + { + return Some(vec![x]); } Some( @@ -245,12 +244,11 @@ fn try_lookup_macro_def_in_macro_use( let krate = extern_crate.resolved_crate(sema.db)?; for mod_def in krate.root_module().declarations(sema.db) { - if let ModuleDef::Macro(mac) = mod_def { - if mac.name(sema.db).as_str() == token.text() { - if let Some(nav) = mac.try_to_nav(sema.db) { - return Some(nav.call_site); - } - } + if let ModuleDef::Macro(mac) = mod_def + && mac.name(sema.db).as_str() == token.text() + && let Some(nav) = mac.try_to_nav(sema.db) + { + return Some(nav.call_site); } } diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index 356bd69aa44e..9960e79a5380 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -722,20 +722,19 @@ impl<'a> WalkExpandedExprCtx<'a> { self.depth += 1; } - if let ast::Expr::MacroExpr(expr) = expr { - if let Some(expanded) = + if let ast::Expr::MacroExpr(expr) = expr + && let Some(expanded) = expr.macro_call().and_then(|call| self.sema.expand_macro_call(&call)) - { - match_ast! { - match (expanded.value) { - ast::MacroStmts(it) => { - self.handle_expanded(it, cb); - }, - ast::Expr(it) => { - self.walk(&it, cb); - }, - _ => {} - } + { + match_ast! { + match (expanded.value) { + ast::MacroStmts(it) => { + self.handle_expanded(it, cb); + }, + ast::Expr(it) => { + self.walk(&it, cb); + }, + _ => {} } } } @@ -755,10 +754,10 @@ impl<'a> WalkExpandedExprCtx<'a> { } for stmt in expanded.statements() { - if let ast::Stmt::ExprStmt(stmt) = stmt { - if let Some(expr) = stmt.expr() { - self.walk(&expr, cb); - } + if let ast::Stmt::ExprStmt(stmt) = stmt + && let Some(expr) = stmt.expr() + { + self.walk(&expr, cb); } } } @@ -806,12 +805,12 @@ pub(crate) fn highlight_unsafe_points( push_to_highlights(unsafe_token_file_id, Some(unsafe_token.text_range())); // highlight unsafe operations - if let Some(block) = block_expr { - if let Some(body) = sema.body_for(InFile::new(unsafe_token_file_id, block.syntax())) { - let unsafe_ops = sema.get_unsafe_ops(body); - for unsafe_op in unsafe_ops { - push_to_highlights(unsafe_op.file_id, Some(unsafe_op.value.text_range())); - } + if let Some(block) = block_expr + && let Some(body) = sema.body_for(InFile::new(unsafe_token_file_id, block.syntax())) + { + let unsafe_ops = sema.get_unsafe_ops(body); + for unsafe_op in unsafe_ops { + push_to_highlights(unsafe_op.file_id, Some(unsafe_op.value.text_range())); } } diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index e4d6279759ed..44c98a43f694 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -244,17 +244,15 @@ fn hover_offset( let node = token.parent()?; // special case macro calls, we wanna render the invoked arm index - if let Some(name) = ast::NameRef::cast(node.clone()) { - if let Some(path_seg) = + if let Some(name) = ast::NameRef::cast(node.clone()) + && let Some(path_seg) = name.syntax().parent().and_then(ast::PathSegment::cast) - { - if let Some(macro_call) = path_seg + && let Some(macro_call) = path_seg .parent_path() .syntax() .parent() .and_then(ast::MacroCall::cast) - { - if let Some(macro_) = sema.resolve_macro_call(¯o_call) { + && let Some(macro_) = sema.resolve_macro_call(¯o_call) { break 'a vec![( (Definition::Macro(macro_), None), sema.resolve_macro_call_arm(¯o_call), @@ -262,9 +260,6 @@ fn hover_offset( node, )]; } - } - } - } match IdentClass::classify_node(sema, &node)? { // It's better for us to fall back to the keyword hover here, diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index 670210d4998d..51b5900e8155 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -95,23 +95,25 @@ pub(super) fn try_expr( if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts { let famous_defs = FamousDefs(sema, sema.scope(try_expr.syntax())?.krate()); // special case for two options, there is no value in showing them - if let Some(option_enum) = famous_defs.core_option_Option() { - if inner == option_enum && body == option_enum { - cov_mark::hit!(hover_try_expr_opt_opt); - return None; - } + if let Some(option_enum) = famous_defs.core_option_Option() + && inner == option_enum + && body == option_enum + { + cov_mark::hit!(hover_try_expr_opt_opt); + return None; } // special case two results to show the error variants only - if let Some(result_enum) = famous_defs.core_result_Result() { - if inner == result_enum && body == result_enum { - let error_type_args = - inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1)); - if let Some((inner, body)) = error_type_args { - inner_ty = inner; - body_ty = body; - "Try Error".clone_into(&mut s); - } + if let Some(result_enum) = famous_defs.core_result_Result() + && inner == result_enum + && body == result_enum + { + let error_type_args = + inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1)); + if let Some((inner, body)) = error_type_args { + inner_ty = inner; + body_ty = body; + "Try Error".clone_into(&mut s); } } } @@ -1132,10 +1134,10 @@ fn markup( ) -> (Markup, Option) { let mut buf = String::new(); - if let Some(mod_path) = mod_path { - if !mod_path.is_empty() { - format_to!(buf, "```rust\n{}\n```\n\n", mod_path); - } + if let Some(mod_path) = mod_path + && !mod_path.is_empty() + { + format_to!(buf, "```rust\n{}\n```\n\n", mod_path); } format_to!(buf, "```rust\n{}\n```", rust); @@ -1217,55 +1219,55 @@ fn render_memory_layout( format_to!(label, ", "); } - if let Some(render) = config.offset { - if let Some(offset) = offset(&layout) { - format_to!(label, "offset = "); - match render { - MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{offset}"), - MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{offset:#X}"), - MemoryLayoutHoverRenderKind::Both if offset >= 10 => { - format_to!(label, "{offset} ({offset:#X})") - } - MemoryLayoutHoverRenderKind::Both => { - format_to!(label, "{offset}") - } + if let Some(render) = config.offset + && let Some(offset) = offset(&layout) + { + format_to!(label, "offset = "); + match render { + MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{offset}"), + MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{offset:#X}"), + MemoryLayoutHoverRenderKind::Both if offset >= 10 => { + format_to!(label, "{offset} ({offset:#X})") + } + MemoryLayoutHoverRenderKind::Both => { + format_to!(label, "{offset}") } - format_to!(label, ", "); } + format_to!(label, ", "); } - if let Some(render) = config.padding { - if let Some((padding_name, padding)) = padding(&layout) { - format_to!(label, "{padding_name} = "); - match render { - MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{padding}"), - MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{padding:#X}"), - MemoryLayoutHoverRenderKind::Both if padding >= 10 => { - format_to!(label, "{padding} ({padding:#X})") - } - MemoryLayoutHoverRenderKind::Both => { - format_to!(label, "{padding}") - } + if let Some(render) = config.padding + && let Some((padding_name, padding)) = padding(&layout) + { + format_to!(label, "{padding_name} = "); + match render { + MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{padding}"), + MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{padding:#X}"), + MemoryLayoutHoverRenderKind::Both if padding >= 10 => { + format_to!(label, "{padding} ({padding:#X})") + } + MemoryLayoutHoverRenderKind::Both => { + format_to!(label, "{padding}") } - format_to!(label, ", "); } + format_to!(label, ", "); } - if config.niches { - if let Some(niches) = layout.niches() { - if niches > 1024 { - if niches.is_power_of_two() { - format_to!(label, "niches = 2{}, ", pwr2_to_exponent(niches)); - } else if is_pwr2plus1(niches) { - format_to!(label, "niches = 2{} + 1, ", pwr2_to_exponent(niches - 1)); - } else if is_pwr2minus1(niches) { - format_to!(label, "niches = 2{} - 1, ", pwr2_to_exponent(niches + 1)); - } else { - format_to!(label, "niches = a lot, "); - } + if config.niches + && let Some(niches) = layout.niches() + { + if niches > 1024 { + if niches.is_power_of_two() { + format_to!(label, "niches = 2{}, ", pwr2_to_exponent(niches)); + } else if is_pwr2plus1(niches) { + format_to!(label, "niches = 2{} + 1, ", pwr2_to_exponent(niches - 1)); + } else if is_pwr2minus1(niches) { + format_to!(label, "niches = 2{} - 1, ", pwr2_to_exponent(niches + 1)); } else { - format_to!(label, "niches = {niches}, "); + format_to!(label, "niches = a lot, "); } + } else { + format_to!(label, "niches = {niches}, "); } } label.pop(); // ' ' diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs index 671fddb43630..7a8514c47af9 100644 --- a/crates/ide/src/inlay_hints.rs +++ b/crates/ide/src/inlay_hints.rs @@ -576,13 +576,13 @@ impl InlayHintLabel { } pub fn append_part(&mut self, part: InlayHintLabelPart) { - if part.linked_location.is_none() && part.tooltip.is_none() { - if let Some(InlayHintLabelPart { text, linked_location: None, tooltip: None }) = + if part.linked_location.is_none() + && part.tooltip.is_none() + && let Some(InlayHintLabelPart { text, linked_location: None, tooltip: None }) = self.parts.last_mut() - { - text.push_str(&part.text); - return; - } + { + text.push_str(&part.text); + return; } self.parts.push(part); } diff --git a/crates/ide/src/inlay_hints/adjustment.rs b/crates/ide/src/inlay_hints/adjustment.rs index 49b43fc37f24..4d020bac3aad 100644 --- a/crates/ide/src/inlay_hints/adjustment.rs +++ b/crates/ide/src/inlay_hints/adjustment.rs @@ -39,10 +39,10 @@ pub(super) fn hints( if let ast::Expr::ParenExpr(_) = expr { return None; } - if let ast::Expr::BlockExpr(b) = expr { - if !b.is_standalone() { - return None; - } + if let ast::Expr::BlockExpr(b) = expr + && !b.is_standalone() + { + return None; } let descended = sema.descend_node_into_attributes(expr.clone()).pop(); diff --git a/crates/ide/src/inlay_hints/bind_pat.rs b/crates/ide/src/inlay_hints/bind_pat.rs index 729349365e6c..922e9598aa01 100644 --- a/crates/ide/src/inlay_hints/bind_pat.rs +++ b/crates/ide/src/inlay_hints/bind_pat.rs @@ -41,13 +41,11 @@ pub(super) fn hints( Some(it.colon_token()) }, ast::LetStmt(it) => { - if config.hide_closure_initialization_hints { - if let Some(ast::Expr::ClosureExpr(closure)) = it.initializer() { - if closure_has_block_body(&closure) { + if config.hide_closure_initialization_hints + && let Some(ast::Expr::ClosureExpr(closure)) = it.initializer() + && closure_has_block_body(&closure) { return None; } - } - } if it.ty().is_some() { return None; } diff --git a/crates/ide/src/inlay_hints/chaining.rs b/crates/ide/src/inlay_hints/chaining.rs index ff157fa171b5..a8bb652fda22 100644 --- a/crates/ide/src/inlay_hints/chaining.rs +++ b/crates/ide/src/inlay_hints/chaining.rs @@ -51,12 +51,11 @@ pub(super) fn hints( if ty.is_unknown() { return None; } - if matches!(expr, ast::Expr::PathExpr(_)) { - if let Some(hir::Adt::Struct(st)) = ty.as_adt() { - if st.fields(sema.db).is_empty() { - return None; - } - } + if matches!(expr, ast::Expr::PathExpr(_)) + && let Some(hir::Adt::Struct(st)) = ty.as_adt() + && st.fields(sema.db).is_empty() + { + return None; } let label = label_of_ty(famous_defs, config, &ty, display_target)?; acc.push(InlayHint { diff --git a/crates/ide/src/inlay_hints/closing_brace.rs b/crates/ide/src/inlay_hints/closing_brace.rs index 05253b679489..e80c9dc9d473 100644 --- a/crates/ide/src/inlay_hints/closing_brace.rs +++ b/crates/ide/src/inlay_hints/closing_brace.rs @@ -120,11 +120,11 @@ pub(super) fn hints( }; if let Some(mut next) = closing_token.next_token() { - if next.kind() == T![;] { - if let Some(tok) = next.next_token() { - closing_token = next; - next = tok; - } + if next.kind() == T![;] + && let Some(tok) = next.next_token() + { + closing_token = next; + next = tok; } if !(next.kind() == SyntaxKind::WHITESPACE && next.text().contains('\n')) { // Only display the hint if the `}` is the last token on the line diff --git a/crates/ide/src/inlay_hints/closure_ret.rs b/crates/ide/src/inlay_hints/closure_ret.rs index 9e600b5455be..fef1cb83c119 100644 --- a/crates/ide/src/inlay_hints/closure_ret.rs +++ b/crates/ide/src/inlay_hints/closure_ret.rs @@ -55,11 +55,9 @@ pub(super) fn hints( // Insert braces if necessary let insert_braces = |builder: &mut TextEditBuilder| { - if !has_block_body { - if let Some(range) = closure.body().map(|b| b.syntax().text_range()) { - builder.insert(range.start(), "{ ".to_owned()); - builder.insert(range.end(), " }".to_owned()); - } + if !has_block_body && let Some(range) = closure.body().map(|b| b.syntax().text_range()) { + builder.insert(range.start(), "{ ".to_owned()); + builder.insert(range.end(), " }".to_owned()); } }; diff --git a/crates/ide/src/inlay_hints/extern_block.rs b/crates/ide/src/inlay_hints/extern_block.rs index 88152bf3e388..491018a4dda8 100644 --- a/crates/ide/src/inlay_hints/extern_block.rs +++ b/crates/ide/src/inlay_hints/extern_block.rs @@ -81,10 +81,10 @@ fn item_hint( text_edit: Some(config.lazy_text_edit(|| { let mut builder = TextEdit::builder(); builder.insert(token.text_range().start(), "unsafe ".to_owned()); - if extern_block.unsafe_token().is_none() { - if let Some(abi) = extern_block.abi() { - builder.insert(abi.syntax().text_range().start(), "unsafe ".to_owned()); - } + if extern_block.unsafe_token().is_none() + && let Some(abi) = extern_block.abi() + { + builder.insert(abi.syntax().text_range().start(), "unsafe ".to_owned()); } builder.finish() })), diff --git a/crates/ide/src/inlay_hints/generic_param.rs b/crates/ide/src/inlay_hints/generic_param.rs index 6e1b3bdbdf03..1fddb6fbe01d 100644 --- a/crates/ide/src/inlay_hints/generic_param.rs +++ b/crates/ide/src/inlay_hints/generic_param.rs @@ -33,10 +33,10 @@ pub(crate) fn hints( let mut args = generic_arg_list.generic_args().peekable(); let start_with_lifetime = matches!(args.peek()?, ast::GenericArg::LifetimeArg(_)); let params = generic_def.params(sema.db).into_iter().filter(|p| { - if let hir::GenericParam::TypeParam(it) = p { - if it.is_implicit(sema.db) { - return false; - } + if let hir::GenericParam::TypeParam(it) = p + && it.is_implicit(sema.db) + { + return false; } if !start_with_lifetime { return !matches!(p, hir::GenericParam::LifetimeParam(_)); diff --git a/crates/ide/src/inlay_hints/implicit_static.rs b/crates/ide/src/inlay_hints/implicit_static.rs index 7212efd954e8..bddce904dfde 100644 --- a/crates/ide/src/inlay_hints/implicit_static.rs +++ b/crates/ide/src/inlay_hints/implicit_static.rs @@ -22,30 +22,31 @@ pub(super) fn hints( return None; } - if let Either::Right(it) = &statik_or_const { - if ast::AssocItemList::can_cast( + if let Either::Right(it) = &statik_or_const + && ast::AssocItemList::can_cast( it.syntax().parent().map_or(SyntaxKind::EOF, |it| it.kind()), - ) { - return None; - } + ) + { + return None; } - if let Some(ast::Type::RefType(ty)) = statik_or_const.either(|it| it.ty(), |it| it.ty()) { - if ty.lifetime().is_none() { - let t = ty.amp_token()?; - acc.push(InlayHint { - range: t.text_range(), - kind: InlayKind::Lifetime, - label: "'static".into(), - text_edit: Some(config.lazy_text_edit(|| { - TextEdit::insert(t.text_range().start(), "'static ".into()) - })), - position: InlayHintPosition::After, - pad_left: false, - pad_right: true, - resolve_parent: None, - }); - } + if let Some(ast::Type::RefType(ty)) = statik_or_const.either(|it| it.ty(), |it| it.ty()) + && ty.lifetime().is_none() + { + let t = ty.amp_token()?; + acc.push(InlayHint { + range: t.text_range(), + kind: InlayKind::Lifetime, + label: "'static".into(), + text_edit: Some( + config + .lazy_text_edit(|| TextEdit::insert(t.text_range().start(), "'static ".into())), + ), + position: InlayHintPosition::After, + pad_left: false, + pad_right: true, + resolve_parent: None, + }); } Some(()) diff --git a/crates/ide/src/inlay_hints/lifetime.rs b/crates/ide/src/inlay_hints/lifetime.rs index 49fec0a793c3..a89c53e00b3b 100644 --- a/crates/ide/src/inlay_hints/lifetime.rs +++ b/crates/ide/src/inlay_hints/lifetime.rs @@ -324,35 +324,35 @@ fn hints_( // apply hints // apply output if required - if let (Some(output_lt), Some(r)) = (&output, ret_type) { - if let Some(ty) = r.ty() { - walk_ty(&ty, &mut |ty| match ty { - ast::Type::RefType(ty) if ty.lifetime().is_none() => { - if let Some(amp) = ty.amp_token() { - is_trivial = false; - acc.push(mk_lt_hint(amp, output_lt.to_string())); - } - false + if let (Some(output_lt), Some(r)) = (&output, ret_type) + && let Some(ty) = r.ty() + { + walk_ty(&ty, &mut |ty| match ty { + ast::Type::RefType(ty) if ty.lifetime().is_none() => { + if let Some(amp) = ty.amp_token() { + is_trivial = false; + acc.push(mk_lt_hint(amp, output_lt.to_string())); } - ast::Type::FnPtrType(_) => { + false + } + ast::Type::FnPtrType(_) => { + is_trivial = false; + true + } + ast::Type::PathType(t) => { + if t.path() + .and_then(|it| it.segment()) + .and_then(|it| it.parenthesized_arg_list()) + .is_some() + { is_trivial = false; true + } else { + false } - ast::Type::PathType(t) => { - if t.path() - .and_then(|it| it.segment()) - .and_then(|it| it.parenthesized_arg_list()) - .is_some() - { - is_trivial = false; - true - } else { - false - } - } - _ => false, - }) - } + } + _ => false, + }) } if config.lifetime_elision_hints == LifetimeElisionHints::SkipTrivial && is_trivial { diff --git a/crates/ide/src/inlay_hints/param_name.rs b/crates/ide/src/inlay_hints/param_name.rs index 5174228466c0..ec0a4c46c7fe 100644 --- a/crates/ide/src/inlay_hints/param_name.rs +++ b/crates/ide/src/inlay_hints/param_name.rs @@ -135,10 +135,10 @@ fn should_hide_param_name_hint( } if unary_function { - if let Some(function_name) = function_name { - if is_param_name_suffix_of_fn_name(param_name, function_name) { - return true; - } + if let Some(function_name) = function_name + && is_param_name_suffix_of_fn_name(param_name, function_name) + { + return true; } if is_obvious_param(param_name) { return true; diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs index 0188c105faa7..a946559c3545 100644 --- a/crates/ide/src/join_lines.rs +++ b/crates/ide/src/join_lines.rs @@ -144,15 +144,15 @@ fn remove_newline( } } - if config.join_else_if { - if let (Some(prev), Some(_next)) = (as_if_expr(&prev), as_if_expr(&next)) { - match prev.else_token() { - Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), - None => { - cov_mark::hit!(join_two_ifs); - edit.replace(token.text_range(), " else ".to_owned()); - return; - } + if config.join_else_if + && let (Some(prev), Some(_next)) = (as_if_expr(&prev), as_if_expr(&next)) + { + match prev.else_token() { + Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), + None => { + cov_mark::hit!(join_two_ifs); + edit.replace(token.text_range(), " else ".to_owned()); + return; } } } @@ -213,10 +213,10 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op let mut buf = expr.syntax().text().to_string(); // Match block needs to have a comma after the block - if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) { - if match_arm.comma_token().is_none() { - buf.push(','); - } + if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) + && match_arm.comma_token().is_none() + { + buf.push(','); } edit.replace(block_range, buf); diff --git a/crates/ide/src/parent_module.rs b/crates/ide/src/parent_module.rs index 50219cee57db..96d829d1260b 100644 --- a/crates/ide/src/parent_module.rs +++ b/crates/ide/src/parent_module.rs @@ -29,14 +29,13 @@ pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec(source_file.syntax(), position.offset); // If cursor is literally on `mod foo`, go to the grandpa. - if let Some(m) = &module { - if !m + if let Some(m) = &module + && !m .item_list() .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); - } + { + cov_mark::hit!(test_resolve_parent_module_on_module_decl); + module = m.syntax().ancestors().skip(1).find_map(ast::Module::cast); } match module { diff --git a/crates/ide/src/rename.rs b/crates/ide/src/rename.rs index 6c1d142c3b05..634edaa5edaf 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -494,10 +494,10 @@ mod tests { ) { let ra_fixture_after = &trim_indent(ra_fixture_after); let (analysis, position) = fixture::position(ra_fixture_before); - if !ra_fixture_after.starts_with("error: ") { - if let Err(err) = analysis.prepare_rename(position).unwrap() { - panic!("Prepare rename to '{new_name}' was failed: {err}") - } + if !ra_fixture_after.starts_with("error: ") + && let Err(err) = analysis.prepare_rename(position).unwrap() + { + panic!("Prepare rename to '{new_name}' was failed: {err}") } let rename_result = analysis .rename(position, new_name) diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 9d1a5bae96fb..83e5c5ab1dfe 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -514,20 +514,19 @@ fn module_def_doctest(db: &RootDatabase, def: Definition) -> Option { .flat_map(|it| it.name(db)) .for_each(|name| format_to!(path, "{}::", name.display(db, edition))); // This probably belongs to canonical_path? - if let Some(assoc_item) = def.as_assoc_item(db) { - if let Some(ty) = assoc_item.implementing_ty(db) { - if let Some(adt) = ty.as_adt() { - let name = adt.name(db); - let mut ty_args = ty.generic_parameters(db, display_target).peekable(); - format_to!(path, "{}", name.display(db, edition)); - if ty_args.peek().is_some() { - format_to!(path, "<{}>", ty_args.format_with(",", |ty, cb| cb(&ty))); - } - format_to!(path, "::{}", def_name.display(db, edition)); - path.retain(|c| c != ' '); - return Some(path); - } + if let Some(assoc_item) = def.as_assoc_item(db) + && let Some(ty) = assoc_item.implementing_ty(db) + && let Some(adt) = ty.as_adt() + { + let name = adt.name(db); + let mut ty_args = ty.generic_parameters(db, display_target).peekable(); + format_to!(path, "{}", name.display(db, edition)); + if ty_args.peek().is_some() { + format_to!(path, "<{}>", ty_args.format_with(",", |ty, cb| cb(&ty))); } + format_to!(path, "::{}", def_name.display(db, edition)); + path.retain(|c| c != ' '); + return Some(path); } format_to!(path, "{}", def_name.display(db, edition)); Some(path) @@ -697,14 +696,13 @@ impl UpdateTest { continue; }; for item in items { - if let hir::ItemInNs::Macros(makro) = item { - if Definition::Macro(makro) + if let hir::ItemInNs::Macros(makro) = item + && Definition::Macro(makro) .usages(sema) .in_scope(&search_scope) .at_least_one() - { - return true; - } + { + return true; } } } diff --git a/crates/ide/src/signature_help.rs b/crates/ide/src/signature_help.rs index e30a3ebefb98..382573b68011 100644 --- a/crates/ide/src/signature_help.rs +++ b/crates/ide/src/signature_help.rs @@ -146,12 +146,11 @@ pub(crate) fn signature_help( // Stop at multi-line expressions, since the signature of the outer call is not very // helpful inside them. - if let Some(expr) = ast::Expr::cast(node.clone()) { - if !matches!(expr, ast::Expr::RecordExpr(..)) - && expr.syntax().text().contains_char('\n') - { - break; - } + if let Some(expr) = ast::Expr::cast(node.clone()) + && !matches!(expr, ast::Expr::RecordExpr(..)) + && expr.syntax().text().contains_char('\n') + { + break; } } @@ -366,10 +365,10 @@ fn signature_help_for_generics( res.signature.push('<'); let mut buf = String::new(); for param in params { - if let hir::GenericParam::TypeParam(ty) = param { - if ty.is_implicit(db) { - continue; - } + if let hir::GenericParam::TypeParam(ty) = param + && ty.is_implicit(db) + { + continue; } buf.clear(); diff --git a/crates/ide/src/static_index.rs b/crates/ide/src/static_index.rs index efee39c13db9..694ac22e1993 100644 --- a/crates/ide/src/static_index.rs +++ b/crates/ide/src/static_index.rs @@ -133,10 +133,10 @@ fn get_definitions( ) -> Option> { for token in sema.descend_into_macros_exact(token) { let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops); - if let Some(defs) = def { - if !defs.is_empty() { - return Some(defs); - } + if let Some(defs) = def + && !defs.is_empty() + { + return Some(defs); } } None diff --git a/crates/ide/src/syntax_highlighting/highlight.rs b/crates/ide/src/syntax_highlighting/highlight.rs index 87db0cd7dc53..8bde8fd97006 100644 --- a/crates/ide/src/syntax_highlighting/highlight.rs +++ b/crates/ide/src/syntax_highlighting/highlight.rs @@ -306,12 +306,12 @@ fn highlight_name_ref( }; let mut h = match name_class { NameRefClass::Definition(def, _) => { - if let Definition::Local(local) = &def { - if let Some(bindings_shadow_count) = bindings_shadow_count { - let name = local.name(sema.db); - let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); - *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) - } + if let Definition::Local(local) = &def + && let Some(bindings_shadow_count) = bindings_shadow_count + { + let name = local.name(sema.db); + let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); + *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) }; let mut h = highlight_def(sema, krate, def, edition, true); @@ -437,21 +437,21 @@ fn highlight_name( edition: Edition, ) -> Highlight { let name_kind = NameClass::classify(sema, &name); - if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind { - if let Some(bindings_shadow_count) = bindings_shadow_count { - let name = local.name(sema.db); - let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); - *shadow_count += 1; - *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) - } + if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind + && let Some(bindings_shadow_count) = bindings_shadow_count + { + let name = local.name(sema.db); + let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); + *shadow_count += 1; + *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) }; match name_kind { Some(NameClass::Definition(def)) => { let mut h = highlight_def(sema, krate, def, edition, false) | HlMod::Definition; - if let Definition::Trait(trait_) = &def { - if trait_.is_unsafe(sema.db) { - h |= HlMod::Unsafe; - } + if let Definition::Trait(trait_) = &def + && trait_.is_unsafe(sema.db) + { + h |= HlMod::Unsafe; } h } @@ -743,10 +743,9 @@ fn highlight_method_call( hir::Access::Owned => { if let Some(receiver_ty) = method_call.receiver().and_then(|it| sema.type_of_expr(&it)) + && !receiver_ty.adjusted().is_copy(sema.db) { - if !receiver_ty.adjusted().is_copy(sema.db) { - h |= HlMod::Consuming - } + h |= HlMod::Consuming } } } diff --git a/crates/load-cargo/src/lib.rs b/crates/load-cargo/src/lib.rs index 98f415a522cb..ad838a6550ec 100644 --- a/crates/load-cargo/src/lib.rs +++ b/crates/load-cargo/src/lib.rs @@ -475,10 +475,10 @@ fn load_crate_graph_into_db( } let changes = vfs.take_changes(); for (_, file) in changes { - if let vfs::Change::Create(v, _) | vfs::Change::Modify(v, _) = file.change { - if let Ok(text) = String::from_utf8(v) { - analysis_change.change_file(file.file_id, Some(text)) - } + if let vfs::Change::Create(v, _) | vfs::Change::Modify(v, _) = file.change + && let Ok(text) = String::from_utf8(v) + { + analysis_change.change_file(file.file_id, Some(text)) } } let source_roots = source_root_config.partition(vfs); diff --git a/crates/mbe/src/benchmark.rs b/crates/mbe/src/benchmark.rs index 04ac85ad43dd..b185556b5c7b 100644 --- a/crates/mbe/src/benchmark.rs +++ b/crates/mbe/src/benchmark.rs @@ -185,24 +185,22 @@ fn invocation_fixtures( for it in tokens.iter() { collect_from_op(it, builder, seed); } - if i + 1 != cnt { - if let Some(sep) = separator { - match &**sep { - Separator::Literal(it) => { - builder.push(tt::Leaf::Literal(it.clone())) + if i + 1 != cnt + && let Some(sep) = separator + { + match &**sep { + Separator::Literal(it) => builder.push(tt::Leaf::Literal(it.clone())), + Separator::Ident(it) => builder.push(tt::Leaf::Ident(it.clone())), + Separator::Puncts(puncts) => { + for it in puncts { + builder.push(tt::Leaf::Punct(*it)) } - Separator::Ident(it) => builder.push(tt::Leaf::Ident(it.clone())), - Separator::Puncts(puncts) => { - for it in puncts { - builder.push(tt::Leaf::Punct(*it)) - } - } - Separator::Lifetime(punct, ident) => { - builder.push(tt::Leaf::Punct(*punct)); - builder.push(tt::Leaf::Ident(ident.clone())); - } - }; - } + } + Separator::Lifetime(punct, ident) => { + builder.push(tt::Leaf::Punct(*punct)); + builder.push(tt::Leaf::Ident(ident.clone())); + } + }; } } } diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index a8d5965d480c..189efcd15c2f 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -475,12 +475,12 @@ fn match_loop_inner<'t>( }) } OpDelimited::Op(Op::Subtree { tokens, delimiter }) => { - if let Ok((subtree, _)) = src.clone().expect_subtree() { - if subtree.delimiter.kind == delimiter.kind { - item.stack.push(item.dot); - item.dot = tokens.iter_delimited_with(*delimiter); - cur_items.push(item); - } + if let Ok((subtree, _)) = src.clone().expect_subtree() + && subtree.delimiter.kind == delimiter.kind + { + item.stack.push(item.dot); + item.dot = tokens.iter_delimited_with(*delimiter); + cur_items.push(item); } } OpDelimited::Op(Op::Var { kind, name, .. }) => { diff --git a/crates/parser/src/grammar/expressions.rs b/crates/parser/src/grammar/expressions.rs index 2b4151e3b752..41fd72d8d5a2 100644 --- a/crates/parser/src/grammar/expressions.rs +++ b/crates/parser/src/grammar/expressions.rs @@ -77,38 +77,38 @@ pub(super) fn stmt(p: &mut Parser<'_>, semicolon: Semicolon) { return; } - if let Some((cm, blocklike)) = expr_stmt(p, Some(m)) { - if !(p.at(T!['}']) || (semicolon != Semicolon::Required && p.at(EOF))) { - // test no_semi_after_block - // fn foo() { - // if true {} - // loop {} - // match () {} - // while true {} - // for _ in () {} - // {} - // {} - // macro_rules! test { - // () => {} - // } - // test!{} - // } - let m = cm.precede(p); - match semicolon { - Semicolon::Required => { - if blocklike.is_block() { - p.eat(T![;]); - } else { - p.expect(T![;]); - } - } - Semicolon::Optional => { + if let Some((cm, blocklike)) = expr_stmt(p, Some(m)) + && !(p.at(T!['}']) || (semicolon != Semicolon::Required && p.at(EOF))) + { + // test no_semi_after_block + // fn foo() { + // if true {} + // loop {} + // match () {} + // while true {} + // for _ in () {} + // {} + // {} + // macro_rules! test { + // () => {} + // } + // test!{} + // } + let m = cm.precede(p); + match semicolon { + Semicolon::Required => { + if blocklike.is_block() { p.eat(T![;]); + } else { + p.expect(T![;]); } - Semicolon::Forbidden => (), } - m.complete(p, EXPR_STMT); + Semicolon::Optional => { + p.eat(T![;]); + } + Semicolon::Forbidden => (), } + m.complete(p, EXPR_STMT); } } @@ -134,14 +134,11 @@ pub(super) fn let_stmt(p: &mut Parser<'_>, with_semi: Semicolon) { if p.at(T![else]) { // test_err let_else_right_curly_brace // fn func() { let Some(_) = {Some(1)} else { panic!("h") };} - if let Some(expr) = expr_after_eq { - if let Some(token) = expr.last_token(p) { - if token == T!['}'] { - p.error( - "right curly brace `}` before `else` in a `let...else` statement not allowed" - ) - } - } + if let Some(expr) = expr_after_eq + && let Some(token) = expr.last_token(p) + && token == T!['}'] + { + p.error("right curly brace `}` before `else` in a `let...else` statement not allowed") } // test let_else diff --git a/crates/parser/src/input.rs b/crates/parser/src/input.rs index 4490956f9704..331bc58dd052 100644 --- a/crates/parser/src/input.rs +++ b/crates/parser/src/input.rs @@ -61,7 +61,7 @@ impl Input { #[inline] fn push_impl(&mut self, kind: SyntaxKind, contextual_kind: SyntaxKind) { let idx = self.len(); - if idx % (bits::BITS as usize) == 0 { + if idx.is_multiple_of(bits::BITS as usize) { self.joint.push(0); } self.kind.push(kind); diff --git a/crates/parser/src/shortcuts.rs b/crates/parser/src/shortcuts.rs index e2baec890c3a..d5e513933f7a 100644 --- a/crates/parser/src/shortcuts.rs +++ b/crates/parser/src/shortcuts.rs @@ -252,10 +252,10 @@ fn n_attached_trivias<'a>( WHITESPACE if text.contains("\n\n") => { // we check whether the next token is a doc-comment // and skip the whitespace in this case - if let Some((COMMENT, peek_text)) = trivias.peek().map(|(_, pair)| pair) { - if is_outer(peek_text) { - continue; - } + if let Some((COMMENT, peek_text)) = trivias.peek().map(|(_, pair)| pair) + && is_outer(peek_text) + { + continue; } break; } diff --git a/crates/query-group-macro/src/lib.rs b/crates/query-group-macro/src/lib.rs index ec4b6b2a4ac3..277cc0b269d7 100644 --- a/crates/query-group-macro/src/lib.rs +++ b/crates/query-group-macro/src/lib.rs @@ -278,15 +278,15 @@ pub(crate) fn query_group_impl( return Err(syn::Error::new(signature.span(), "Queries must have a return type")); }; - if let syn::Type::Path(ref ty_path) = *return_ty { - if matches!(query_kind, QueryKind::Input) { - let field = InputStructField { - name: method_name.to_token_stream(), - ty: ty_path.path.to_token_stream(), - }; - - input_struct_fields.push(field); - } + if let syn::Type::Path(ref ty_path) = *return_ty + && matches!(query_kind, QueryKind::Input) + { + let field = InputStructField { + name: method_name.to_token_stream(), + ty: ty_path.path.to_token_stream(), + }; + + input_struct_fields.push(field); } if let Some(block) = &mut method.default { diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 4dba97c8ec49..ab045e0bf9ff 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs @@ -122,12 +122,12 @@ fn setup_logging(log_file_flag: Option) -> anyhow::Result<()> { // directory which we set to the project workspace. // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/general-environment-variables // https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-syminitialize - if let Ok(path) = env::current_exe() { - if let Some(path) = path.parent() { - // SAFETY: This is safe because this is single-threaded. - unsafe { - env::set_var("_NT_SYMBOL_PATH", path); - } + if let Ok(path) = env::current_exe() + && let Some(path) = path.parent() + { + // SAFETY: This is safe because this is single-threaded. + unsafe { + env::set_var("_NT_SYMBOL_PATH", path); } } } diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 4f75d14834c6..97886844a9f9 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -136,34 +136,30 @@ impl flags::AnalysisStats { for source_root_id in source_roots { let source_root = db.source_root(source_root_id).source_root(db); for file_id in source_root.iter() { - if let Some(p) = source_root.path_for_file(&file_id) { - if let Some((_, Some("rs"))) = p.name_and_extension() { - // measure workspace/project code - if !source_root.is_library || self.with_deps { - let length = db.file_text(file_id).text(db).lines().count(); - let item_stats = db - .file_item_tree( - EditionedFileId::current_edition(db, file_id).into(), - ) - .item_tree_stats() - .into(); - - workspace_loc += length; - workspace_item_trees += 1; - workspace_item_stats += item_stats; - } else { - let length = db.file_text(file_id).text(db).lines().count(); - let item_stats = db - .file_item_tree( - EditionedFileId::current_edition(db, file_id).into(), - ) - .item_tree_stats() - .into(); - - dep_loc += length; - dep_item_trees += 1; - dep_item_stats += item_stats; - } + if let Some(p) = source_root.path_for_file(&file_id) + && let Some((_, Some("rs"))) = p.name_and_extension() + { + // measure workspace/project code + if !source_root.is_library || self.with_deps { + let length = db.file_text(file_id).text(db).lines().count(); + let item_stats = db + .file_item_tree(EditionedFileId::current_edition(db, file_id).into()) + .item_tree_stats() + .into(); + + workspace_loc += length; + workspace_item_trees += 1; + workspace_item_stats += item_stats; + } else { + let length = db.file_text(file_id).text(db).lines().count(); + let item_stats = db + .file_item_tree(EditionedFileId::current_edition(db, file_id).into()) + .item_tree_stats() + .into(); + + dep_loc += length; + dep_item_trees += 1; + dep_item_stats += item_stats; } } } @@ -560,29 +556,35 @@ impl flags::AnalysisStats { std::fs::write(path, txt).unwrap(); let res = ws.run_build_scripts(&cargo_config, &|_| ()).unwrap(); - if let Some(err) = res.error() { - if err.contains("error: could not compile") { - if let Some(mut err_idx) = err.find("error[E") { - err_idx += 7; - let err_code = &err[err_idx..err_idx + 4]; - match err_code { - "0282" | "0283" => continue, // Byproduct of testing method - "0277" | "0308" if generated.contains(&todo) => continue, // See https://github.com/rust-lang/rust/issues/69882 - // FIXME: In some rare cases `AssocItem::container_or_implemented_trait` returns `None` for trait methods. - // Generated code is valid in case traits are imported - "0599" if err.contains("the following trait is implemented but not in scope") => continue, - _ => (), + if let Some(err) = res.error() + && err.contains("error: could not compile") + { + if let Some(mut err_idx) = err.find("error[E") { + err_idx += 7; + let err_code = &err[err_idx..err_idx + 4]; + match err_code { + "0282" | "0283" => continue, // Byproduct of testing method + "0277" | "0308" if generated.contains(&todo) => continue, // See https://github.com/rust-lang/rust/issues/69882 + // FIXME: In some rare cases `AssocItem::container_or_implemented_trait` returns `None` for trait methods. + // Generated code is valid in case traits are imported + "0599" + if err.contains( + "the following trait is implemented but not in scope", + ) => + { + continue; } - bar.println(err); - bar.println(generated); - acc.error_codes - .entry(err_code.to_owned()) - .and_modify(|n| *n += 1) - .or_insert(1); - } else { - acc.syntax_errors += 1; - bar.println(format!("Syntax error: \n{err}")); + _ => (), } + bar.println(err); + bar.println(generated); + acc.error_codes + .entry(err_code.to_owned()) + .and_modify(|n| *n += 1) + .or_insert(1); + } else { + acc.syntax_errors += 1; + bar.println(format!("Syntax error: \n{err}")); } } } @@ -731,12 +733,11 @@ impl flags::AnalysisStats { let name = body_id.name(db).unwrap_or_else(Name::missing); let module = body_id.module(db); let display_target = module.krate().to_display_target(db); - if let Some(only_name) = self.only.as_deref() { - if name.display(db, Edition::LATEST).to_string() != only_name - && full_name(db, body_id, module) != only_name - { - continue; - } + if let Some(only_name) = self.only.as_deref() + && name.display(db, Edition::LATEST).to_string() != only_name + && full_name(db, body_id, module) != only_name + { + continue; } let msg = move || { if verbosity.is_verbose() { diff --git a/crates/rust-analyzer/src/cli/progress_report.rs b/crates/rust-analyzer/src/cli/progress_report.rs index 1b9b870a7c74..028311388c56 100644 --- a/crates/rust-analyzer/src/cli/progress_report.rs +++ b/crates/rust-analyzer/src/cli/progress_report.rs @@ -83,11 +83,11 @@ impl<'a> ProgressReport<'a> { output.extend(text.chars().skip(common_prefix_length)); // If the new text is shorter than the old one: delete overlapping characters - if let Some(overlap_count) = self.text.len().checked_sub(text.len()) { - if overlap_count > 0 { - output += &" ".repeat(overlap_count); - output += &"\x08".repeat(overlap_count); - } + if let Some(overlap_count) = self.text.len().checked_sub(text.len()) + && overlap_count > 0 + { + output += &" ".repeat(overlap_count); + output += &"\x08".repeat(overlap_count); } let _ = io::stdout().write(output.as_bytes()); diff --git a/crates/rust-analyzer/src/cli/rustc_tests.rs b/crates/rust-analyzer/src/cli/rustc_tests.rs index 30ac93fb6f83..36ae98b321b8 100644 --- a/crates/rust-analyzer/src/cli/rustc_tests.rs +++ b/crates/rust-analyzer/src/cli/rustc_tests.rs @@ -305,10 +305,10 @@ impl flags::RustcTests { for i in walk_dir { let i = i?; let p = i.into_path(); - if let Some(f) = &self.filter { - if !p.as_os_str().to_string_lossy().contains(f) { - continue; - } + if let Some(f) = &self.filter + && !p.as_os_str().to_string_lossy().contains(f) + { + continue; } if p.extension().is_none_or(|x| x != "rs") { continue; diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index a8bcce196c4e..70d04485ca08 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -3904,17 +3904,16 @@ mod tests { for idx in url_offsets { let link = &schema[idx..]; // matching on whitespace to ignore normal links - if let Some(link_end) = link.find([' ', '[']) { - if link.chars().nth(link_end) == Some('[') { - if let Some(link_text_end) = link.find(']') { - let link_text = link[link_end..(link_text_end + 1)].to_string(); - - schema.replace_range((idx + link_end)..(idx + link_text_end + 1), ""); - schema.insert(idx, '('); - schema.insert(idx + link_end + 1, ')'); - schema.insert_str(idx, &link_text); - } - } + if let Some(link_end) = link.find([' ', '[']) + && link.chars().nth(link_end) == Some('[') + && let Some(link_text_end) = link.find(']') + { + let link_text = link[link_end..(link_text_end + 1)].to_string(); + + schema.replace_range((idx + link_end)..(idx + link_text_end + 1), ""); + schema.insert(idx, '('); + schema.insert(idx + link_end + 1, ')'); + schema.insert_str(idx, &link_text); } } diff --git a/crates/rust-analyzer/src/config/patch_old_style.rs b/crates/rust-analyzer/src/config/patch_old_style.rs index 95857dd8f3b4..389bb7848c01 100644 --- a/crates/rust-analyzer/src/config/patch_old_style.rs +++ b/crates/rust-analyzer/src/config/patch_old_style.rs @@ -73,19 +73,19 @@ pub(super) fn patch_json_for_outdated_configs(json: &mut Value) { } // completion.snippets -> completion.snippets.custom; - if let Some(Value::Object(obj)) = copy.pointer("/completion/snippets").cloned() { - if obj.len() != 1 || obj.get("custom").is_none() { - merge( - json, - json! {{ - "completion": { - "snippets": { - "custom": obj - }, + if let Some(Value::Object(obj)) = copy.pointer("/completion/snippets").cloned() + && (obj.len() != 1 || obj.get("custom").is_none()) + { + merge( + json, + json! {{ + "completion": { + "snippets": { + "custom": obj }, - }}, - ); - } + }, + }}, + ); } // callInfo_full -> signatureInfo_detail, signatureInfo_documentation_enable diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs index 79d8f678de4d..3f64628de860 100644 --- a/crates/rust-analyzer/src/diagnostics/to_proto.rs +++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs @@ -298,10 +298,10 @@ pub(crate) fn map_rust_diagnostic_to_lsp( let mut source = String::from("rustc"); let mut code = rd.code.as_ref().map(|c| c.code.clone()); - if let Some(code_val) = &code { - if config.check_ignore.contains(code_val) { - return Vec::new(); - } + if let Some(code_val) = &code + && config.check_ignore.contains(code_val) + { + return Vec::new(); } if let Some(code_val) = &code { @@ -373,10 +373,8 @@ pub(crate) fn map_rust_diagnostic_to_lsp( let primary_location = primary_location(config, workspace_root, primary_span, snap); let message = { let mut message = message.clone(); - if needs_primary_span_label { - if let Some(primary_span_label) = &primary_span.label { - format_to!(message, "\n{}", primary_span_label); - } + if needs_primary_span_label && let Some(primary_span_label) = &primary_span.label { + format_to!(message, "\n{}", primary_span_label); } message }; diff --git a/crates/rust-analyzer/src/flycheck.rs b/crates/rust-analyzer/src/flycheck.rs index 512ce0b9de35..e4e0bcdc1cd0 100644 --- a/crates/rust-analyzer/src/flycheck.rs +++ b/crates/rust-analyzer/src/flycheck.rs @@ -492,12 +492,11 @@ impl FlycheckActor { FlycheckConfig::CargoCommand { command, options, ansi_color_output } => { let mut cmd = toolchain::command(Tool::Cargo.path(), &*self.root, &options.extra_env); - if let Some(sysroot_root) = &self.sysroot_root { - if !options.extra_env.contains_key("RUSTUP_TOOLCHAIN") - && std::env::var_os("RUSTUP_TOOLCHAIN").is_none() - { - cmd.env("RUSTUP_TOOLCHAIN", AsRef::::as_ref(sysroot_root)); - } + if let Some(sysroot_root) = &self.sysroot_root + && !options.extra_env.contains_key("RUSTUP_TOOLCHAIN") + && std::env::var_os("RUSTUP_TOOLCHAIN").is_none() + { + cmd.env("RUSTUP_TOOLCHAIN", AsRef::::as_ref(sysroot_root)); } cmd.arg(command); diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs index 62a28a1a685d..3171bdd36178 100644 --- a/crates/rust-analyzer/src/global_state.rs +++ b/crates/rust-analyzer/src/global_state.rs @@ -591,10 +591,10 @@ impl GlobalState { pub(crate) fn respond(&mut self, response: lsp_server::Response) { if let Some((method, start)) = self.req_queue.incoming.complete(&response.id) { - if let Some(err) = &response.error { - if err.message.starts_with("server panicked") { - self.poke_rust_analyzer_developer(format!("{}, check the log", err.message)); - } + if let Some(err) = &response.error + && err.message.starts_with("server panicked") + { + self.poke_rust_analyzer_developer(format!("{}, check the log", err.message)); } let duration = start.elapsed(); @@ -663,18 +663,18 @@ impl GlobalState { pub(crate) fn check_workspaces_msrv(&self) -> impl Iterator + '_ { self.workspaces.iter().filter_map(|ws| { - if let Some(toolchain) = &ws.toolchain { - if *toolchain < crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION { - return Some(format!( - "Workspace `{}` is using an outdated toolchain version `{}` but \ + if let Some(toolchain) = &ws.toolchain + && *toolchain < crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION + { + return Some(format!( + "Workspace `{}` is using an outdated toolchain version `{}` but \ rust-analyzer only supports `{}` and higher.\n\ Consider using the rust-analyzer rustup component for your toolchain or upgrade your toolchain to a supported version.\n\n", - ws.manifest_or_root(), - toolchain, - crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION, - )); - } + ws.manifest_or_root(), + toolchain, + crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION, + )); } None }) diff --git a/crates/rust-analyzer/src/handlers/dispatch.rs b/crates/rust-analyzer/src/handlers/dispatch.rs index aea116e647db..b25245dd884a 100644 --- a/crates/rust-analyzer/src/handlers/dispatch.rs +++ b/crates/rust-analyzer/src/handlers/dispatch.rs @@ -433,10 +433,10 @@ impl NotificationDispatcher<'_> { } pub(crate) fn finish(&mut self) { - if let Some(not) = &self.not { - if !not.method.starts_with("$/") { - tracing::error!("unhandled notification: {:?}", not); - } + if let Some(not) = &self.not + && !not.method.starts_with("$/") + { + tracing::error!("unhandled notification: {:?}", not); } } } diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs index 200e972e4289..e193ff77743d 100644 --- a/crates/rust-analyzer/src/handlers/notification.rs +++ b/crates/rust-analyzer/src/handlers/notification.rs @@ -39,14 +39,12 @@ pub(crate) fn handle_work_done_progress_cancel( state: &mut GlobalState, params: WorkDoneProgressCancelParams, ) -> 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) = id.parse::() { - if let Some(flycheck) = state.flycheck.get(id as usize) { - flycheck.cancel(); - } - } - } + if let lsp_types::NumberOrString::String(s) = ¶ms.token + && let Some(id) = s.strip_prefix("rust-analyzer/flycheck/") + && let Ok(id) = id.parse::() + && let Some(flycheck) = state.flycheck.get(id as usize) + { + flycheck.cancel(); } // Just ignore this. It is OK to continue sending progress @@ -76,12 +74,12 @@ pub(crate) fn handle_did_open_text_document( tracing::error!("duplicate DidOpenTextDocument: {}", path); } - if let Some(abs_path) = path.as_path() { - if state.config.excluded().any(|excluded| abs_path.starts_with(&excluded)) { - tracing::trace!("opened excluded file {abs_path}"); - state.vfs.write().0.insert_excluded_file(path); - return Ok(()); - } + if let Some(abs_path) = path.as_path() + && state.config.excluded().any(|excluded| abs_path.starts_with(&excluded)) + { + tracing::trace!("opened excluded file {abs_path}"); + state.vfs.write().0.insert_excluded_file(path); + return Ok(()); } let contents = params.text_document.text.into_bytes(); @@ -449,12 +447,11 @@ pub(crate) fn handle_run_flycheck( params: RunFlycheckParams, ) -> anyhow::Result<()> { let _p = tracing::info_span!("handle_run_flycheck").entered(); - if let Some(text_document) = params.text_document { - if let Ok(vfs_path) = from_proto::vfs_path(&text_document.uri) { - if run_flycheck(state, vfs_path) { - return Ok(()); - } - } + if let Some(text_document) = params.text_document + && let Ok(vfs_path) = from_proto::vfs_path(&text_document.uri) + && run_flycheck(state, vfs_path) + { + return Ok(()); } // No specific flycheck was triggered, so let's trigger all of them. if state.config.flycheck_workspace(None) { diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs index a76a65220d3b..25c0aac405e7 100644 --- a/crates/rust-analyzer/src/handlers/request.rs +++ b/crates/rust-analyzer/src/handlers/request.rs @@ -973,14 +973,13 @@ pub(crate) fn handle_runnables( res.push(runnable); } - if let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args { - if let Some(TargetSpec::Cargo(CargoTargetSpec { + if let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args + && let Some(TargetSpec::Cargo(CargoTargetSpec { sysroot_root: Some(sysroot_root), .. })) = &target_spec - { - r.environment.insert("RUSTC_TOOLCHAIN".to_owned(), sysroot_root.to_string()); - } + { + r.environment.insert("RUSTC_TOOLCHAIN".to_owned(), sysroot_root.to_string()); }; res.push(runnable); @@ -1034,25 +1033,25 @@ pub(crate) fn handle_runnables( } Some(TargetSpec::ProjectJson(_)) => {} None => { - if !snap.config.linked_or_discovered_projects().is_empty() { - if let Some(path) = snap.file_id_to_file_path(file_id).parent() { - let mut cargo_args = vec!["check".to_owned(), "--workspace".to_owned()]; - cargo_args.extend(config.cargo_extra_args.iter().cloned()); - res.push(lsp_ext::Runnable { - label: "cargo check --workspace".to_owned(), - location: None, - kind: lsp_ext::RunnableKind::Cargo, - args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs { - workspace_root: None, - cwd: path.as_path().unwrap().to_path_buf().into(), - override_cargo: config.override_cargo, - cargo_args, - executable_args: Vec::new(), - environment: Default::default(), - }), - }); - }; - } + if !snap.config.linked_or_discovered_projects().is_empty() + && let Some(path) = snap.file_id_to_file_path(file_id).parent() + { + let mut cargo_args = vec!["check".to_owned(), "--workspace".to_owned()]; + cargo_args.extend(config.cargo_extra_args.iter().cloned()); + res.push(lsp_ext::Runnable { + label: "cargo check --workspace".to_owned(), + location: None, + kind: lsp_ext::RunnableKind::Cargo, + args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs { + workspace_root: None, + cwd: path.as_path().unwrap().to_path_buf().into(), + override_cargo: config.override_cargo, + cargo_args, + executable_args: Vec::new(), + environment: Default::default(), + }), + }); + }; } } Ok(res) @@ -1557,12 +1556,12 @@ pub(crate) fn handle_code_action_resolve( code_action.edit = ca.edit; code_action.command = ca.command; - if let Some(edit) = code_action.edit.as_ref() { - if let Some(changes) = edit.document_changes.as_ref() { - for change in changes { - if let lsp_ext::SnippetDocumentChangeOperation::Op(res_op) = change { - resource_ops_supported(&snap.config, resolve_resource_op(res_op))? - } + if let Some(edit) = code_action.edit.as_ref() + && let Some(changes) = edit.document_changes.as_ref() + { + for change in changes { + if let lsp_ext::SnippetDocumentChangeOperation::Op(res_op) = change { + resource_ops_supported(&snap.config, resolve_resource_op(res_op))? } } } @@ -1958,12 +1957,11 @@ pub(crate) fn handle_semantic_tokens_full_delta( if let Some(cached_tokens @ lsp_types::SemanticTokens { result_id: Some(prev_id), .. }) = &cached_tokens + && *prev_id == params.previous_result_id { - if *prev_id == params.previous_result_id { - let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens); - snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens); - return Ok(Some(delta.into())); - } + let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens); + snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens); + return Ok(Some(delta.into())); } // Clone first to keep the lock short @@ -2122,24 +2120,25 @@ fn show_impl_command_link( snap: &GlobalStateSnapshot, position: &FilePosition, ) -> Option { - if snap.config.hover_actions().implementations && snap.config.client_commands().show_reference { - if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) { - let uri = to_proto::url(snap, position.file_id); - let line_index = snap.file_line_index(position.file_id).ok()?; - let position = to_proto::position(&line_index, position.offset); - let locations: Vec<_> = nav_data - .info - .into_iter() - .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok()) - .collect(); - let title = to_proto::implementation_title(locations.len()); - let command = to_proto::command::show_references(title, &uri, position, locations); - - return Some(lsp_ext::CommandLinkGroup { - commands: vec![to_command_link(command, "Go to implementations".into())], - ..Default::default() - }); - } + if snap.config.hover_actions().implementations + && snap.config.client_commands().show_reference + && let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) + { + let uri = to_proto::url(snap, position.file_id); + let line_index = snap.file_line_index(position.file_id).ok()?; + let position = to_proto::position(&line_index, position.offset); + let locations: Vec<_> = nav_data + .info + .into_iter() + .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok()) + .collect(); + let title = to_proto::implementation_title(locations.len()); + let command = to_proto::command::show_references(title, &uri, position, locations); + + return Some(lsp_ext::CommandLinkGroup { + commands: vec![to_command_link(command, "Go to implementations".into())], + ..Default::default() + }); } None } @@ -2148,28 +2147,29 @@ fn show_ref_command_link( snap: &GlobalStateSnapshot, position: &FilePosition, ) -> Option { - if snap.config.hover_actions().references && snap.config.client_commands().show_reference { - if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) { - let uri = to_proto::url(snap, position.file_id); - let line_index = snap.file_line_index(position.file_id).ok()?; - let position = to_proto::position(&line_index, position.offset); - let locations: Vec<_> = ref_search_res - .into_iter() - .flat_map(|res| res.references) - .flat_map(|(file_id, ranges)| { - ranges.into_iter().map(move |(range, _)| FileRange { file_id, range }) - }) - .unique() - .filter_map(|range| to_proto::location(snap, range).ok()) - .collect(); - let title = to_proto::reference_title(locations.len()); - let command = to_proto::command::show_references(title, &uri, position, locations); - - return Some(lsp_ext::CommandLinkGroup { - commands: vec![to_command_link(command, "Go to references".into())], - ..Default::default() - }); - } + if snap.config.hover_actions().references + && snap.config.client_commands().show_reference + && let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) + { + let uri = to_proto::url(snap, position.file_id); + let line_index = snap.file_line_index(position.file_id).ok()?; + let position = to_proto::position(&line_index, position.offset); + let locations: Vec<_> = ref_search_res + .into_iter() + .flat_map(|res| res.references) + .flat_map(|(file_id, ranges)| { + ranges.into_iter().map(move |(range, _)| FileRange { file_id, range }) + }) + .unique() + .filter_map(|range| to_proto::location(snap, range).ok()) + .collect(); + let title = to_proto::reference_title(locations.len()); + let command = to_proto::command::show_references(title, &uri, position, locations); + + return Some(lsp_ext::CommandLinkGroup { + commands: vec![to_command_link(command, "Go to references".into())], + ..Default::default() + }); } None } diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index 00cf890510d4..61c758d5e86e 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -501,14 +501,12 @@ impl GlobalState { } } - if self.config.cargo_autoreload_config(None) - || self.config.discover_workspace_config().is_some() - { - if let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) = + if (self.config.cargo_autoreload_config(None) + || self.config.discover_workspace_config().is_some()) + && let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) = self.fetch_workspaces_queue.should_start_op() - { - self.fetch_workspaces(cause, path, force_crate_graph_reload); - } + { + self.fetch_workspaces(cause, path, force_crate_graph_reload); } if !self.fetch_workspaces_queue.op_in_progress() { @@ -765,33 +763,33 @@ impl GlobalState { self.report_progress("Fetching", state, msg, None, None); } Task::DiscoverLinkedProjects(arg) => { - if let Some(cfg) = self.config.discover_workspace_config() { - if !self.discover_workspace_queue.op_in_progress() { - // the clone is unfortunately necessary to avoid a borrowck error when - // `self.report_progress` is called later - let title = &cfg.progress_label.clone(); - let command = cfg.command.clone(); - let discover = DiscoverCommand::new(self.discover_sender.clone(), command); - - self.report_progress(title, Progress::Begin, None, None, None); - self.discover_workspace_queue - .request_op("Discovering workspace".to_owned(), ()); - let _ = self.discover_workspace_queue.should_start_op(); - - let arg = match arg { - DiscoverProjectParam::Buildfile(it) => DiscoverArgument::Buildfile(it), - DiscoverProjectParam::Path(it) => DiscoverArgument::Path(it), - }; + if let Some(cfg) = self.config.discover_workspace_config() + && !self.discover_workspace_queue.op_in_progress() + { + // the clone is unfortunately necessary to avoid a borrowck error when + // `self.report_progress` is called later + let title = &cfg.progress_label.clone(); + let command = cfg.command.clone(); + let discover = DiscoverCommand::new(self.discover_sender.clone(), command); + + self.report_progress(title, Progress::Begin, None, None, None); + self.discover_workspace_queue + .request_op("Discovering workspace".to_owned(), ()); + let _ = self.discover_workspace_queue.should_start_op(); + + let arg = match arg { + DiscoverProjectParam::Buildfile(it) => DiscoverArgument::Buildfile(it), + DiscoverProjectParam::Path(it) => DiscoverArgument::Path(it), + }; - let handle = discover.spawn( - arg, - &std::env::current_dir() - .expect("Failed to get cwd during project discovery"), - ); - self.discover_handle = Some(handle.unwrap_or_else(|e| { - panic!("Failed to spawn project discovery command: {e}") - })); - } + let handle = discover.spawn( + arg, + &std::env::current_dir() + .expect("Failed to get cwd during project discovery"), + ); + self.discover_handle = Some(handle.unwrap_or_else(|e| { + panic!("Failed to spawn project discovery command: {e}") + })); } } Task::FetchBuildData(progress) => { diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index e798aa6a8a60..aa38aa72d44e 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -306,13 +306,13 @@ impl GlobalState { _ => None, }); - if let Some(build) = build { - if is_quiescent { - let path = AbsPathBuf::try_from(build.build_file) - .expect("Unable to convert to an AbsPath"); - let arg = DiscoverProjectParam::Buildfile(path); - sender.send(Task::DiscoverLinkedProjects(arg)).unwrap(); - } + if let Some(build) = build + && is_quiescent + { + let path = AbsPathBuf::try_from(build.build_file) + .expect("Unable to convert to an AbsPath"); + let arg = DiscoverProjectParam::Buildfile(path); + sender.send(Task::DiscoverLinkedProjects(arg)).unwrap(); } } diff --git a/crates/span/src/map.rs b/crates/span/src/map.rs index f58201793da2..bb09933536e7 100644 --- a/crates/span/src/map.rs +++ b/crates/span/src/map.rs @@ -41,13 +41,13 @@ where /// Pushes a new span onto the [`SpanMap`]. pub fn push(&mut self, offset: TextSize, span: SpanData) { - if cfg!(debug_assertions) { - if let Some(&(last_offset, _)) = self.spans.last() { - assert!( - last_offset < offset, - "last_offset({last_offset:?}) must be smaller than offset({offset:?})" - ); - } + if cfg!(debug_assertions) + && let Some(&(last_offset, _)) = self.spans.last() + { + assert!( + last_offset < offset, + "last_offset({last_offset:?}) must be smaller than offset({offset:?})" + ); } self.spans.push((offset, span)); } diff --git a/crates/syntax-bridge/src/lib.rs b/crates/syntax-bridge/src/lib.rs index d59229952f52..bdff671802c2 100644 --- a/crates/syntax-bridge/src/lib.rs +++ b/crates/syntax-bridge/src/lib.rs @@ -768,17 +768,17 @@ where } fn bump(&mut self) -> Option<(Self::Token, TextRange)> { - if let Some((punct, offset)) = self.punct_offset.clone() { - if usize::from(offset) + 1 < punct.text().len() { - let offset = offset + TextSize::of('.'); - let range = punct.text_range(); - self.punct_offset = Some((punct.clone(), offset)); - let range = TextRange::at(range.start() + offset, TextSize::of('.')); - return Some(( - SynToken::Punct { token: punct, offset: u32::from(offset) as usize }, - range, - )); - } + if let Some((punct, offset)) = self.punct_offset.clone() + && usize::from(offset) + 1 < punct.text().len() + { + let offset = offset + TextSize::of('.'); + let range = punct.text_range(); + self.punct_offset = Some((punct.clone(), offset)); + let range = TextRange::at(range.start() + offset, TextSize::of('.')); + return Some(( + SynToken::Punct { token: punct, offset: u32::from(offset) as usize }, + range, + )); } if let Some(leaf) = self.current_leaves.pop() { diff --git a/crates/syntax-bridge/src/prettify_macro_expansion.rs b/crates/syntax-bridge/src/prettify_macro_expansion.rs index 0a5c8df0d0ae..2f932e045832 100644 --- a/crates/syntax-bridge/src/prettify_macro_expansion.rs +++ b/crates/syntax-bridge/src/prettify_macro_expansion.rs @@ -61,10 +61,11 @@ pub fn prettify_macro_expansion( } _ => continue, }; - if token.kind() == SyntaxKind::IDENT && token.text() == "$crate" { - if let Some(replacement) = dollar_crate_replacement(&token) { - dollar_crate_replacements.push((token.clone(), replacement)); - } + if token.kind() == SyntaxKind::IDENT + && token.text() == "$crate" + && let Some(replacement) = dollar_crate_replacement(&token) + { + dollar_crate_replacements.push((token.clone(), replacement)); } let tok = &token; diff --git a/crates/syntax-bridge/src/tests.rs b/crates/syntax-bridge/src/tests.rs index 8871bf56a5df..c8dc3131b59c 100644 --- a/crates/syntax-bridge/src/tests.rs +++ b/crates/syntax-bridge/src/tests.rs @@ -34,14 +34,11 @@ fn check_punct_spacing(fixture: &str) { while !cursor.eof() { while let Some(token_tree) = cursor.token_tree() { if let tt::TokenTree::Leaf(Leaf::Punct(Punct { - spacing, - span: Span { range, .. }, - .. + spacing, span: Span { range, .. }, .. })) = token_tree + && let Some(expected) = annotations.remove(range) { - if let Some(expected) = annotations.remove(range) { - assert_eq!(expected, *spacing); - } + assert_eq!(expected, *spacing); } cursor.bump(); } diff --git a/crates/syntax-bridge/src/to_parser_input.rs b/crates/syntax-bridge/src/to_parser_input.rs index 021dc6595f9b..c0ff8e1db2c2 100644 --- a/crates/syntax-bridge/src/to_parser_input.rs +++ b/crates/syntax-bridge/src/to_parser_input.rs @@ -21,17 +21,17 @@ pub fn to_parser_input( let tt = current.token_tree(); // Check if it is lifetime - if let Some(tt::TokenTree::Leaf(tt::Leaf::Punct(punct))) = tt { - if punct.char == '\'' { - current.bump(); - match current.token_tree() { - Some(tt::TokenTree::Leaf(tt::Leaf::Ident(_ident))) => { - res.push(LIFETIME_IDENT); - current.bump(); - continue; - } - _ => panic!("Next token must be ident"), + if let Some(tt::TokenTree::Leaf(tt::Leaf::Punct(punct))) = tt + && punct.char == '\'' + { + current.bump(); + match current.token_tree() { + Some(tt::TokenTree::Leaf(tt::Leaf::Ident(_ident))) => { + res.push(LIFETIME_IDENT); + current.bump(); + continue; } + _ => panic!("Next token must be ident"), } } diff --git a/crates/syntax/src/ast/edit.rs b/crates/syntax/src/ast/edit.rs index d97fdec524fb..9b30642fe4b0 100644 --- a/crates/syntax/src/ast/edit.rs +++ b/crates/syntax/src/ast/edit.rs @@ -89,11 +89,11 @@ impl IndentLevel { _ => None, }); for token in tokens { - if let Some(ws) = ast::Whitespace::cast(token) { - if ws.text().contains('\n') { - let new_ws = make::tokens::whitespace(&format!("{}{self}", ws.syntax())); - ted::replace(ws.syntax(), &new_ws); - } + if let Some(ws) = ast::Whitespace::cast(token) + && ws.text().contains('\n') + { + let new_ws = make::tokens::whitespace(&format!("{}{self}", ws.syntax())); + ted::replace(ws.syntax(), &new_ws); } } } @@ -122,13 +122,13 @@ impl IndentLevel { _ => None, }); for token in tokens { - if let Some(ws) = ast::Whitespace::cast(token) { - if ws.text().contains('\n') { - let new_ws = make::tokens::whitespace( - &ws.syntax().text().replace(&format!("\n{self}"), "\n"), - ); - ted::replace(ws.syntax(), &new_ws); - } + if let Some(ws) = ast::Whitespace::cast(token) + && ws.text().contains('\n') + { + let new_ws = make::tokens::whitespace( + &ws.syntax().text().replace(&format!("\n{self}"), "\n"), + ); + ted::replace(ws.syntax(), &new_ws); } } } diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs index 28b543ea7064..f01ac081c8bd 100644 --- a/crates/syntax/src/ast/edit_in_place.rs +++ b/crates/syntax/src/ast/edit_in_place.rs @@ -383,10 +383,10 @@ impl ast::GenericParamList { impl ast::WhereClause { pub fn add_predicate(&self, predicate: ast::WherePred) { - if let Some(pred) = self.predicates().last() { - if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) { - ted::append_child_raw(self.syntax(), make::token(T![,])); - } + if let Some(pred) = self.predicates().last() + && !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) + { + ted::append_child_raw(self.syntax(), make::token(T![,])); } ted::append_child(self.syntax(), predicate.syntax()); } @@ -744,10 +744,10 @@ impl ast::LetStmt { } if let Some(existing_ty) = self.ty() { - if let Some(sibling) = existing_ty.syntax().prev_sibling_or_token() { - if sibling.kind() == SyntaxKind::WHITESPACE { - ted::remove(sibling); - } + if let Some(sibling) = existing_ty.syntax().prev_sibling_or_token() + && sibling.kind() == SyntaxKind::WHITESPACE + { + ted::remove(sibling); } ted::remove(existing_ty.syntax()); @@ -823,19 +823,18 @@ impl ast::RecordExprField { return; } // this is a shorthand - if let Some(ast::Expr::PathExpr(path_expr)) = self.expr() { - if let Some(path) = path_expr.path() { - if let Some(name_ref) = path.as_single_name_ref() { - path_expr.syntax().detach(); - let children = vec![ - name_ref.syntax().clone().into(), - ast::make::token(T![:]).into(), - ast::make::tokens::single_space().into(), - expr.syntax().clone().into(), - ]; - ted::insert_all_raw(Position::last_child_of(self.syntax()), children); - } - } + if let Some(ast::Expr::PathExpr(path_expr)) = self.expr() + && let Some(path) = path_expr.path() + && let Some(name_ref) = path.as_single_name_ref() + { + path_expr.syntax().detach(); + let children = vec![ + name_ref.syntax().clone().into(), + ast::make::token(T![:]).into(), + ast::make::tokens::single_space().into(), + expr.syntax().clone().into(), + ]; + ted::insert_all_raw(Position::last_child_of(self.syntax()), children); } } } diff --git a/crates/syntax/src/ast/prec.rs b/crates/syntax/src/ast/prec.rs index 00750bff0ba2..1364adb187fc 100644 --- a/crates/syntax/src/ast/prec.rs +++ b/crates/syntax/src/ast/prec.rs @@ -276,19 +276,19 @@ impl Expr { } // Not every expression can be followed by `else` in the `let-else` - if let Some(ast::Stmt::LetStmt(e)) = stmt { - if e.let_else().is_some() { - match self { - BinExpr(e) - if e.op_kind() - .map(|op| matches!(op, BinaryOp::LogicOp(_))) - .unwrap_or(false) => - { - return true; - } - _ if self.clone().trailing_brace().is_some() => return true, - _ => {} + if let Some(ast::Stmt::LetStmt(e)) = stmt + && e.let_else().is_some() + { + match self { + BinExpr(e) + if e.op_kind() + .map(|op| matches!(op, BinaryOp::LogicOp(_))) + .unwrap_or(false) => + { + return true; } + _ if self.clone().trailing_brace().is_some() => return true, + _ => {} } } diff --git a/crates/syntax/src/syntax_editor.rs b/crates/syntax/src/syntax_editor.rs index 5107754b1825..124ac5c072c9 100644 --- a/crates/syntax/src/syntax_editor.rs +++ b/crates/syntax/src/syntax_editor.rs @@ -626,10 +626,10 @@ mod tests { if let Some(ret_ty) = parent_fn.ret_type() { editor.delete(ret_ty.syntax().clone()); - if let Some(SyntaxElement::Token(token)) = ret_ty.syntax().next_sibling_or_token() { - if token.kind().is_trivia() { - editor.delete(token); - } + if let Some(SyntaxElement::Token(token)) = ret_ty.syntax().next_sibling_or_token() + && token.kind().is_trivia() + { + editor.delete(token); } } diff --git a/crates/syntax/src/ted.rs b/crates/syntax/src/ted.rs index 6fcbdd006c24..5c286479c4e3 100644 --- a/crates/syntax/src/ted.rs +++ b/crates/syntax/src/ted.rs @@ -90,15 +90,15 @@ pub fn insert_raw(position: Position, elem: impl Element) { insert_all_raw(position, vec![elem.syntax_element()]); } pub fn insert_all(position: Position, mut elements: Vec) { - if let Some(first) = elements.first() { - if let Some(ws) = ws_before(&position, first) { - elements.insert(0, ws.into()); - } + if let Some(first) = elements.first() + && let Some(ws) = ws_before(&position, first) + { + elements.insert(0, ws.into()); } - if let Some(last) = elements.last() { - if let Some(ws) = ws_after(&position, last) { - elements.push(ws.into()); - } + if let Some(last) = elements.last() + && let Some(ws) = ws_after(&position, last) + { + elements.push(ws.into()); } insert_all_raw(position, elements); } @@ -165,20 +165,22 @@ fn ws_before(position: &Position, new: &SyntaxElement) -> Option { PositionRepr::After(it) => it, }; - if prev.kind() == T!['{'] && new.kind() == SyntaxKind::USE { - if let Some(item_list) = prev.parent().and_then(ast::ItemList::cast) { - let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into()); - indent.0 += 1; - return Some(make::tokens::whitespace(&format!("\n{indent}"))); - } + if prev.kind() == T!['{'] + && new.kind() == SyntaxKind::USE + && let Some(item_list) = prev.parent().and_then(ast::ItemList::cast) + { + let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into()); + indent.0 += 1; + return Some(make::tokens::whitespace(&format!("\n{indent}"))); } - if prev.kind() == T!['{'] && ast::Stmt::can_cast(new.kind()) { - if let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast) { - let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into()); - indent.0 += 1; - return Some(make::tokens::whitespace(&format!("\n{indent}"))); - } + if prev.kind() == T!['{'] + && ast::Stmt::can_cast(new.kind()) + && let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast) + { + let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into()); + indent.0 += 1; + return Some(make::tokens::whitespace(&format!("\n{indent}"))); } ws_between(prev, new) diff --git a/crates/syntax/src/validation.rs b/crates/syntax/src/validation.rs index 4180f9cd1855..485140be8f69 100644 --- a/crates/syntax/src/validation.rs +++ b/crates/syntax/src/validation.rs @@ -142,50 +142,50 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec) { match literal.kind() { ast::LiteralKind::String(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 1, '"') { - unescape_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 1, '"') + { + unescape_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::ByteString(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 2, '"') { - unescape_byte_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 2, '"') + { + unescape_byte_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::CString(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 2, '"') { - unescape_c_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 2, '"') + { + unescape_c_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::Char(_) => { - if let Some(without_quotes) = unquote(text, 1, '\'') { - if let Err(err) = unescape_char(without_quotes) { - push_err(1, 0, err); - } + if let Some(without_quotes) = unquote(text, 1, '\'') + && let Err(err) = unescape_char(without_quotes) + { + push_err(1, 0, err); } } ast::LiteralKind::Byte(_) => { - if let Some(without_quotes) = unquote(text, 2, '\'') { - if let Err(err) = unescape_byte(without_quotes) { - push_err(2, 0, err); - } + if let Some(without_quotes) = unquote(text, 2, '\'') + && let Err(err) = unescape_byte(without_quotes) + { + push_err(2, 0, err); } } ast::LiteralKind::IntNumber(_) @@ -224,14 +224,14 @@ pub(crate) fn validate_block_structure(root: &SyntaxNode) { } fn validate_numeric_name(name_ref: Option, errors: &mut Vec) { - if let Some(int_token) = int_token(name_ref) { - if int_token.text().chars().any(|c| !c.is_ascii_digit()) { - errors.push(SyntaxError::new( - "Tuple (struct) field access is only allowed through \ + if let Some(int_token) = int_token(name_ref) + && int_token.text().chars().any(|c| !c.is_ascii_digit()) + { + errors.push(SyntaxError::new( + "Tuple (struct) field access is only allowed through \ decimal integers with no underscores or suffix", - int_token.text_range(), - )); - } + int_token.text_range(), + )); } fn int_token(name_ref: Option) -> Option { @@ -285,13 +285,13 @@ fn validate_path_keywords(segment: ast::PathSegment, errors: &mut Vec Option { diff --git a/crates/test-fixture/src/lib.rs b/crates/test-fixture/src/lib.rs index 8937e53175ab..4413d2f222c1 100644 --- a/crates/test-fixture/src/lib.rs +++ b/crates/test-fixture/src/lib.rs @@ -955,12 +955,12 @@ impl ProcMacroExpander for DisallowCfgProcMacroExpander { _: String, ) -> Result { for tt in subtree.token_trees().flat_tokens() { - if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = tt { - if ident.sym == sym::cfg || ident.sym == sym::cfg_attr { - return Err(ProcMacroExpansionError::Panic( - "cfg or cfg_attr found in DisallowCfgProcMacroExpander".to_owned(), - )); - } + if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = tt + && (ident.sym == sym::cfg || ident.sym == sym::cfg_attr) + { + return Err(ProcMacroExpansionError::Panic( + "cfg or cfg_attr found in DisallowCfgProcMacroExpander".to_owned(), + )); } } Ok(subtree.clone()) diff --git a/crates/tt/src/lib.rs b/crates/tt/src/lib.rs index 44123385c8cc..243a27b83b0d 100644 --- a/crates/tt/src/lib.rs +++ b/crates/tt/src/lib.rs @@ -357,10 +357,10 @@ impl<'a, S: Copy> TokenTreesView<'a, S> { } pub fn try_into_subtree(self) -> Option> { - if let Some(TokenTree::Subtree(subtree)) = self.0.first() { - if subtree.usize_len() == (self.0.len() - 1) { - return Some(SubtreeView::new(self.0)); - } + if let Some(TokenTree::Subtree(subtree)) = self.0.first() + && subtree.usize_len() == (self.0.len() - 1) + { + return Some(SubtreeView::new(self.0)); } None } @@ -1028,10 +1028,10 @@ pub fn pretty(mut tkns: &[TokenTree]) -> String { tkns = rest; last = [last, tokentree_to_text(tkn, &mut tkns)].join(if last_to_joint { "" } else { " " }); last_to_joint = false; - if let TokenTree::Leaf(Leaf::Punct(punct)) = tkn { - if punct.spacing == Spacing::Joint { - last_to_joint = true; - } + if let TokenTree::Leaf(Leaf::Punct(punct)) = tkn + && punct.spacing == Spacing::Joint + { + last_to_joint = true; } } last diff --git a/crates/vfs-notify/src/lib.rs b/crates/vfs-notify/src/lib.rs index a03337dbc51e..c6393cc6922a 100644 --- a/crates/vfs-notify/src/lib.rs +++ b/crates/vfs-notify/src/lib.rs @@ -194,52 +194,49 @@ impl NotifyActor { } }, Event::NotifyEvent(event) => { - if let Some(event) = log_notify_error(event) { - if let EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) = + if let Some(event) = log_notify_error(event) + && let EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) = event.kind - { - let files = event - .paths - .into_iter() - .filter_map(|path| { - Some( - AbsPathBuf::try_from( - Utf8PathBuf::from_path_buf(path).ok()?, - ) + { + let files = event + .paths + .into_iter() + .filter_map(|path| { + Some( + AbsPathBuf::try_from(Utf8PathBuf::from_path_buf(path).ok()?) .expect("path is absolute"), - ) - }) - .filter_map(|path| -> Option<(AbsPathBuf, Option>)> { - let meta = fs::metadata(&path).ok()?; - if meta.file_type().is_dir() - && self - .watched_dir_entries - .iter() - .any(|dir| dir.contains_dir(&path)) - { - self.watch(path.as_ref()); - return None; - } - - if !meta.file_type().is_file() { - return None; - } - - if !(self.watched_file_entries.contains(&path) - || self - .watched_dir_entries - .iter() - .any(|dir| dir.contains_file(&path))) - { - return None; - } - - let contents = read(&path); - Some((path, contents)) - }) - .collect(); - self.send(loader::Message::Changed { files }); - } + ) + }) + .filter_map(|path| -> Option<(AbsPathBuf, Option>)> { + let meta = fs::metadata(&path).ok()?; + if meta.file_type().is_dir() + && self + .watched_dir_entries + .iter() + .any(|dir| dir.contains_dir(&path)) + { + self.watch(path.as_ref()); + return None; + } + + if !meta.file_type().is_file() { + return None; + } + + if !(self.watched_file_entries.contains(&path) + || self + .watched_dir_entries + .iter() + .any(|dir| dir.contains_file(&path))) + { + return None; + } + + let contents = read(&path); + Some((path, contents)) + }) + .collect(); + self.send(loader::Message::Changed { files }); } } } diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs index 19ca62e8a329..bc7eb88f3a84 100644 --- a/xtask/src/codegen.rs +++ b/xtask/src/codegen.rs @@ -173,11 +173,11 @@ fn add_preamble(cg: CodegenType, mut text: String) -> String { #[allow(clippy::print_stderr)] fn ensure_file_contents(cg: CodegenType, file: &Path, contents: &str, check: bool) -> bool { let contents = normalize_newlines(contents); - if let Ok(old_contents) = fs::read_to_string(file) { - if normalize_newlines(&old_contents) == contents { - // File is already up to date. - return false; - } + if let Ok(old_contents) = fs::read_to_string(file) + && normalize_newlines(&old_contents) == contents + { + // File is already up to date. + return false; } let display_path = file.strip_prefix(project_root()).unwrap_or(file); diff --git a/xtask/src/publish/notes.rs b/xtask/src/publish/notes.rs index 93592d4986f8..8d36fcb61b44 100644 --- a/xtask/src/publish/notes.rs +++ b/xtask/src/publish/notes.rs @@ -72,13 +72,13 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_document_title(&mut self) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((level, title)) = get_title(&line) { - let title = process_inline_macros(title)?; - if level == 1 { - self.write_title(level, &title); - return Ok(()); - } + if let Some(Ok(line)) = self.iter.next() + && let Some((level, title)) = get_title(&line) + { + let title = process_inline_macros(title)?; + if level == 1 { + self.write_title(level, &title); + return Ok(()); } } bail!("document title not found") @@ -141,39 +141,39 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_source_code_block(&mut self, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some(styles) = line.strip_prefix("[source").and_then(|s| s.strip_suffix(']')) { - let mut styles = styles.split(','); - if !styles.next().unwrap().is_empty() { - bail!("not a source code block"); - } - let language = styles.next(); - return self.process_listing_block(language, level); + if let Some(Ok(line)) = self.iter.next() + && let Some(styles) = line.strip_prefix("[source").and_then(|s| s.strip_suffix(']')) + { + let mut styles = styles.split(','); + if !styles.next().unwrap().is_empty() { + bail!("not a source code block"); } + let language = styles.next(); + return self.process_listing_block(language, level); } bail!("not a source code block") } fn process_listing_block(&mut self, style: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if line == LISTING_DELIMITER { - self.write_indent(level); - self.output.push_str("```"); - if let Some(style) = style { - self.output.push_str(style); - } - self.output.push('\n'); - while let Some(line) = self.iter.next() { - let line = line?; - if line == LISTING_DELIMITER { - self.write_line("```", level); - return Ok(()); - } else { - self.write_line(&line, level); - } + if let Some(Ok(line)) = self.iter.next() + && line == LISTING_DELIMITER + { + self.write_indent(level); + self.output.push_str("```"); + if let Some(style) = style { + self.output.push_str(style); + } + self.output.push('\n'); + while let Some(line) = self.iter.next() { + let line = line?; + if line == LISTING_DELIMITER { + self.write_line("```", level); + return Ok(()); + } else { + self.write_line(&line, level); } - bail!("listing block is not terminated") } + bail!("listing block is not terminated") } bail!("not a listing block") } @@ -200,49 +200,48 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_image_block(&mut self, caption: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((url, attrs)) = parse_media_block(&line, IMAGE_BLOCK_PREFIX) { - let alt = if let Some(stripped) = - attrs.strip_prefix('"').and_then(|s| s.strip_suffix('"')) - { + if let Some(Ok(line)) = self.iter.next() + && let Some((url, attrs)) = parse_media_block(&line, IMAGE_BLOCK_PREFIX) + { + let alt = + if let Some(stripped) = attrs.strip_prefix('"').and_then(|s| s.strip_suffix('"')) { stripped } else { attrs }; - if let Some(caption) = caption { - self.write_caption_line(caption, level); - } - self.write_indent(level); - self.output.push_str("!["); - self.output.push_str(alt); - self.output.push_str("]("); - self.output.push_str(url); - self.output.push_str(")\n"); - return Ok(()); + if let Some(caption) = caption { + self.write_caption_line(caption, level); } + self.write_indent(level); + self.output.push_str("!["); + self.output.push_str(alt); + self.output.push_str("]("); + self.output.push_str(url); + self.output.push_str(")\n"); + return Ok(()); } bail!("not a image block") } fn process_video_block(&mut self, caption: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((url, attrs)) = parse_media_block(&line, VIDEO_BLOCK_PREFIX) { - let html_attrs = match attrs { - "options=loop" => "controls loop", - r#"options="autoplay,loop""# => "autoplay controls loop", - _ => bail!("unsupported video syntax"), - }; - if let Some(caption) = caption { - self.write_caption_line(caption, level); - } - self.write_indent(level); - self.output.push_str(r#"\n"); - return Ok(()); + if let Some(Ok(line)) = self.iter.next() + && let Some((url, attrs)) = parse_media_block(&line, VIDEO_BLOCK_PREFIX) + { + let html_attrs = match attrs { + "options=loop" => "controls loop", + r#"options="autoplay,loop""# => "autoplay controls loop", + _ => bail!("unsupported video syntax"), + }; + if let Some(caption) = caption { + self.write_caption_line(caption, level); } + self.write_indent(level); + self.output.push_str(r#"\n"); + return Ok(()); } bail!("not a video block") } @@ -371,12 +370,11 @@ fn strip_prefix_symbol(line: &str, symbol: char) -> Option<(usize, &str)> { } fn parse_media_block<'a>(line: &'a str, prefix: &str) -> Option<(&'a str, &'a str)> { - if let Some(line) = line.strip_prefix(prefix) { - if let Some((url, rest)) = line.split_once('[') { - if let Some(attrs) = rest.strip_suffix(']') { - return Some((url, attrs)); - } - } + if let Some(line) = line.strip_prefix(prefix) + && let Some((url, rest)) = line.split_once('[') + && let Some(attrs) = rest.strip_suffix(']') + { + return Some((url, attrs)); } None }