From fe6271a73ce61c4ef0ef2a471a44725cce106b3a Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 9 Jun 2023 14:19:06 +0200 Subject: [PATCH 1/3] Add unstable cargo lint tables --- Cargo.toml | 22 ++++++++++++++++++++++ crates/base-db/Cargo.toml | 3 +++ crates/cfg/Cargo.toml | 3 +++ crates/flycheck/Cargo.toml | 3 +++ crates/hir-def/Cargo.toml | 3 +++ crates/hir-expand/Cargo.toml | 3 +++ crates/hir-ty/Cargo.toml | 3 +++ crates/hir/Cargo.toml | 3 +++ crates/ide-assists/Cargo.toml | 3 +++ crates/ide-completion/Cargo.toml | 3 +++ crates/ide-db/Cargo.toml | 3 +++ crates/ide-diagnostics/Cargo.toml | 3 +++ crates/ide-ssr/Cargo.toml | 3 +++ crates/ide/Cargo.toml | 3 +++ crates/intern/Cargo.toml | 3 +++ crates/limit/Cargo.toml | 3 +++ crates/mbe/Cargo.toml | 3 +++ crates/parser/Cargo.toml | 3 +++ crates/paths/Cargo.toml | 3 +++ crates/proc-macro-api/Cargo.toml | 3 +++ crates/proc-macro-srv-cli/Cargo.toml | 3 +++ crates/proc-macro-srv/Cargo.toml | 3 +++ crates/proc-macro-test/Cargo.toml | 3 +++ crates/profile/Cargo.toml | 3 +++ crates/project-model/Cargo.toml | 3 +++ crates/rust-analyzer/Cargo.toml | 3 +++ crates/sourcegen/Cargo.toml | 3 +++ crates/stdx/Cargo.toml | 3 +++ crates/syntax/Cargo.toml | 3 +++ crates/test-utils/Cargo.toml | 3 +++ crates/text-edit/Cargo.toml | 3 +++ crates/toolchain/Cargo.toml | 3 +++ crates/tt/Cargo.toml | 3 +++ crates/vfs-notify/Cargo.toml | 3 +++ crates/vfs/Cargo.toml | 3 +++ 35 files changed, 124 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 3050cf764a4c..fbbcf198ce7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -92,3 +92,25 @@ serde_json = "1.0.94" triomphe = { version = "0.1.8", default-features = false, features = ["std"] } rustc_lexer = { version = "0.1.0", package = "ra-ap-rustc_lexer" } + +[workspace.lints.rust] +rust_2018_idioms = "warn" +unused_lifetimes = "warn" +semicolon_in_expressions_from_macros = "warn" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +# () makes a fine error in most cases +result_unit_err = "allow" +# We don't expose public APIs that matter like this +len_without_is_empty = "allow" +# Should be tackled at some point +too_many_arguments = "allow" +# Should be tackled at some point +type_complexity = "allow" +# we currently prefer explicit control flow return over `...?;` statements whose result is unused +question_mark = "allow" +# We have macros that rely on this currently +enum_variant_names = "allow" +# Builder pattern disagrees +new_ret_no_self = "allow" diff --git a/crates/base-db/Cargo.toml b/crates/base-db/Cargo.toml index 6001772c86ee..7948d299795f 100644 --- a/crates/base-db/Cargo.toml +++ b/crates/base-db/Cargo.toml @@ -27,3 +27,6 @@ syntax.workspace = true test-utils.workspace = true tt.workspace = true vfs.workspace = true + +[lints] +workspace = true diff --git a/crates/cfg/Cargo.toml b/crates/cfg/Cargo.toml index 0880bc239d83..8c62bac89958 100644 --- a/crates/cfg/Cargo.toml +++ b/crates/cfg/Cargo.toml @@ -29,3 +29,6 @@ derive_arbitrary = "1.2.2" # local deps mbe.workspace = true syntax.workspace = true + +[lints] +workspace = true diff --git a/crates/flycheck/Cargo.toml b/crates/flycheck/Cargo.toml index 3f6671b1c43d..d7b38baac8e4 100644 --- a/crates/flycheck/Cargo.toml +++ b/crates/flycheck/Cargo.toml @@ -24,3 +24,6 @@ command-group = "2.0.1" paths.workspace = true stdx.workspace = true toolchain.workspace = true + +[lints] +workspace = true diff --git a/crates/hir-def/Cargo.toml b/crates/hir-def/Cargo.toml index 83c7051646ed..50579ac4b36e 100644 --- a/crates/hir-def/Cargo.toml +++ b/crates/hir-def/Cargo.toml @@ -51,3 +51,6 @@ expect-test = "1.4.0" # local deps test-utils.workspace = true + +[lints] +workspace = true diff --git a/crates/hir-expand/Cargo.toml b/crates/hir-expand/Cargo.toml index 40d8659f25ba..0831c9543031 100644 --- a/crates/hir-expand/Cargo.toml +++ b/crates/hir-expand/Cargo.toml @@ -37,3 +37,6 @@ limit.workspace = true [dev-dependencies] expect-test = "1.4.0" + +[lints] +workspace = true diff --git a/crates/hir-ty/Cargo.toml b/crates/hir-ty/Cargo.toml index 6ca0dbb85039..218deecea955 100644 --- a/crates/hir-ty/Cargo.toml +++ b/crates/hir-ty/Cargo.toml @@ -55,3 +55,6 @@ project-model = { path = "../project-model" } # local deps test-utils.workspace = true + +[lints] +workspace = true diff --git a/crates/hir/Cargo.toml b/crates/hir/Cargo.toml index a20aff93f19b..94850783bbec 100644 --- a/crates/hir/Cargo.toml +++ b/crates/hir/Cargo.toml @@ -30,3 +30,6 @@ profile.workspace = true stdx.workspace = true syntax.workspace = true tt.workspace = true + +[lints] +workspace = true diff --git a/crates/ide-assists/Cargo.toml b/crates/ide-assists/Cargo.toml index 447e38f91f43..ab1786b4f958 100644 --- a/crates/ide-assists/Cargo.toml +++ b/crates/ide-assists/Cargo.toml @@ -35,3 +35,6 @@ sourcegen.workspace = true [features] in-rust-tree = [] + +[lints] +workspace = true diff --git a/crates/ide-completion/Cargo.toml b/crates/ide-completion/Cargo.toml index 092fb303668f..cd6d474d77c5 100644 --- a/crates/ide-completion/Cargo.toml +++ b/crates/ide-completion/Cargo.toml @@ -35,3 +35,6 @@ expect-test = "1.4.0" # local deps test-utils.workspace = true + +[lints] +workspace = true diff --git a/crates/ide-db/Cargo.toml b/crates/ide-db/Cargo.toml index 4e75dc4dba54..58945c59734f 100644 --- a/crates/ide-db/Cargo.toml +++ b/crates/ide-db/Cargo.toml @@ -48,3 +48,6 @@ xshell = "0.2.2" # local deps test-utils.workspace = true sourcegen.workspace = true + +[lints] +workspace = true diff --git a/crates/ide-diagnostics/Cargo.toml b/crates/ide-diagnostics/Cargo.toml index e18624fcc267..3224d3238624 100644 --- a/crates/ide-diagnostics/Cargo.toml +++ b/crates/ide-diagnostics/Cargo.toml @@ -35,3 +35,6 @@ sourcegen.workspace = true [features] in-rust-tree = [] + +[lints] +workspace = true diff --git a/crates/ide-ssr/Cargo.toml b/crates/ide-ssr/Cargo.toml index 70ed6dea5bf2..3978b73b73de 100644 --- a/crates/ide-ssr/Cargo.toml +++ b/crates/ide-ssr/Cargo.toml @@ -31,3 +31,6 @@ expect-test = "1.4.0" # local deps test-utils.workspace = true + +[lints] +workspace = true diff --git a/crates/ide/Cargo.toml b/crates/ide/Cargo.toml index 2aee203c4ea5..937a9a1d593b 100644 --- a/crates/ide/Cargo.toml +++ b/crates/ide/Cargo.toml @@ -52,3 +52,6 @@ test-utils.workspace = true [features] in-rust-tree = ["ide-assists/in-rust-tree", "ide-diagnostics/in-rust-tree"] + +[lints] +workspace = true diff --git a/crates/intern/Cargo.toml b/crates/intern/Cargo.toml index dcd0d7881255..d1e568ed7755 100644 --- a/crates/intern/Cargo.toml +++ b/crates/intern/Cargo.toml @@ -19,3 +19,6 @@ hashbrown = { version = "0.12.1", default-features = false } once_cell = "1.17.0" rustc-hash = "1.1.0" triomphe.workspace = true + +[lints] +workspace = true diff --git a/crates/limit/Cargo.toml b/crates/limit/Cargo.toml index c08886909922..0e6fd2b2ad39 100644 --- a/crates/limit/Cargo.toml +++ b/crates/limit/Cargo.toml @@ -11,3 +11,6 @@ rust-version.workspace = true [features] tracking = [] default = ["tracking"] + +[lints] +workspace = true diff --git a/crates/mbe/Cargo.toml b/crates/mbe/Cargo.toml index 82105522ebdd..bb587448a49b 100644 --- a/crates/mbe/Cargo.toml +++ b/crates/mbe/Cargo.toml @@ -25,3 +25,6 @@ stdx.workspace = true [dev-dependencies] test-utils.workspace = true + +[lints] +workspace = true diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml index 09e62c35278e..503a83e87919 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -22,3 +22,6 @@ expect-test = "1.4.0" stdx.workspace = true sourcegen.workspace = true + +[lints] +workspace = true diff --git a/crates/paths/Cargo.toml b/crates/paths/Cargo.toml index 28b54be5212f..a06f0b11b3d9 100644 --- a/crates/paths/Cargo.toml +++ b/crates/paths/Cargo.toml @@ -16,3 +16,6 @@ doctest = false # serde-derive crate. Even though we don't activate the derive feature here, # someone else in the crate graph certainly does! # serde.workspace = true + +[lints] +workspace = true diff --git a/crates/proc-macro-api/Cargo.toml b/crates/proc-macro-api/Cargo.toml index d3486e75575b..fbe9d54f2ed6 100644 --- a/crates/proc-macro-api/Cargo.toml +++ b/crates/proc-macro-api/Cargo.toml @@ -33,3 +33,6 @@ stdx.workspace = true profile.workspace = true # Intentionally *not* depend on anything salsa-related # base-db.workspace = true + +[lints] +workspace = true diff --git a/crates/proc-macro-srv-cli/Cargo.toml b/crates/proc-macro-srv-cli/Cargo.toml index 8f03c6ec7b57..2597a3ae7f75 100644 --- a/crates/proc-macro-srv-cli/Cargo.toml +++ b/crates/proc-macro-srv-cli/Cargo.toml @@ -18,3 +18,6 @@ sysroot-abi = ["proc-macro-srv/sysroot-abi"] [[bin]] name = "rust-analyzer-proc-macro-srv" path = "src/main.rs" + +[lints] +workspace = true diff --git a/crates/proc-macro-srv/Cargo.toml b/crates/proc-macro-srv/Cargo.toml index d5eb157bfef9..49370270190d 100644 --- a/crates/proc-macro-srv/Cargo.toml +++ b/crates/proc-macro-srv/Cargo.toml @@ -36,3 +36,6 @@ proc-macro-test.workspace = true [features] sysroot-abi = [] + +[lints] +workspace = true diff --git a/crates/proc-macro-test/Cargo.toml b/crates/proc-macro-test/Cargo.toml index 77b4afd7d7e1..3a26f08e5b7e 100644 --- a/crates/proc-macro-test/Cargo.toml +++ b/crates/proc-macro-test/Cargo.toml @@ -18,3 +18,6 @@ proc-macro-test-impl = { path = "imp", version = "0.0.0" } # local deps toolchain.workspace = true + +[lints] +workspace = true diff --git a/crates/profile/Cargo.toml b/crates/profile/Cargo.toml index 602e74275106..cb5686aa74da 100644 --- a/crates/profile/Cargo.toml +++ b/crates/profile/Cargo.toml @@ -31,3 +31,6 @@ jemalloc = ["jemalloc-ctl"] # Uncomment to enable for the whole crate graph # default = [ "cpu_profiler" ] + +[lints] +workspace = true diff --git a/crates/project-model/Cargo.toml b/crates/project-model/Cargo.toml index 3abff64a83b2..34e159924513 100644 --- a/crates/project-model/Cargo.toml +++ b/crates/project-model/Cargo.toml @@ -33,3 +33,6 @@ toolchain.workspace = true [dev-dependencies] expect-test = "1.4.0" + +[lints] +workspace = true diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml index 5b72d57560b2..ab059d204e5a 100644 --- a/crates/rust-analyzer/Cargo.toml +++ b/crates/rust-analyzer/Cargo.toml @@ -96,3 +96,6 @@ jemalloc = ["jemallocator", "profile/jemalloc"] force-always-assert = ["always-assert/force"] sysroot-abi = [] in-rust-tree = ["sysroot-abi", "ide/in-rust-tree", "syntax/in-rust-tree"] + +[lints] +workspace = true diff --git a/crates/sourcegen/Cargo.toml b/crates/sourcegen/Cargo.toml index fb2b9ebef506..a61c8e2f435f 100644 --- a/crates/sourcegen/Cargo.toml +++ b/crates/sourcegen/Cargo.toml @@ -13,3 +13,6 @@ doctest = false [dependencies] xshell = "0.2.2" + +[lints] +workspace = true diff --git a/crates/stdx/Cargo.toml b/crates/stdx/Cargo.toml index a67f36ae9006..28eca78e914b 100644 --- a/crates/stdx/Cargo.toml +++ b/crates/stdx/Cargo.toml @@ -26,3 +26,6 @@ winapi = { version = "0.3.9", features = ["winerror"] } [features] # Uncomment to enable for the whole crate graph # default = [ "backtrace" ] + +[lints] +workspace = true diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml index fb38d25ab541..e08ba3c67f38 100644 --- a/crates/syntax/Cargo.toml +++ b/crates/syntax/Cargo.toml @@ -42,3 +42,6 @@ sourcegen.workspace = true [features] in-rust-tree = [] + +[lints] +workspace = true diff --git a/crates/test-utils/Cargo.toml b/crates/test-utils/Cargo.toml index 2b5b6f495616..cf9cbeed680e 100644 --- a/crates/test-utils/Cargo.toml +++ b/crates/test-utils/Cargo.toml @@ -19,3 +19,6 @@ rustc-hash = "1.1.0" stdx.workspace = true profile.workspace = true + +[lints] +workspace = true diff --git a/crates/text-edit/Cargo.toml b/crates/text-edit/Cargo.toml index 76d0ca5ccb60..ff5f64633747 100644 --- a/crates/text-edit/Cargo.toml +++ b/crates/text-edit/Cargo.toml @@ -14,3 +14,6 @@ doctest = false [dependencies] itertools = "0.10.5" text-size.workspace = true + +[lints] +workspace = true diff --git a/crates/toolchain/Cargo.toml b/crates/toolchain/Cargo.toml index a283f9a88421..2b55859a0027 100644 --- a/crates/toolchain/Cargo.toml +++ b/crates/toolchain/Cargo.toml @@ -13,3 +13,6 @@ doctest = false [dependencies] home = "0.5.4" + +[lints] +workspace = true diff --git a/crates/tt/Cargo.toml b/crates/tt/Cargo.toml index a28ee5f1ca2b..e19adab76d05 100644 --- a/crates/tt/Cargo.toml +++ b/crates/tt/Cargo.toml @@ -15,3 +15,6 @@ doctest = false smol_str.workspace = true stdx.workspace = true + +[lints] +workspace = true diff --git a/crates/vfs-notify/Cargo.toml b/crates/vfs-notify/Cargo.toml index 5d61a227284e..ddc91c95447d 100644 --- a/crates/vfs-notify/Cargo.toml +++ b/crates/vfs-notify/Cargo.toml @@ -20,3 +20,6 @@ notify = "5.0" stdx.workspace = true vfs.workspace = true paths.workspace = true + +[lints] +workspace = true diff --git a/crates/vfs/Cargo.toml b/crates/vfs/Cargo.toml index 3ae3dc83ca9b..8a00b1efc4cf 100644 --- a/crates/vfs/Cargo.toml +++ b/crates/vfs/Cargo.toml @@ -19,3 +19,6 @@ nohash-hasher.workspace = true paths.workspace = true stdx.workspace = true + +[lints] +workspace = true From f7c3b7e8057c3c5d06ae65f428d07b1bc20b97f5 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 9 Jun 2023 20:09:47 +0200 Subject: [PATCH 2/3] Fix clippy lints --- crates/base-db/src/fixture.rs | 2 +- crates/base-db/src/input.rs | 10 +- crates/flycheck/src/lib.rs | 1 + crates/hir-def/src/attr.rs | 2 +- crates/hir-def/src/body.rs | 4 +- crates/hir-def/src/body/lower.rs | 2 +- crates/hir-def/src/data.rs | 2 +- crates/hir-def/src/data/adt.rs | 2 +- crates/hir-def/src/db.rs | 8 +- crates/hir-def/src/find_path.rs | 2 +- crates/hir-def/src/generics.rs | 1 + crates/hir-def/src/lang_item.rs | 1 + crates/hir-def/src/nameres/collector.rs | 12 +- crates/hir-def/src/nameres/path_resolution.rs | 2 +- crates/hir-def/src/nameres/tests/macros.rs | 4 +- crates/hir-def/src/path.rs | 6 +- crates/hir-def/src/path/lower.rs | 2 +- crates/hir-def/src/per_ns.rs | 8 +- crates/hir-def/src/resolver.rs | 67 ++++--- crates/hir-def/src/test_db.rs | 2 + crates/hir-expand/src/attrs.rs | 6 +- crates/hir-expand/src/builtin_fn_macro.rs | 2 +- crates/hir-expand/src/quote.rs | 36 ++-- crates/hir-ty/src/chalk_db.rs | 2 +- crates/hir-ty/src/chalk_ext.rs | 4 +- crates/hir-ty/src/consteval.rs | 4 +- crates/hir-ty/src/diagnostics/decl_check.rs | 1 + crates/hir-ty/src/diagnostics/expr.rs | 39 ++-- crates/hir-ty/src/display.rs | 33 ++-- crates/hir-ty/src/infer.rs | 25 ++- crates/hir-ty/src/infer/closure.rs | 42 ++--- crates/hir-ty/src/infer/expr.rs | 15 +- crates/hir-ty/src/infer/pat.rs | 10 +- crates/hir-ty/src/infer/path.rs | 2 +- crates/hir-ty/src/infer/unify.rs | 8 +- crates/hir-ty/src/inhabitedness.rs | 3 +- crates/hir-ty/src/interner.rs | 2 +- crates/hir-ty/src/layout.rs | 6 +- crates/hir-ty/src/layout/adt.rs | 2 +- crates/hir-ty/src/layout/target.rs | 2 +- crates/hir-ty/src/layout/tests.rs | 10 +- crates/hir-ty/src/layout/tests/closure.rs | 1 + crates/hir-ty/src/lib.rs | 2 +- crates/hir-ty/src/lower.rs | 2 +- crates/hir-ty/src/method_resolution.rs | 9 +- crates/hir-ty/src/mir.rs | 12 +- crates/hir-ty/src/mir/borrowck.rs | 6 +- crates/hir-ty/src/mir/eval.rs | 170 ++++++++---------- crates/hir-ty/src/mir/eval/shim.rs | 8 +- crates/hir-ty/src/mir/eval/tests.rs | 6 +- crates/hir-ty/src/mir/lower.rs | 45 +++-- crates/hir-ty/src/mir/lower/as_place.rs | 80 ++++----- .../hir-ty/src/mir/lower/pattern_matching.rs | 39 ++-- crates/hir-ty/src/mir/monomorphization.rs | 11 +- crates/hir-ty/src/test_db.rs | 4 +- crates/hir-ty/src/utils.rs | 2 +- crates/hir/src/lib.rs | 54 +++--- crates/hir/src/semantics.rs | 8 +- crates/hir/src/semantics/source_to_def.rs | 5 +- crates/hir/src/source_analyzer.rs | 12 +- .../src/handlers/add_missing_match_arms.rs | 6 +- .../ide-assists/src/handlers/auto_import.rs | 2 +- .../src/handlers/convert_match_to_let_else.rs | 2 +- .../convert_nested_function_to_closure.rs | 4 +- ...ert_two_arm_bool_match_to_matches_macro.rs | 2 +- .../extract_expressions_from_format_string.rs | 2 +- .../src/handlers/extract_function.rs | 33 ++-- .../src/handlers/extract_module.rs | 11 +- .../src/handlers/extract_type_alias.rs | 2 +- .../src/handlers/generate_constant.rs | 7 +- .../src/handlers/generate_delegate_methods.rs | 2 +- .../generate_documentation_template.rs | 2 +- .../src/handlers/generate_enum_variant.rs | 4 +- .../src/handlers/generate_getter.rs | 16 +- .../ide-assists/src/handlers/generate_impl.rs | 4 +- .../handlers/generate_is_empty_from_len.rs | 2 +- .../src/handlers/inline_const_as_literal.rs | 20 +-- .../ide-assists/src/handlers/inline_macro.rs | 2 +- .../src/handlers/introduce_named_lifetime.rs | 4 +- .../src/handlers/replace_if_let_with_match.rs | 2 +- .../src/handlers/replace_method_eager_lazy.rs | 2 +- .../replace_turbofish_with_explicit_type.rs | 4 +- .../src/handlers/unnecessary_async.rs | 4 +- .../ide-assists/src/handlers/unwrap_block.rs | 2 +- crates/ide-assists/src/tests.rs | 2 +- crates/ide-assists/src/tests/sourcegen.rs | 2 +- crates/ide-assists/src/utils/suggest_name.rs | 8 +- .../src/completions/env_vars.rs | 2 +- .../ide-completion/src/completions/field.rs | 26 ++- .../src/completions/flyimport.rs | 5 +- .../src/completions/fn_param.rs | 2 +- .../src/completions/item_list.rs | 2 +- crates/ide-completion/src/context/analysis.rs | 17 +- crates/ide-completion/src/item.rs | 2 +- crates/ide-completion/src/render.rs | 9 +- crates/ide-completion/src/render/function.rs | 54 +++--- crates/ide-completion/src/render/literal.rs | 10 +- crates/ide-completion/src/render/macro_.rs | 2 +- crates/ide-completion/src/tests.rs | 2 +- crates/ide-db/src/active_parameter.rs | 24 ++- crates/ide-db/src/items_locator.rs | 6 +- crates/ide-db/src/lib.rs | 6 +- .../src/handlers/incoherent_impl.rs | 2 +- .../src/handlers/missing_fields.rs | 2 +- .../src/handlers/type_mismatch.rs | 2 +- crates/ide-diagnostics/src/lib.rs | 4 +- crates/ide-ssr/src/fragments.rs | 4 +- crates/ide-ssr/src/matching.rs | 10 +- crates/ide/src/annotations.rs | 3 +- crates/ide/src/annotations/fn_references.rs | 2 +- crates/ide/src/doc_links.rs | 8 +- crates/ide/src/doc_links/tests.rs | 27 ++- crates/ide/src/fetch_crates.rs | 2 +- crates/ide/src/folding_ranges.rs | 3 +- crates/ide/src/highlight_related.rs | 3 +- crates/ide/src/hover/render.rs | 8 +- crates/ide/src/inlay_hints.rs | 2 +- crates/ide/src/inlay_hints/discriminant.rs | 2 +- crates/ide/src/inlay_hints/fn_lifetime_fn.rs | 16 +- crates/ide/src/inlay_hints/param_name.rs | 2 +- crates/ide/src/interpret_function.rs | 2 +- crates/ide/src/lib.rs | 4 +- crates/ide/src/moniker.rs | 7 +- crates/ide/src/signature_help.rs | 2 +- crates/ide/src/syntax_highlighting.rs | 7 +- crates/ide/src/typing.rs | 9 +- crates/ide/src/view_crate_graph.rs | 2 +- crates/intern/src/lib.rs | 14 +- crates/mbe/src/expander/transcriber.rs | 6 +- crates/mbe/src/syntax_bridge.rs | 5 +- crates/proc-macro-api/src/msg.rs | 1 + crates/proc-macro-test/imp/src/lib.rs | 1 + crates/project-model/src/cargo_workspace.rs | 6 +- crates/project-model/src/manifest_path.rs | 2 +- crates/project-model/src/tests.rs | 2 +- crates/project-model/src/workspace.rs | 11 +- crates/rust-analyzer/src/bin/main.rs | 2 +- .../rust-analyzer/src/cli/analysis_stats.rs | 12 +- crates/rust-analyzer/src/cli/diagnostics.rs | 4 +- crates/rust-analyzer/src/cli/lsif.rs | 4 +- crates/rust-analyzer/src/cli/scip.rs | 8 +- crates/rust-analyzer/src/cli/ssr.rs | 4 +- crates/rust-analyzer/src/config.rs | 14 +- crates/rust-analyzer/src/global_state.rs | 4 +- .../src/handlers/notification.rs | 2 +- crates/rust-analyzer/src/lsp_utils.rs | 2 +- crates/rust-analyzer/src/main_loop.rs | 2 +- crates/rust-analyzer/src/reload.rs | 85 +++++---- crates/rust-analyzer/src/semantic_tokens.rs | 2 +- crates/rust-analyzer/src/to_proto.rs | 28 ++- .../rust-analyzer/tests/slow-tests/support.rs | 1 + crates/syntax/src/ast/edit_in_place.rs | 12 +- crates/syntax/src/ast/make.rs | 6 +- crates/tt/src/buffer.rs | 1 + lib/line-index/tests/it.rs | 13 +- 155 files changed, 734 insertions(+), 847 deletions(-) diff --git a/crates/base-db/src/fixture.rs b/crates/base-db/src/fixture.rs index 5b11343173b3..1759733f2e0f 100644 --- a/crates/base-db/src/fixture.rs +++ b/crates/base-db/src/fixture.rs @@ -116,7 +116,7 @@ impl ChangeFixture { let toolchain = toolchain .map(|it| { ReleaseChannel::from_str(&it) - .unwrap_or_else(|| panic!("unknown release channel found: {it}")) + .unwrap_or_else(|()| panic!("unknown release channel found: {it}")) }) .unwrap_or(ReleaseChannel::Stable); let mut change = Change::new(); diff --git a/crates/base-db/src/input.rs b/crates/base-db/src/input.rs index e8d521b42f86..0bd15cfa4ffc 100644 --- a/crates/base-db/src/input.rs +++ b/crates/base-db/src/input.rs @@ -282,13 +282,17 @@ impl ReleaseChannel { ReleaseChannel::Nightly => "nightly", } } +} + +impl FromStr for ReleaseChannel { + type Err = (); - pub fn from_str(str: &str) -> Option { - Some(match str { + fn from_str(str: &str) -> Result { + Ok(match str { "" => ReleaseChannel::Stable, "nightly" => ReleaseChannel::Nightly, _ if str.starts_with("beta") => ReleaseChannel::Beta, - _ => return None, + _ => return Err(()), }) } } diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs index fbb943ccb99d..e07eb7c8662d 100644 --- a/crates/flycheck/src/lib.rs +++ b/crates/flycheck/src/lib.rs @@ -513,6 +513,7 @@ impl CargoActor { } } +#[allow(clippy::large_enum_variant)] enum CargoMessage { CompilerArtifact(cargo_metadata::Artifact), Diagnostic(Diagnostic), diff --git a/crates/hir-def/src/attr.rs b/crates/hir-def/src/attr.rs index bab3bbc2329a..49eb7c722070 100644 --- a/crates/hir-def/src/attr.rs +++ b/crates/hir-def/src/attr.rs @@ -379,7 +379,7 @@ fn parse_comma_sep(subtree: &tt::Subtree) -> Vec { } impl AttrsWithOwner { - pub(crate) fn attrs_with_owner(db: &dyn DefDatabase, owner: AttrDefId) -> Self { + pub(crate) fn attrs_with_owner_query(db: &dyn DefDatabase, owner: AttrDefId) -> Self { Self { attrs: db.attrs(owner), owner } } diff --git a/crates/hir-def/src/body.rs b/crates/hir-def/src/body.rs index 36626ed1a9b1..2e1c7b916f23 100644 --- a/crates/hir-def/src/body.rs +++ b/crates/hir-def/src/body.rs @@ -242,12 +242,12 @@ impl Body { } } Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => { - args.iter().copied().for_each(|p| f(p)); + args.iter().copied().for_each(&mut f); } Pat::Ref { pat, .. } => f(*pat), Pat::Slice { prefix, slice, suffix } => { let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter()); - total_iter.copied().for_each(|p| f(p)); + total_iter.copied().for_each(&mut f); } Pat::Record { args, .. } => { args.iter().for_each(|RecordFieldPat { pat, .. }| f(*pat)); diff --git a/crates/hir-def/src/body/lower.rs b/crates/hir-def/src/body/lower.rs index 7b88e525bf18..972229a51f33 100644 --- a/crates/hir-def/src/body/lower.rs +++ b/crates/hir-def/src/body/lower.rs @@ -811,7 +811,7 @@ impl ExprCollector<'_> { expr: iterator, arms: Box::new([MatchArm { pat: iter_pat, guard: None, expr: loop_outer }]), }, - syntax_ptr.clone(), + syntax_ptr, ) } diff --git a/crates/hir-def/src/data.rs b/crates/hir-def/src/data.rs index 40e6a4308784..a2ccb5be4c38 100644 --- a/crates/hir-def/src/data.rs +++ b/crates/hir-def/src/data.rs @@ -739,7 +739,7 @@ impl<'a> AssocItemCollector<'a> { self.diagnostics.push(DefDiagnostic::macro_expansion_parse_error( self.module_id.local_id, error_call_kind(), - errors.into(), + errors, )); } diff --git a/crates/hir-def/src/data/adt.rs b/crates/hir-def/src/data/adt.rs index 6db5abccc921..d71cfdbbbccc 100644 --- a/crates/hir-def/src/data/adt.rs +++ b/crates/hir-def/src/data/adt.rs @@ -473,7 +473,7 @@ fn lower_struct( trace: &mut Trace>, ast: &InFile, ) -> StructKind { - let ctx = LowerCtx::new(db, &expander.hygiene(), ast.file_id); + let ctx = LowerCtx::new(db, expander.hygiene(), ast.file_id); match &ast.value { ast::StructKind::Tuple(fl) => { diff --git a/crates/hir-def/src/db.rs b/crates/hir-def/src/db.rs index 6d18e3f56cab..acba4f7a6668 100644 --- a/crates/hir-def/src/db.rs +++ b/crates/hir-def/src/db.rs @@ -193,7 +193,7 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast Attrs; #[salsa::transparent] - #[salsa::invoke(AttrsWithOwner::attrs_with_owner)] + #[salsa::invoke(AttrsWithOwner::attrs_with_owner_query)] fn attrs_with_owner(&self, def: AttrDefId) -> AttrsWithOwner; // endregion:attrs @@ -271,10 +271,8 @@ fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: CrateId) -> bool { None => continue, }; - let segments = tt.split(|tt| match tt { - tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => true, - _ => false, - }); + let segments = + tt.split(|tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',')); for output in segments.skip(1) { match output { [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.text == "no_std" => { diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index e8cc2eab4617..0ae7643958e4 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -206,7 +206,7 @@ fn find_path_for_module( } if let value @ Some(_) = - find_in_prelude(db, &root_def_map, &def_map, ItemInNs::Types(module_id.into()), from) + find_in_prelude(db, &root_def_map, def_map, ItemInNs::Types(module_id.into()), from) { return value; } diff --git a/crates/hir-def/src/generics.rs b/crates/hir-def/src/generics.rs index f19c3f028f42..c39f97373578 100644 --- a/crates/hir-def/src/generics.rs +++ b/crates/hir-def/src/generics.rs @@ -300,6 +300,7 @@ impl GenericParams { } } + #[allow(clippy::borrowed_box)] fn add_where_predicate_from_bound( &mut self, lower_ctx: &LowerCtx<'_>, diff --git a/crates/hir-def/src/lang_item.rs b/crates/hir-def/src/lang_item.rs index 0e9ac58fbaaa..fc59636b8e67 100644 --- a/crates/hir-def/src/lang_item.rs +++ b/crates/hir-def/src/lang_item.rs @@ -219,6 +219,7 @@ macro_rules! language_item_table { } } + #[allow(clippy::should_implement_trait)] /// Opposite of [`LangItem::name`] pub fn from_str(name: &str) -> Option { match name { diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index 06542b4b1e99..432fe9e4c5cb 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -1388,14 +1388,14 @@ impl DefCollector<'_> { always!(krate == loc.def.krate); DefDiagnostic::unresolved_proc_macro(module_id, loc.kind.clone(), loc.def.krate) } - _ => DefDiagnostic::macro_error(module_id, loc.kind.clone(), err.to_string()), + _ => DefDiagnostic::macro_error(module_id, loc.kind, err.to_string()), }; self.def_map.diagnostics.push(diag); } if let errors @ [_, ..] = &*value { let loc: MacroCallLoc = self.db.lookup_intern_macro_call(macro_call_id); - let diag = DefDiagnostic::macro_expansion_parse_error(module_id, loc.kind, &errors); + let diag = DefDiagnostic::macro_expansion_parse_error(module_id, loc.kind, errors); self.def_map.diagnostics.push(diag); } @@ -1847,7 +1847,7 @@ impl ModCollector<'_, '_> { item_tree: self.item_tree, mod_dir, } - .collect_in_top_module(&*items); + .collect_in_top_module(items); if is_macro_use { self.import_all_legacy_macros(module_id); } @@ -2238,9 +2238,9 @@ impl ModCollector<'_, '_> { fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) { let macros = self.def_collector.def_map[module_id].scope.collect_legacy_macros(); for (name, macs) in macros { - macs.last().map(|&mac| { - self.def_collector.define_legacy_macro(self.module_id, name.clone(), mac) - }); + if let Some(&mac) = macs.last() { + self.def_collector.define_legacy_macro(self.module_id, name.clone(), mac); + } } } diff --git a/crates/hir-def/src/nameres/path_resolution.rs b/crates/hir-def/src/nameres/path_resolution.rs index 5f6163175a72..01248ae07876 100644 --- a/crates/hir-def/src/nameres/path_resolution.rs +++ b/crates/hir-def/src/nameres/path_resolution.rs @@ -454,7 +454,7 @@ impl DefMap { let macro_use_prelude = || { self.macro_use_prelude .get(name) - .map_or(PerNs::none(), |&it| PerNs::macros(it.into(), Visibility::Public)) + .map_or(PerNs::none(), |&it| PerNs::macros(it, Visibility::Public)) }; let prelude = || self.resolve_in_prelude(db, name); diff --git a/crates/hir-def/src/nameres/tests/macros.rs b/crates/hir-def/src/nameres/tests/macros.rs index f4cca8d68d0a..eabf93f1b6cf 100644 --- a/crates/hir-def/src/nameres/tests/macros.rs +++ b/crates/hir-def/src/nameres/tests/macros.rs @@ -1294,8 +1294,8 @@ fn proc_attr(a: TokenStream, b: TokenStream) -> TokenStream { a } let actual = def_map .macro_use_prelude - .iter() - .map(|(name, _)| name.display(&db).to_string()) + .keys() + .map(|name| name.display(&db).to_string()) .sorted() .join("\n"); diff --git a/crates/hir-def/src/path.rs b/crates/hir-def/src/path.rs index b9b808254971..a902117c79c6 100644 --- a/crates/hir-def/src/path.rs +++ b/crates/hir-def/src/path.rs @@ -150,7 +150,7 @@ impl Path { pub fn mod_path(&self) -> Option<&ModPath> { match self { - Path::Normal { mod_path, .. } => Some(&mod_path), + Path::Normal { mod_path, .. } => Some(mod_path), Path::LangItem(_) => None, } } @@ -215,13 +215,13 @@ impl<'a> PathSegments<'a> { } pub fn skip(&self, len: usize) -> PathSegments<'a> { PathSegments { - segments: &self.segments.get(len..).unwrap_or(&[]), + segments: self.segments.get(len..).unwrap_or(&[]), generic_args: self.generic_args.and_then(|it| it.get(len..)), } } pub fn take(&self, len: usize) -> PathSegments<'a> { PathSegments { - segments: &self.segments.get(..len).unwrap_or(&self.segments), + segments: self.segments.get(..len).unwrap_or(self.segments), generic_args: self.generic_args.map(|it| it.get(..len).unwrap_or(it)), } } diff --git a/crates/hir-def/src/path/lower.rs b/crates/hir-def/src/path/lower.rs index 26d2706175ca..917ad0986e66 100644 --- a/crates/hir-def/src/path/lower.rs +++ b/crates/hir-def/src/path/lower.rs @@ -45,7 +45,7 @@ pub(super) fn lower_path(mut path: ast::Path, ctx: &LowerCtx<'_>) -> Option, pub values: Option<(ModuleDefId, Visibility)>, pub macros: Option<(MacroId, Visibility)>, } -impl Default for PerNs { - fn default() -> Self { - PerNs { types: None, values: None, macros: None } - } -} - impl PerNs { pub fn none() -> PerNs { PerNs { types: None, values: None, macros: None } diff --git a/crates/hir-def/src/resolver.rs b/crates/hir-def/src/resolver.rs index 06f5b2526a45..7cfb974987bf 100644 --- a/crates/hir-def/src/resolver.rs +++ b/crates/hir-def/src/resolver.rs @@ -69,15 +69,15 @@ impl fmt::Debug for ExprScope { #[derive(Debug, Clone)] enum Scope { /// All the items and imported names of a module - BlockScope(ModuleItemMap), + Block(ModuleItemMap), /// Brings the generic parameters of an item into scope GenericParams { def: GenericDefId, params: Interned }, /// Brings `Self` in `impl` block into scope - ImplDefScope(ImplId), + ImplDef(ImplId), /// Brings `Self` in enum, struct and union definitions into scope - AdtScope(AdtId), + Adt(AdtId), /// Local bindings - ExprScope(ExprScope), + Expr(ExprScope), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -210,23 +210,23 @@ impl Resolver { for scope in self.scopes() { match scope { - Scope::ExprScope(_) => continue, + Scope::Expr(_) => continue, Scope::GenericParams { params, def } => { if let Some(id) = params.find_type_by_name(first_name, *def) { return Some((TypeNs::GenericParam(id), remaining_idx())); } } - &Scope::ImplDefScope(impl_) => { + &Scope::ImplDef(impl_) => { if first_name == &name![Self] { return Some((TypeNs::SelfType(impl_), remaining_idx())); } } - &Scope::AdtScope(adt) => { + &Scope::Adt(adt) => { if first_name == &name![Self] { return Some((TypeNs::AdtSelfType(adt), remaining_idx())); } } - Scope::BlockScope(m) => { + Scope::Block(m) => { if let Some(res) = m.resolve_path_in_type_ns(db, path) { return Some(res); } @@ -253,8 +253,7 @@ impl Resolver { db: &dyn DefDatabase, visibility: &RawVisibility, ) -> Option { - let within_impl = - self.scopes().find(|scope| matches!(scope, Scope::ImplDefScope(_))).is_some(); + let within_impl = self.scopes().any(|scope| matches!(&scope, Scope::ImplDef(_))); match visibility { RawVisibility::Module(_) => { let (item_map, module) = self.item_scope(); @@ -296,7 +295,7 @@ impl Resolver { if n_segments <= 1 { for scope in self.scopes() { match scope { - Scope::ExprScope(scope) => { + Scope::Expr(scope) => { let entry = scope .expr_scopes .entries(scope.scope_id) @@ -315,14 +314,14 @@ impl Resolver { return Some(ResolveValueResult::ValueNs(val)); } } - &Scope::ImplDefScope(impl_) => { + &Scope::ImplDef(impl_) => { if first_name == &name![Self] { return Some(ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_))); } } // bare `Self` doesn't work in the value namespace in a struct/enum definition - Scope::AdtScope(_) => continue, - Scope::BlockScope(m) => { + Scope::Adt(_) => continue, + Scope::Block(m) => { if let Some(def) = m.resolve_path_in_value_ns(db, path) { return Some(def); } @@ -332,25 +331,25 @@ impl Resolver { } else { for scope in self.scopes() { match scope { - Scope::ExprScope(_) => continue, + Scope::Expr(_) => continue, Scope::GenericParams { params, def } => { if let Some(id) = params.find_type_by_name(first_name, *def) { let ty = TypeNs::GenericParam(id); return Some(ResolveValueResult::Partial(ty, 1)); } } - &Scope::ImplDefScope(impl_) => { + &Scope::ImplDef(impl_) => { if first_name == &name![Self] { return Some(ResolveValueResult::Partial(TypeNs::SelfType(impl_), 1)); } } - Scope::AdtScope(adt) => { + Scope::Adt(adt) => { if first_name == &name![Self] { let ty = TypeNs::AdtSelfType(*adt); return Some(ResolveValueResult::Partial(ty, 1)); } } - Scope::BlockScope(m) => { + Scope::Block(m) => { if let Some(def) = m.resolve_path_in_value_ns(db, path) { return Some(def); } @@ -486,8 +485,8 @@ impl Resolver { for scope in self.scopes() { match scope { - Scope::BlockScope(m) => traits.extend(m.def_map[m.module_id].scope.traits()), - &Scope::ImplDefScope(impl_) => { + Scope::Block(m) => traits.extend(m.def_map[m.module_id].scope.traits()), + &Scope::ImplDef(impl_) => { if let Some(target_trait) = &db.impl_data(impl_).target_trait { if let Some(TypeNs::TraitId(trait_)) = self.resolve_path_in_type_ns_fully(db, &target_trait.path) @@ -513,7 +512,7 @@ impl Resolver { pub fn traits_in_scope_from_block_scopes(&self) -> impl Iterator + '_ { self.scopes() .filter_map(|scope| match scope { - Scope::BlockScope(m) => Some(m.def_map[m.module_id].scope.traits()), + Scope::Block(m) => Some(m.def_map[m.module_id].scope.traits()), _ => None, }) .flatten() @@ -559,7 +558,7 @@ impl Resolver { pub fn body_owner(&self) -> Option { self.scopes().find_map(|scope| match scope { - Scope::ExprScope(it) => Some(it.owner), + Scope::Expr(it) => Some(it.owner), _ => None, }) } @@ -579,7 +578,7 @@ impl Resolver { expr_scopes: &Arc, scope_id: ScopeId, ) { - resolver.scopes.push(Scope::ExprScope(ExprScope { + resolver.scopes.push(Scope::Expr(ExprScope { owner, expr_scopes: expr_scopes.clone(), scope_id, @@ -588,7 +587,7 @@ impl Resolver { let def_map = db.block_def_map(block); resolver .scopes - .push(Scope::BlockScope(ModuleItemMap { def_map, module_id: DefMap::ROOT })); + .push(Scope::Block(ModuleItemMap { def_map, module_id: DefMap::ROOT })); // FIXME: This adds as many module scopes as there are blocks, but resolving in each // already traverses all parents, so this is O(n²). I think we could only store the // innermost module scope instead? @@ -598,7 +597,7 @@ impl Resolver { let start = self.scopes.len(); let innermost_scope = self.scopes().next(); match innermost_scope { - Some(&Scope::ExprScope(ExprScope { scope_id, ref expr_scopes, owner })) => { + Some(&Scope::Expr(ExprScope { scope_id, ref expr_scopes, owner })) => { let expr_scopes = expr_scopes.clone(); let scope_chain = expr_scopes .scope_chain(expr_scopes.scope_for(expr_id)) @@ -651,7 +650,7 @@ impl Resolver { fn item_scope(&self) -> (&DefMap, LocalModuleId) { self.scopes() .find_map(|scope| match scope { - Scope::BlockScope(m) => Some((&*m.def_map, m.module_id)), + Scope::Block(m) => Some((&*m.def_map, m.module_id)), _ => None, }) .unwrap_or((&self.module_scope.def_map, self.module_scope.module_id)) @@ -672,7 +671,7 @@ pub enum ScopeDef { impl Scope { fn process_names(&self, acc: &mut ScopeNames, db: &dyn DefDatabase) { match self { - Scope::BlockScope(m) => { + Scope::Block(m) => { m.def_map[m.module_id].scope.entries().for_each(|(name, def)| { acc.add_per_ns(name, def); }); @@ -706,13 +705,13 @@ impl Scope { acc.add(¶m.name, ScopeDef::GenericParam(id.into())) } } - Scope::ImplDefScope(i) => { + Scope::ImplDef(i) => { acc.add(&name![Self], ScopeDef::ImplSelfType(*i)); } - Scope::AdtScope(i) => { + Scope::Adt(i) => { acc.add(&name![Self], ScopeDef::AdtSelfType(*i)); } - Scope::ExprScope(scope) => { + Scope::Expr(scope) => { if let Some((label, name)) = scope.expr_scopes.label(scope.scope_id) { acc.add(&name, ScopeDef::Label(label)) } @@ -777,11 +776,11 @@ impl Resolver { } fn push_impl_def_scope(self, impl_def: ImplId) -> Resolver { - self.push_scope(Scope::ImplDefScope(impl_def)) + self.push_scope(Scope::ImplDef(impl_def)) } fn push_block_scope(self, def_map: Arc, module_id: LocalModuleId) -> Resolver { - self.push_scope(Scope::BlockScope(ModuleItemMap { def_map, module_id })) + self.push_scope(Scope::Block(ModuleItemMap { def_map, module_id })) } fn push_expr_scope( @@ -790,7 +789,7 @@ impl Resolver { expr_scopes: Arc, scope_id: ScopeId, ) -> Resolver { - self.push_scope(Scope::ExprScope(ExprScope { owner, expr_scopes, scope_id })) + self.push_scope(Scope::Expr(ExprScope { owner, expr_scopes, scope_id })) } } @@ -964,7 +963,7 @@ impl + Copy> HasResolver for T { def.module(db) .resolver(db) .push_generic_params_scope(db, def.into()) - .push_scope(Scope::AdtScope(def)) + .push_scope(Scope::Adt(def)) } } diff --git a/crates/hir-def/src/test_db.rs b/crates/hir-def/src/test_db.rs index a6befc8a81a8..b17ef3fe30d6 100644 --- a/crates/hir-def/src/test_db.rs +++ b/crates/hir-def/src/test_db.rs @@ -39,12 +39,14 @@ impl Default for TestDB { } } +#[allow(clippy::borrow_deref_ref)] // false positive impl Upcast for TestDB { fn upcast(&self) -> &(dyn ExpandDatabase + 'static) { &*self } } +#[allow(clippy::borrow_deref_ref)] // false positive impl Upcast for TestDB { fn upcast(&self) -> &(dyn DefDatabase + 'static) { &*self diff --git a/crates/hir-expand/src/attrs.rs b/crates/hir-expand/src/attrs.rs index 4c918e55b92a..70afdf4fcea2 100644 --- a/crates/hir-expand/src/attrs.rs +++ b/crates/hir-expand/src/attrs.rs @@ -30,7 +30,7 @@ impl ops::Deref for RawAttrs { fn deref(&self) -> &[Attr] { match &self.entries { - Some(it) => &*it, + Some(it) => it, None => &[], } } @@ -76,7 +76,7 @@ impl RawAttrs { .cloned() .chain(b.iter().map(|it| { let mut it = it.clone(); - it.id.id = it.id.ast_index() as u32 + last_ast_index + it.id.id = (it.id.ast_index() as u32 + last_ast_index) | (it.id.cfg_attr_index().unwrap_or(0) as u32) << AttrId::AST_INDEX_BITS; it @@ -293,7 +293,7 @@ impl Attr { // FIXME: This is necessarily a hack. It'd be nice if we could avoid allocation here. let subtree = tt::Subtree { delimiter: tt::Delimiter::unspecified(), - token_trees: tts.into_iter().cloned().collect(), + token_trees: tts.to_vec(), }; let (parse, _) = mbe::token_tree_to_syntax_node(&subtree, mbe::TopEntryPoint::MetaItem); diff --git a/crates/hir-expand/src/builtin_fn_macro.rs b/crates/hir-expand/src/builtin_fn_macro.rs index a9f0c154b02b..93c44395a64f 100644 --- a/crates/hir-expand/src/builtin_fn_macro.rs +++ b/crates/hir-expand/src/builtin_fn_macro.rs @@ -326,7 +326,7 @@ fn format_args_expand_general( '}' => "".to_owned(), ':' => { let mut s = String::new(); - while let Some(c) = format_iter.next() { + for c in format_iter.by_ref() { if c == '}' { break; } diff --git a/crates/hir-expand/src/quote.rs b/crates/hir-expand/src/quote.rs index ab3809abc7a2..d351c47c9cff 100644 --- a/crates/hir-expand/src/quote.rs +++ b/crates/hir-expand/src/quote.rs @@ -9,17 +9,17 @@ #[macro_export] macro_rules! __quote { () => { - Vec::::new() + Vec::<$crate::tt::TokenTree>::new() }; ( @SUBTREE $delim:ident $($tt:tt)* ) => { { let children = $crate::__quote!($($tt)*); - crate::tt::Subtree { - delimiter: crate::tt::Delimiter { - kind: crate::tt::DelimiterKind::$delim, - open: crate::tt::TokenId::unspecified(), - close: crate::tt::TokenId::unspecified(), + $crate::tt::Subtree { + delimiter: $crate::tt::Delimiter { + kind: $crate::tt::DelimiterKind::$delim, + open: $crate::tt::TokenId::unspecified(), + close: $crate::tt::TokenId::unspecified(), }, token_trees: $crate::quote::IntoTt::to_tokens(children), } @@ -29,10 +29,10 @@ macro_rules! __quote { ( @PUNCT $first:literal ) => { { vec![ - crate::tt::Leaf::Punct(crate::tt::Punct { + $crate::tt::Leaf::Punct($crate::tt::Punct { char: $first, - spacing: crate::tt::Spacing::Alone, - span: crate::tt::TokenId::unspecified(), + spacing: $crate::tt::Spacing::Alone, + span: $crate::tt::TokenId::unspecified(), }).into() ] } @@ -41,15 +41,15 @@ macro_rules! __quote { ( @PUNCT $first:literal, $sec:literal ) => { { vec![ - crate::tt::Leaf::Punct(crate::tt::Punct { + $crate::tt::Leaf::Punct($crate::tt::Punct { char: $first, - spacing: crate::tt::Spacing::Joint, - span: crate::tt::TokenId::unspecified(), + spacing: $crate::tt::Spacing::Joint, + span: $crate::tt::TokenId::unspecified(), }).into(), - crate::tt::Leaf::Punct(crate::tt::Punct { + $crate::tt::Leaf::Punct($crate::tt::Punct { char: $sec, - spacing: crate::tt::Spacing::Alone, - span: crate::tt::TokenId::unspecified(), + spacing: $crate::tt::Spacing::Alone, + span: $crate::tt::TokenId::unspecified(), }).into() ] } @@ -68,7 +68,7 @@ macro_rules! __quote { ( ## $first:ident $($tail:tt)* ) => { { - let mut tokens = $first.into_iter().map($crate::quote::ToTokenTree::to_token).collect::>(); + let mut tokens = $first.into_iter().map($crate::quote::ToTokenTree::to_token).collect::>(); let mut tail_tokens = $crate::quote::IntoTt::to_tokens($crate::__quote!($($tail)*)); tokens.append(&mut tail_tokens); tokens @@ -87,9 +87,9 @@ macro_rules! __quote { // Ident ( $tt:ident ) => { vec![ { - crate::tt::Leaf::Ident(crate::tt::Ident { + $crate::tt::Leaf::Ident($crate::tt::Ident { text: stringify!($tt).into(), - span: crate::tt::TokenId::unspecified(), + span: $crate::tt::TokenId::unspecified(), }).into() }] }; diff --git a/crates/hir-ty/src/chalk_db.rs b/crates/hir-ty/src/chalk_db.rs index ac962c9e3e1f..1e8253794ca3 100644 --- a/crates/hir-ty/src/chalk_db.rs +++ b/crates/hir-ty/src/chalk_db.rs @@ -200,7 +200,7 @@ impl<'a> chalk_solve::RustIrDatabase for ChalkContext<'a> { well_known_trait: rust_ir::WellKnownTrait, ) -> Option> { let lang_attr = lang_item_from_well_known_trait(well_known_trait); - let trait_ = match self.db.lang_item(self.krate, lang_attr.into()) { + let trait_ = match self.db.lang_item(self.krate, lang_attr) { Some(LangItemTarget::Trait(trait_)) => trait_, _ => return None, }; diff --git a/crates/hir-ty/src/chalk_ext.rs b/crates/hir-ty/src/chalk_ext.rs index a8071591adac..d89f7c5b8332 100644 --- a/crates/hir-ty/src/chalk_ext.rs +++ b/crates/hir-ty/src/chalk_ext.rs @@ -50,7 +50,7 @@ pub trait TyExt { fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option>; fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option; - fn is_copy(self, db: &dyn HirDatabase, owner: DefWithBodyId) -> bool; + fn implements_copy(self, db: &dyn HirDatabase, owner: DefWithBodyId) -> bool; /// FIXME: Get rid of this, it's not a good abstraction fn equals_ctor(&self, other: &Ty) -> bool; @@ -341,7 +341,7 @@ impl TyExt for Ty { } } - fn is_copy(self, db: &dyn HirDatabase, owner: DefWithBodyId) -> bool { + fn implements_copy(self, db: &dyn HirDatabase, owner: DefWithBodyId) -> bool { let crate_id = owner.module(db.upcast()).krate(); let Some(copy_trait) = db.lang_item(crate_id, LangItem::Copy).and_then(|x| x.as_trait()) else { return false; diff --git a/crates/hir-ty/src/consteval.rs b/crates/hir-ty/src/consteval.rs index 40b63b17b5aa..849122f80947 100644 --- a/crates/hir-ty/src/consteval.rs +++ b/crates/hir-ty/src/consteval.rs @@ -166,7 +166,7 @@ pub fn try_const_usize(db: &dyn HirDatabase, c: &Const) -> Option { chalk_ir::ConstValue::InferenceVar(_) => None, chalk_ir::ConstValue::Placeholder(_) => None, chalk_ir::ConstValue::Concrete(c) => match &c.interned { - ConstScalar::Bytes(x, _) => Some(u128::from_le_bytes(pad16(&x, false))), + ConstScalar::Bytes(x, _) => Some(u128::from_le_bytes(pad16(x, false))), ConstScalar::UnevaluatedConst(c, subst) => { let ec = db.const_eval(*c, subst.clone()).ok()?; try_const_usize(db, &ec) @@ -286,7 +286,7 @@ pub(crate) fn eval_to_const( } } let infer = ctx.clone().resolve_all(); - if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, &ctx.body, &infer, expr) { + if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, ctx.body, &infer, expr) { if let Ok(result) = interpret_mir(db, &mir_body, true).0 { return result; } diff --git a/crates/hir-ty/src/diagnostics/decl_check.rs b/crates/hir-ty/src/diagnostics/decl_check.rs index 1233469b947b..0a4e9a9e7575 100644 --- a/crates/hir-ty/src/diagnostics/decl_check.rs +++ b/crates/hir-ty/src/diagnostics/decl_check.rs @@ -55,6 +55,7 @@ pub fn incorrect_case( validator.sink } +#[allow(clippy::enum_variant_names)] #[derive(Debug)] pub enum CaseType { // `some_var` diff --git a/crates/hir-ty/src/diagnostics/expr.rs b/crates/hir-ty/src/diagnostics/expr.rs index ab34dc88d87b..9590991c5659 100644 --- a/crates/hir-ty/src/diagnostics/expr.rs +++ b/crates/hir-ty/src/diagnostics/expr.rs @@ -120,29 +120,24 @@ impl ExprValidator { return; } - match expr { - Expr::MethodCall { receiver, .. } => { - let (callee, _) = match self.infer.method_resolution(call_id) { - Some(it) => it, - None => return, - }; - - if filter_map_next_checker - .get_or_insert_with(|| { - FilterMapNextChecker::new(&self.owner.resolver(db.upcast()), db) - }) - .check(call_id, receiver, &callee) - .is_some() - { - self.diagnostics.push( - BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { - method_call_expr: call_id, - }, - ); - } + if let Expr::MethodCall { receiver, .. } = expr { + let (callee, _) = match self.infer.method_resolution(call_id) { + Some(it) => it, + None => return, + }; + + if filter_map_next_checker + .get_or_insert_with(|| { + FilterMapNextChecker::new(&self.owner.resolver(db.upcast()), db) + }) + .check(call_id, receiver, &callee) + .is_some() + { + self.diagnostics.push(BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { + method_call_expr: call_id, + }); } - _ => return, - }; + } } fn validate_match( diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index c1df24d17291..0c580faa59f1 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -89,7 +89,7 @@ pub trait HirDisplay { fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError>; /// Returns a `Display`able type that is human-readable. - fn into_displayable<'a>( + fn as_displayable<'a>( &'a self, db: &'a dyn HirDatabase, max_size: Option, @@ -434,7 +434,7 @@ impl HirDisplay for Const { Ok(()) } ConstValue::Concrete(c) => match &c.interned { - ConstScalar::Bytes(b, m) => render_const_scalar(f, &b, m, &data.ty), + ConstScalar::Bytes(b, m) => render_const_scalar(f, b, m, &data.ty), ConstScalar::UnevaluatedConst(c, parameters) => { write!(f, "{}", c.name(f.db.upcast()))?; hir_fmt_generics(f, parameters, c.generic_def(f.db.upcast()))?; @@ -457,7 +457,7 @@ impl HirDisplay for HexifiedConst { if let ConstScalar::Bytes(b, m) = &c.interned { let value = u128::from_le_bytes(pad16(b, false)); if value >= 10 { - render_const_scalar(f, &b, m, &data.ty)?; + render_const_scalar(f, b, m, &data.ty)?; return write!(f, " ({:#X})", value); } } @@ -479,7 +479,7 @@ fn render_const_scalar( let krate = *f.db.crate_graph().crates_in_topological_order().last().unwrap(); match ty.kind(Interner) { TyKind::Scalar(s) => match s { - Scalar::Bool => write!(f, "{}", if b[0] == 0 { false } else { true }), + Scalar::Bool => write!(f, "{}", b[0] != 0), Scalar::Char => { let x = u128::from_le_bytes(pad16(b, false)) as u32; let Ok(c) = char::try_from(x) else { @@ -513,7 +513,7 @@ fn render_const_scalar( let Some(bytes) = memory_map.get(addr, size) else { return f.write_str(""); }; - let s = std::str::from_utf8(&bytes).unwrap_or(""); + let s = std::str::from_utf8(bytes).unwrap_or(""); write!(f, "{s:?}") } TyKind::Slice(ty) => { @@ -535,7 +535,7 @@ fn render_const_scalar( f.write_str(", ")?; } let offset = size_one * i; - render_const_scalar(f, &bytes[offset..offset + size_one], memory_map, &ty)?; + render_const_scalar(f, &bytes[offset..offset + size_one], memory_map, ty)?; } f.write_str("]") } @@ -607,7 +607,7 @@ fn render_const_scalar( continue; }; let size = layout.size.bytes_usize(); - render_const_scalar(f, &b[offset..offset + size], memory_map, &ty)?; + render_const_scalar(f, &b[offset..offset + size], memory_map, ty)?; } f.write_str(")") } @@ -648,7 +648,7 @@ fn render_const_scalar( f, &field_types, adt.0.module(f.db.upcast()).krate(), - &var_layout, + var_layout, subst, b, memory_map, @@ -679,7 +679,7 @@ fn render_const_scalar( f.write_str(", ")?; } let offset = size_one * i; - render_const_scalar(f, &b[offset..offset + size_one], memory_map, &ty)?; + render_const_scalar(f, &b[offset..offset + size_one], memory_map, ty)?; } f.write_str("]") } @@ -746,7 +746,7 @@ fn render_variant_after_name( } write!(f, ")")?; } - return Ok(()); + Ok(()) } VariantData::Unit => Ok(()), } @@ -892,7 +892,7 @@ impl HirDisplay for Ty { write!(f, ",)")?; } else { write!(f, "(")?; - f.write_joined(&*substs.as_slice(Interner), ", ")?; + f.write_joined(substs.as_slice(Interner), ", ")?; write!(f, ")")?; } } @@ -1056,7 +1056,7 @@ impl HirDisplay for Ty { f.start_location_link(t.into()); } write!(f, "Future")?; - if let Some(_) = future_trait { + if future_trait.is_some() { f.end_location_link(); } write!(f, "<")?; @@ -1064,7 +1064,7 @@ impl HirDisplay for Ty { f.start_location_link(t.into()); } write!(f, "Output")?; - if let Some(_) = output { + if output.is_some() { f.end_location_link(); } write!(f, " = ")?; @@ -1232,8 +1232,7 @@ impl HirDisplay for Ty { let subst = subst.as_slice(Interner); let a: Option> = subst .get(subst.len() - 3..) - .map(|args| args.iter().map(|arg| arg.ty(Interner)).collect()) - .flatten(); + .and_then(|args| args.iter().map(|arg| arg.ty(Interner)).collect()); if let Some([resume_ty, yield_ty, ret_ty]) = a.as_deref() { write!(f, "|")?; @@ -1443,7 +1442,7 @@ fn write_bounds_like_dyn_trait( f.start_location_link(trait_.into()); write!(f, "{}", f.db.trait_data(trait_).name.display(f.db.upcast()))?; f.end_location_link(); - if let [_, params @ ..] = &*trait_ref.substitution.as_slice(Interner) { + if let [_, params @ ..] = trait_ref.substitution.as_slice(Interner) { if is_fn_trait { if let Some(args) = params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple()) @@ -1523,7 +1522,7 @@ fn write_bounds_like_dyn_trait( } write!(f, "Sized")?; } - if let Some(_) = sized_trait { + if sized_trait.is_some() { f.end_location_link(); } } diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs index 80f32e96ee63..a0844658df6f 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -136,8 +136,9 @@ pub(crate) fn normalize(db: &dyn HirDatabase, trait_env: Arc, /// Binding modes inferred for patterns. /// -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)] pub enum BindingMode { + #[default] Move, Ref(Mutability), } @@ -152,12 +153,6 @@ impl BindingMode { } } -impl Default for BindingMode { - fn default() -> Self { - BindingMode::Move - } -} - #[derive(Debug)] pub(crate) struct InferOk { value: T, @@ -522,10 +517,10 @@ enum BreakableKind { Border, } -fn find_breakable<'c>( - ctxs: &'c mut [BreakableContext], +fn find_breakable( + ctxs: &mut [BreakableContext], label: Option, -) -> Option<&'c mut BreakableContext> { +) -> Option<&mut BreakableContext> { let mut ctxs = ctxs .iter_mut() .rev() @@ -536,10 +531,10 @@ fn find_breakable<'c>( } } -fn find_continuable<'c>( - ctxs: &'c mut [BreakableContext], +fn find_continuable( + ctxs: &mut [BreakableContext], label: Option, -) -> Option<&'c mut BreakableContext> { +) -> Option<&mut BreakableContext> { match label { Some(_) => find_breakable(ctxs, label).filter(|it| matches!(it.kind, BreakableKind::Loop)), None => find_breakable(ctxs, label), @@ -754,8 +749,8 @@ impl<'a> InferenceContext<'a> { ImplTraitId::ReturnTypeImplTrait(_, idx) => idx, _ => unreachable!(), }; - let bounds = (*rpits) - .map_ref(|rpits| rpits.impl_traits[idx].bounds.map_ref(|it| it.into_iter())); + let bounds = + (*rpits).map_ref(|rpits| rpits.impl_traits[idx].bounds.map_ref(|it| it.iter())); let var = self.table.new_type_var(); let var_subst = Substitution::from1(Interner, var.clone()); for bound in bounds { diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index 23189f383e0e..5da759dbdcee 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -129,7 +129,7 @@ impl HirPlace { ctx.owner.module(ctx.db.upcast()).krate(), ); } - ty.clone() + ty } fn capture_kind_of_truncated_place( @@ -137,13 +137,10 @@ impl HirPlace { mut current_capture: CaptureKind, len: usize, ) -> CaptureKind { - match current_capture { - CaptureKind::ByRef(BorrowKind::Mut { .. }) => { - if self.projections[len..].iter().any(|x| *x == ProjectionElem::Deref) { - current_capture = CaptureKind::ByRef(BorrowKind::Unique); - } + if let CaptureKind::ByRef(BorrowKind::Mut { .. }) = current_capture { + if self.projections[len..].iter().any(|x| *x == ProjectionElem::Deref) { + current_capture = CaptureKind::ByRef(BorrowKind::Unique); } - _ => (), } current_capture } @@ -236,7 +233,7 @@ pub(crate) struct CapturedItemWithoutTy { impl CapturedItemWithoutTy { fn with_ty(self, ctx: &mut InferenceContext<'_>) -> CapturedItem { - let ty = self.place.ty(ctx).clone(); + let ty = self.place.ty(ctx); let ty = match &self.kind { CaptureKind::ByValue => ty, CaptureKind::ByRef(bk) => { @@ -321,12 +318,10 @@ impl InferenceContext<'_> { match &self.body[tgt_expr] { Expr::Path(p) => { let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); - if let Some(r) = resolver.resolve_path_in_value_ns(self.db.upcast(), p) { - if let ResolveValueResult::ValueNs(v) = r { - if let ValueNs::LocalBinding(b) = v { - return Some(HirPlace { local: b, projections: vec![] }); - } - } + if let Some(ResolveValueResult::ValueNs(ValueNs::LocalBinding(b))) = + resolver.resolve_path_in_value_ns(self.db.upcast(), p) + { + return Some(HirPlace { local: b, projections: vec![] }); } } Expr::Field { expr, name } => { @@ -392,7 +387,7 @@ impl InferenceContext<'_> { fn consume_place(&mut self, place: HirPlace, span: MirSpan) { if self.is_upvar(&place) { - let ty = place.ty(self).clone(); + let ty = place.ty(self); let kind = if self.is_ty_copy(ty) { CaptureKind::ByRef(BorrowKind::Shared) } else { @@ -730,7 +725,7 @@ impl InferenceContext<'_> { // without creating query cycles. return self.result.closure_info.get(id).map(|x| x.1 == FnTrait::Fn).unwrap_or(true); } - self.table.resolve_completely(ty).is_copy(self.db, self.owner) + self.table.resolve_completely(ty).implements_copy(self.db, self.owner) } fn select_from_expr(&mut self, expr: ExprId) { @@ -787,8 +782,7 @@ impl InferenceContext<'_> { .iter() .cloned() .chain((0..cnt).map(|_| ProjectionElem::Deref)) - .collect::>() - .into(); + .collect::>(); match &self.body[pat] { Pat::Missing | Pat::Wild => (), Pat::Tuple { args, ellipsis } => { @@ -826,10 +820,8 @@ impl InferenceContext<'_> { continue; }; let mut p = place.clone(); - p.projections.push(ProjectionElem::Field(FieldId { - parent: variant.into(), - local_id, - })); + p.projections + .push(ProjectionElem::Field(FieldId { parent: variant, local_id })); self.consume_with_pat(p, arg); } } @@ -871,7 +863,7 @@ impl InferenceContext<'_> { for (arg, (i, _)) in it { let mut p = place.clone(); p.projections.push(ProjectionElem::Field(FieldId { - parent: variant.into(), + parent: variant, local_id: i, })); self.consume_with_pat(p, *arg); @@ -975,11 +967,11 @@ impl InferenceContext<'_> { let mut deferred_closures = mem::take(&mut self.deferred_closures); let mut dependents_count: FxHashMap = deferred_closures.keys().map(|x| (*x, 0)).collect(); - for (_, deps) in &self.closure_dependencies { + self.closure_dependencies.iter().for_each(|(_, deps)| { for dep in deps { *dependents_count.entry(*dep).or_default() += 1; } - } + }); let mut queue: Vec<_> = deferred_closures.keys().copied().filter(|x| dependents_count[x] == 0).collect(); let mut result = vec![]; diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index 33e98ac86cf6..3acfd323b2f1 100644 --- a/crates/hir-ty/src/infer/expr.rs +++ b/crates/hir-ty/src/infer/expr.rs @@ -290,7 +290,7 @@ impl<'a> InferenceContext<'a> { // Now go through the argument patterns for (arg_pat, arg_ty) in args.iter().zip(&sig_tys) { - self.infer_top_pat(*arg_pat, &arg_ty); + self.infer_top_pat(*arg_pat, arg_ty); } // FIXME: lift these out into a struct @@ -449,7 +449,7 @@ impl<'a> InferenceContext<'a> { ty } &Expr::Continue { label } => { - if let None = find_continuable(&mut self.breakables, label) { + if find_continuable(&mut self.breakables, label).is_none() { self.push_diagnostic(InferenceDiagnostic::BreakOutsideOfLoop { expr: tgt_expr, is_break: false, @@ -919,7 +919,7 @@ impl<'a> InferenceContext<'a> { derefed_callee: &Ty, adjustments: &mut Vec, callee_ty: &Ty, - params: &Vec, + params: &[Ty], tgt_expr: ExprId, ) { match fn_x { @@ -955,7 +955,7 @@ impl<'a> InferenceContext<'a> { .push(callee_ty.clone()) .push(TyBuilder::tuple_with(params.iter().cloned())) .build(); - self.write_method_resolution(tgt_expr, func, subst.clone()); + self.write_method_resolution(tgt_expr, func, subst); } } @@ -1058,8 +1058,7 @@ impl<'a> InferenceContext<'a> { let inner_exp = expected .to_option(table) .as_ref() - .map(|e| e.as_adt()) - .flatten() + .and_then(|e| e.as_adt()) .filter(|(e_adt, _)| e_adt == &box_id) .map(|(_, subts)| { let g = subts.at(Interner, 0); @@ -1297,7 +1296,7 @@ impl<'a> InferenceContext<'a> { .unwrap_or_else(|| this.table.new_type_var()); let ty = if let Some(expr) = initializer { - let ty = if contains_explicit_ref_binding(&this.body, *pat) { + let ty = if contains_explicit_ref_binding(this.body, *pat) { this.infer_expr(*expr, &Expectation::has_type(decl_ty.clone())) } else { this.infer_expr_coerce( @@ -1629,7 +1628,7 @@ impl<'a> InferenceContext<'a> { // that we have more information about the types of arguments when we // type-check the functions. This isn't really the right way to do this. for check_closures in [false, true] { - let mut skip_indices = skip_indices.into_iter().copied().fuse().peekable(); + let mut skip_indices = skip_indices.iter().copied().fuse().peekable(); let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty())); let expected_iter = expected_inputs .iter() diff --git a/crates/hir-ty/src/infer/pat.rs b/crates/hir-ty/src/infer/pat.rs index 2480f8babac4..771a05f98206 100644 --- a/crates/hir-ty/src/infer/pat.rs +++ b/crates/hir-ty/src/infer/pat.rs @@ -149,13 +149,13 @@ impl<'a> InferenceContext<'a> { ) -> Ty { let expected = self.resolve_ty_shallow(expected); let expectations = match expected.as_tuple() { - Some(parameters) => &*parameters.as_slice(Interner), + Some(parameters) => parameters.as_slice(Interner), _ => &[], }; let ((pre, post), n_uncovered_patterns) = match ellipsis { Some(idx) => (subs.split_at(idx), expectations.len().saturating_sub(subs.len())), - None => ((&subs[..], &[][..]), 0), + None => ((subs, &[][..]), 0), }; let mut expectations_iter = expectations .iter() @@ -262,7 +262,7 @@ impl<'a> InferenceContext<'a> { &Pat::Lit(expr) => { // Don't emit type mismatches again, the expression lowering already did that. let ty = self.infer_lit_pat(expr, &expected); - self.write_pat_ty(pat, ty.clone()); + self.write_pat_ty(pat, ty); return self.pat_ty_after_adjustment(pat); } Pat::Box { inner } => match self.resolve_boxed_box() { @@ -350,7 +350,7 @@ impl<'a> InferenceContext<'a> { self.result.binding_modes.insert(binding, mode); let inner_ty = match subpat { - Some(subpat) => self.infer_pat(subpat, &expected, default_bm), + Some(subpat) => self.infer_pat(subpat, expected, default_bm), None => expected.clone(), }; let inner_ty = self.insert_type_vars_shallow(inner_ty); @@ -363,7 +363,7 @@ impl<'a> InferenceContext<'a> { }; self.write_pat_ty(pat, inner_ty.clone()); self.write_binding_ty(binding, bound_ty); - return inner_ty; + inner_ty } fn infer_slice_pat( diff --git a/crates/hir-ty/src/infer/path.rs b/crates/hir-ty/src/infer/path.rs index 95a20f983f1b..c5b78e93304b 100644 --- a/crates/hir-ty/src/infer/path.rs +++ b/crates/hir-ty/src/infer/path.rs @@ -351,7 +351,7 @@ impl InferenceContext<'_> { name: &Name, id: ExprOrPatId, ) -> Option<(ValueNs, Substitution)> { - let ty = self.resolve_ty_shallow(&ty); + let ty = self.resolve_ty_shallow(ty); let (enum_id, subst) = match ty.as_adt() { Some((AdtId::EnumId(e), subst)) => (e, subst), _ => return None, diff --git a/crates/hir-ty/src/infer/unify.rs b/crates/hir-ty/src/infer/unify.rs index e33d8f1795e2..115af408a525 100644 --- a/crates/hir-ty/src/infer/unify.rs +++ b/crates/hir-ty/src/infer/unify.rs @@ -252,8 +252,7 @@ impl<'a> InferenceTable<'a> { // and registering an obligation. But it needs chalk support, so we handle the most basic // case (a non associated const without generic parameters) manually. if subst.len(Interner) == 0 { - if let Ok(eval) = self.db.const_eval((*c_id).into(), subst.clone()) - { + if let Ok(eval) = self.db.const_eval(*c_id, subst.clone()) { eval } else { unknown_const(c.data(Interner).ty.clone()) @@ -491,9 +490,8 @@ impl<'a> InferenceTable<'a> { pub(crate) fn try_obligation(&mut self, goal: Goal) -> Option { let in_env = InEnvironment::new(&self.trait_env.env, goal); let canonicalized = self.canonicalize(in_env); - let solution = - self.db.trait_solve(self.trait_env.krate, self.trait_env.block, canonicalized.value); - solution + + self.db.trait_solve(self.trait_env.krate, self.trait_env.block, canonicalized.value) } pub(crate) fn register_obligation(&mut self, goal: Goal) { diff --git a/crates/hir-ty/src/inhabitedness.rs b/crates/hir-ty/src/inhabitedness.rs index e5038543b68e..ff5586d63faf 100644 --- a/crates/hir-ty/src/inhabitedness.rs +++ b/crates/hir-ty/src/inhabitedness.rs @@ -86,8 +86,7 @@ impl TypeVisitor for UninhabitedFrom<'_> { Some(0) | None => CONTINUE_OPAQUELY_INHABITED, Some(1..) => item_ty.super_visit_with(self, outer_binder), }, - - TyKind::Ref(..) | _ => CONTINUE_OPAQUELY_INHABITED, + _ => CONTINUE_OPAQUELY_INHABITED, }; self.recursive_ty.remove(ty); self.max_depth += 1; diff --git a/crates/hir-ty/src/interner.rs b/crates/hir-ty/src/interner.rs index 89f7d9c4f4ab..58d5ed5559cc 100644 --- a/crates/hir-ty/src/interner.rs +++ b/crates/hir-ty/src/interner.rs @@ -415,7 +415,7 @@ impl chalk_ir::interner::HasInterner for Interner { macro_rules! has_interner { ($t:ty) => { impl HasInterner for $t { - type Interner = crate::Interner; + type Interner = $crate::Interner; } }; } diff --git a/crates/hir-ty/src/layout.rs b/crates/hir-ty/src/layout.rs index 35d3407c16c1..d2413280790b 100644 --- a/crates/hir-ty/src/layout.rs +++ b/crates/hir-ty/src/layout.rs @@ -84,9 +84,9 @@ pub fn layout_of_ty_query( ) -> Result, LayoutError> { let Some(target) = db.target_data_layout(krate) else { return Err(LayoutError::TargetLayoutNotAvailable) }; let cx = LayoutCx { krate, target: &target }; - let dl = &*cx.current_data_layout(); + let dl = cx.current_data_layout(); let trait_env = Arc::new(TraitEnvironment::empty(krate)); - let ty = normalize(db, trait_env, ty.clone()); + let ty = normalize(db, trait_env, ty); let result = match ty.kind(Interner) { TyKind::Adt(AdtId(def), subst) => return db.layout_of_adt(*def, subst.clone(), krate), TyKind::Scalar(s) => match s { @@ -152,7 +152,7 @@ pub fn layout_of_ty_query( cx.univariant(dl, &fields, &ReprOptions::default(), kind).ok_or(LayoutError::Unknown)? } TyKind::Array(element, count) => { - let count = try_const_usize(db, &count).ok_or(LayoutError::UserError( + let count = try_const_usize(db, count).ok_or(LayoutError::UserError( "unevaluated or mistyped const generic parameter".to_string(), ))? as u64; let element = db.layout_of_ty(element.clone(), krate)?; diff --git a/crates/hir-ty/src/layout/adt.rs b/crates/hir-ty/src/layout/adt.rs index bd2752a7119a..c2e2a4244147 100644 --- a/crates/hir-ty/src/layout/adt.rs +++ b/crates/hir-ty/src/layout/adt.rs @@ -82,7 +82,7 @@ pub fn layout_of_adt_query( matches!(def, AdtId::EnumId(..)), is_unsafe_cell(db, def), layout_scalar_valid_range(db, def), - |min, max| repr_discr(&dl, &repr, min, max).unwrap_or((Integer::I8, false)), + |min, max| repr_discr(dl, &repr, min, max).unwrap_or((Integer::I8, false)), variants.iter_enumerated().filter_map(|(id, _)| { let AdtId::EnumId(e) = def else { return None }; let d = diff --git a/crates/hir-ty/src/layout/target.rs b/crates/hir-ty/src/layout/target.rs index 04b940afbe8f..b2185a03ea2d 100644 --- a/crates/hir-ty/src/layout/target.rs +++ b/crates/hir-ty/src/layout/target.rs @@ -12,7 +12,7 @@ pub fn target_data_layout_query( ) -> Option> { let crate_graph = db.crate_graph(); let target_layout = crate_graph[krate].target_layout.as_ref().ok()?; - let res = TargetDataLayout::parse_from_llvm_datalayout_string(&target_layout); + let res = TargetDataLayout::parse_from_llvm_datalayout_string(target_layout); if let Err(_e) = &res { // FIXME: Print the error here once it implements debug/display // also logging here is somewhat wrong, but unfortunately this is the earliest place we can diff --git a/crates/hir-ty/src/layout/tests.rs b/crates/hir-ty/src/layout/tests.rs index fca2e09ff0a9..b26dce15c61e 100644 --- a/crates/hir-ty/src/layout/tests.rs +++ b/crates/hir-ty/src/layout/tests.rs @@ -1,3 +1,5 @@ +#![allow(clippy::useless_attribute)] + use std::collections::HashMap; use base_db::fixture::WithFixture; @@ -307,11 +309,11 @@ fn return_position_impl_trait() { } let waker = Arc::new(EmptyWaker).into(); let mut context = Context::from_waker(&waker); - let x = pinned.poll(&mut context); - x + + pinned.poll(&mut context) } - let x = unwrap_fut(f()); - x + + unwrap_fut(f()) } size_and_align_expr! { struct Foo(T, T, (T, T)); diff --git a/crates/hir-ty/src/layout/tests/closure.rs b/crates/hir-ty/src/layout/tests/closure.rs index 576e7f3fc619..f35a65a4cc14 100644 --- a/crates/hir-ty/src/layout/tests/closure.rs +++ b/crates/hir-ty/src/layout/tests/closure.rs @@ -1,3 +1,4 @@ +#![allow(clippy::all)] use crate::size_and_align_expr; #[test] diff --git a/crates/hir-ty/src/lib.rs b/crates/hir-ty/src/lib.rs index 1a4d003bf5e9..0f9d5880dbef 100644 --- a/crates/hir-ty/src/lib.rs +++ b/crates/hir-ty/src/lib.rs @@ -185,7 +185,7 @@ impl MemoryMap { self.memory.iter().map(|x| Ok((*x.0, f(x.1)?))).collect() } - fn get<'a>(&'a self, addr: usize, size: usize) -> Option<&'a [u8]> { + fn get(&self, addr: usize, size: usize) -> Option<&[u8]> { if size == 0 { Some(&[]) } else { diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index 0c68891fe493..65d755d73073 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -1316,7 +1316,7 @@ fn named_associated_type_shorthand_candidates( ), _ => None, }); - if let Some(_) = res { + if res.is_some() { return res; } // Handle `Self::Type` referring to own associated type in trait definitions diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index 6fa3d1351a91..60f44ba785ff 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -563,7 +563,7 @@ impl ReceiverAdjustments { if let TyKind::Ref(m, l, inner) = ty.kind(Interner) { if let TyKind::Array(inner, _) = inner.kind(Interner) { break 'x TyKind::Ref( - m.clone(), + *m, l.clone(), TyKind::Slice(inner.clone()).intern(Interner), ) @@ -911,7 +911,7 @@ pub fn iterate_method_candidates_dyn( let ty = table.instantiate_canonical(ty.clone()); let deref_chain = autoderef_method_receiver(&mut table, ty); - let result = deref_chain.into_iter().try_for_each(|(receiver_ty, adj)| { + deref_chain.into_iter().try_for_each(|(receiver_ty, adj)| { iterate_method_candidates_with_autoref( &receiver_ty, adj, @@ -922,8 +922,7 @@ pub fn iterate_method_candidates_dyn( name, callback, ) - }); - result + }) } LookupMode::Path => { // No autoderef for path lookups @@ -1288,7 +1287,7 @@ pub(crate) fn resolve_indexing_op( ty: Canonical, index_trait: TraitId, ) -> Option { - let mut table = InferenceTable::new(db, env.clone()); + let mut table = InferenceTable::new(db, env); let ty = table.instantiate_canonical(ty); let deref_chain = autoderef_method_receiver(&mut table, ty); for (ty, adj) in deref_chain { diff --git a/crates/hir-ty/src/mir.rs b/crates/hir-ty/src/mir.rs index 2345bab0bb4d..13d660485009 100644 --- a/crates/hir-ty/src/mir.rs +++ b/crates/hir-ty/src/mir.rs @@ -142,7 +142,7 @@ impl ProjectionElem { } _ => { never!("Overloaded deref on type {} is not a projection", base.display(db)); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } }, ProjectionElem::Field(f) => match &base.data(Interner).kind { @@ -151,7 +151,7 @@ impl ProjectionElem { } _ => { never!("Only adt has field"); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } }, ProjectionElem::TupleOrClosureField(f) => match &base.data(Interner).kind { @@ -167,7 +167,7 @@ impl ProjectionElem { TyKind::Closure(id, subst) => closure_field(*id, subst, *f), _ => { never!("Only tuple or closure has tuple or closure field"); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } }, ProjectionElem::ConstantIndex { .. } | ProjectionElem::Index(_) => { @@ -175,7 +175,7 @@ impl ProjectionElem { TyKind::Array(inner, _) | TyKind::Slice(inner) => inner.clone(), _ => { never!("Overloaded index is not a projection"); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } } } @@ -194,12 +194,12 @@ impl ProjectionElem { TyKind::Slice(_) => base.clone(), _ => { never!("Subslice projection should only happen on slice and array"); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } }, ProjectionElem::OpaqueCast(_) => { never!("We don't emit these yet"); - return TyKind::Error.intern(Interner); + TyKind::Error.intern(Interner) } } } diff --git a/crates/hir-ty/src/mir/borrowck.rs b/crates/hir-ty/src/mir/borrowck.rs index a0ea1cc5ef7d..9ee5d631fa55 100644 --- a/crates/hir-ty/src/mir/borrowck.rs +++ b/crates/hir-ty/src/mir/borrowck.rs @@ -116,7 +116,7 @@ fn moved_out_of_ref(db: &dyn HirDatabase, body: &MirBody) -> Vec ); } if is_dereference_of_ref - && !ty.clone().is_copy(db, body.owner) + && !ty.clone().implements_copy(db, body.owner) && !ty.data(Interner).flags.intersects(TypeFlags::HAS_ERROR) { result.push(MovedOutOfRef { span, ty }); @@ -281,10 +281,10 @@ fn ever_initialized_map(body: &MirBody) -> ArenaMap { - Some(target).into_iter().chain(unwind.into_iter()).copied().collect() + Some(target).into_iter().chain(unwind.iter()).copied().collect() } TerminatorKind::DropAndReplace { .. } | TerminatorKind::Assert { .. } diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index 9acf9d39e56c..6fca088175ef 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -47,10 +47,10 @@ mod tests; macro_rules! from_bytes { ($ty:tt, $value:expr) => { - ($ty::from_le_bytes(match ($value).try_into() { + $ty::from_le_bytes(match ($value).try_into() { Ok(x) => x, Err(_) => return Err(MirEvalError::TypeError(stringify!(mismatched size in constructing $ty))), - })) + }) }; } @@ -211,7 +211,7 @@ impl From for IntervalOrOwned { } impl IntervalOrOwned { - pub(crate) fn to_vec(self, memory: &Evaluator<'_>) -> Result> { + pub(crate) fn into_vec(self, memory: &Evaluator<'_>) -> Result> { Ok(match self { IntervalOrOwned::Owned(o) => o, IntervalOrOwned::Borrowed(b) => b.get(memory)?.to_vec(), @@ -241,17 +241,16 @@ impl Address { } } - fn to_bytes(&self) -> Vec { + fn to_bytes(self) -> Vec { usize::to_le_bytes(self.to_usize()).to_vec() } - fn to_usize(&self) -> usize { - let as_num = match self { - Stack(x) => *x + usize::MAX / 2, - Heap(x) => *x + usize::MAX / 4, - Invalid(x) => *x, - }; - as_num + fn to_usize(self) -> usize { + match self { + Stack(x) => x + usize::MAX / 2, + Heap(x) => x + usize::MAX / 4, + Invalid(x) => x, + } } fn map(&self, f: impl FnOnce(usize) -> usize) -> Address { @@ -417,7 +416,7 @@ impl std::fmt::Debug for MirEvalError { let mut e = &**e; let mut stack = vec![(*func, *span)]; while let Self::InFunction(f, next_e, span, _) = e { - e = &next_e; + e = next_e; stack.push((*f, *span)); } f.debug_struct("WithStack").field("error", e).field("stack", &stack).finish() @@ -468,14 +467,14 @@ pub fn interpret_mir( let ty = body.locals[return_slot()].ty.clone(); let mut evaluator = Evaluator::new(db, body, assert_placeholder_ty_is_unused); let x: Result = (|| { - let bytes = evaluator.interpret_mir(&body, None.into_iter())?; + let bytes = evaluator.interpret_mir(body, None.into_iter())?; let mut memory_map = evaluator.create_memory_map( &bytes, &ty, - &Locals { ptr: &ArenaMap::new(), body: &body, drop_flags: DropFlags::default() }, + &Locals { ptr: &ArenaMap::new(), body, drop_flags: DropFlags::default() }, )?; memory_map.vtable = evaluator.vtable_map.clone(); - return Ok(intern_const_scalar(ConstScalar::Bytes(bytes, memory_map), ty)); + Ok(intern_const_scalar(ConstScalar::Bytes(bytes, memory_map), ty)) })(); ( x, @@ -505,7 +504,7 @@ impl Evaluator<'_> { stderr: vec![], assert_placeholder_ty_is_unused, stack_depth_limit: 100, - execution_limit: 1000_000, + execution_limit: 1_000_000, } } @@ -710,8 +709,7 @@ impl Evaluator<'_> { return Err(MirEvalError::StackOverflow); } let mut current_block_idx = body.start_block; - let mut locals = - Locals { ptr: &ArenaMap::new(), body: &body, drop_flags: DropFlags::default() }; + let mut locals = Locals { ptr: &ArenaMap::new(), body, drop_flags: DropFlags::default() }; let (locals_ptr, stack_size) = { let mut stack_ptr = self.stack.len(); let addr = body @@ -753,7 +751,7 @@ impl Evaluator<'_> { match &statement.kind { StatementKind::Assign(l, r) => { let addr = self.place_addr(l, &locals)?; - let result = self.eval_rvalue(r, &mut locals)?.to_vec(&self)?; + let result = self.eval_rvalue(r, &mut locals)?.into_vec(self)?; self.write_memory(addr, &result)?; locals.drop_flags.add_place(l.clone()); } @@ -812,7 +810,7 @@ impl Evaluator<'_> { } TerminatorKind::SwitchInt { discr, targets } => { let val = u128::from_le_bytes(pad16( - self.eval_operand(discr, &mut locals)?.get(&self)?, + self.eval_operand(discr, &mut locals)?.get(self)?, false, )); current_block_idx = targets.target_for_value(val); @@ -857,7 +855,7 @@ impl Evaluator<'_> { } } Rvalue::UnaryOp(op, val) => { - let mut c = self.eval_operand(val, locals)?.get(&self)?; + let mut c = self.eval_operand(val, locals)?.get(self)?; let mut ty = self.operand_ty(val, locals)?; while let TyKind::Ref(_, _, z) = ty.kind(Interner) { ty = z.clone(); @@ -900,8 +898,8 @@ impl Evaluator<'_> { Rvalue::CheckedBinaryOp(op, lhs, rhs) => 'binary_op: { let lc = self.eval_operand(lhs, locals)?; let rc = self.eval_operand(rhs, locals)?; - let mut lc = lc.get(&self)?; - let mut rc = rc.get(&self)?; + let mut lc = lc.get(self)?; + let mut rc = rc.get(self)?; let mut ty = self.operand_ty(lhs, locals)?; while let TyKind::Ref(_, _, z) = ty.kind(Interner) { ty = z.clone(); @@ -1048,17 +1046,11 @@ impl Evaluator<'_> { } Rvalue::Discriminant(p) => { let ty = self.place_ty(p, locals)?; - let bytes = self.eval_place(p, locals)?.get(&self)?; + let bytes = self.eval_place(p, locals)?.get(self)?; let layout = self.layout(&ty)?; - let enum_id = 'b: { - match ty.kind(Interner) { - TyKind::Adt(e, _) => match e.0 { - AdtId::EnumId(e) => break 'b e, - _ => (), - }, - _ => (), - } - return Ok(Owned(0u128.to_le_bytes().to_vec())); + let enum_id = match ty.kind(Interner) { + &TyKind::Adt(chalk_ir::AdtId(AdtId::EnumId(e)), _) => e, + _ => return Ok(Owned(0u128.to_le_bytes().to_vec())), }; match &layout.variants { Variants::Single { index } => { @@ -1102,7 +1094,7 @@ impl Evaluator<'_> { } } Rvalue::Repeat(x, len) => { - let len = match try_const_usize(self.db, &len) { + let len = match try_const_usize(self.db, len) { Some(x) => x as usize, None => not_supported!("non evaluatable array len in repeat Rvalue"), }; @@ -1128,13 +1120,13 @@ impl Evaluator<'_> { AggregateKind::Array(_) => { let mut r = vec![]; for x in values { - let value = x.get(&self)?; + let value = x.get(self)?; r.extend(value); } Owned(r) } AggregateKind::Tuple(ty) => { - let layout = self.layout(&ty)?; + let layout = self.layout(ty)?; Owned(self.make_by_layout( layout.size.bytes_usize(), &layout, @@ -1148,7 +1140,7 @@ impl Evaluator<'_> { .fields .offset(u32::from(f.local_id.into_raw()) as usize) .bytes_usize(); - let op = values[0].get(&self)?; + let op = values[0].get(self)?; let mut result = vec![0; layout.size.bytes_usize()]; result[offset..offset + op.len()].copy_from_slice(op); Owned(result) @@ -1164,7 +1156,7 @@ impl Evaluator<'_> { )?) } AggregateKind::Closure(ty) => { - let layout = self.layout(&ty)?; + let layout = self.layout(ty)?; Owned(self.make_by_layout( layout.size.bytes_usize(), &layout, @@ -1209,14 +1201,11 @@ impl Evaluator<'_> { | CastKind::PointerExposeAddress | CastKind::PointerFromExposedAddress => { let current_ty = self.operand_ty(operand, locals)?; - let is_signed = match current_ty.kind(Interner) { - TyKind::Scalar(s) => match s { - chalk_ir::Scalar::Int(_) => true, - _ => false, - }, - _ => false, - }; - let current = pad16(self.eval_operand(operand, locals)?.get(&self)?, is_signed); + let is_signed = matches!( + current_ty.kind(Interner), + TyKind::Scalar(chalk_ir::Scalar::Int(_)) + ); + let current = pad16(self.eval_operand(operand, locals)?.get(self)?, is_signed); let dest_size = self.size_of_sized(target_ty, locals, "destination of int to int cast")?; Owned(current[0..dest_size].to_vec()) @@ -1265,44 +1254,43 @@ impl Evaluator<'_> { _ => None, } } - Ok(match self.coerce_unsized_look_through_fields(target_ty, for_ptr)? { - ty => match &ty.data(Interner).kind { - TyKind::Slice(_) => { - match self.coerce_unsized_look_through_fields(current_ty, for_ptr)? { - ty => match &ty.data(Interner).kind { - TyKind::Array(_, size) => { - let len = match try_const_usize(self.db, size) { - None => not_supported!( - "unevaluatble len of array in coerce unsized" - ), - Some(x) => x as usize, - }; - let mut r = Vec::with_capacity(16); - let addr = addr.get(self)?; - r.extend(addr.iter().copied()); - r.extend(len.to_le_bytes().into_iter()); - Owned(r) - } - t => { - not_supported!("slice unsizing from non array type {t:?}") + let ty = self.coerce_unsized_look_through_fields(target_ty, for_ptr)?; + let res = match &ty.data(Interner).kind { + TyKind::Slice(_) => { + let ty = self.coerce_unsized_look_through_fields(current_ty, for_ptr)?; + match &ty.data(Interner).kind { + TyKind::Array(_, size) => { + let len = match try_const_usize(self.db, size) { + None => { + not_supported!("unevaluatble len of array in coerce unsized") } - }, - } - } - TyKind::Dyn(_) => match ¤t_ty.data(Interner).kind { - TyKind::Raw(_, ty) | TyKind::Ref(_, _, ty) => { - let vtable = self.vtable_map.id(ty.clone()); + Some(x) => x as usize, + }; let mut r = Vec::with_capacity(16); let addr = addr.get(self)?; r.extend(addr.iter().copied()); - r.extend(vtable.to_le_bytes().into_iter()); + r.extend(len.to_le_bytes().into_iter()); Owned(r) } - _ => not_supported!("dyn unsizing from non pointers"), - }, - _ => not_supported!("unknown unsized cast"), + t => { + not_supported!("slice unsizing from non array type {t:?}") + } + } + } + TyKind::Dyn(_) => match ¤t_ty.data(Interner).kind { + TyKind::Raw(_, ty) | TyKind::Ref(_, _, ty) => { + let vtable = self.vtable_map.id(ty.clone()); + let mut r = Vec::with_capacity(16); + let addr = addr.get(self)?; + r.extend(addr.iter().copied()); + r.extend(vtable.to_le_bytes().into_iter()); + Owned(r) + } + _ => not_supported!("dyn unsizing from non pointers"), }, - }) + _ => not_supported!("unknown unsized cast"), + }; + Ok(res) } fn layout_of_variant( @@ -1383,7 +1371,7 @@ impl Evaluator<'_> { } for (i, op) in values.enumerate() { let offset = variant_layout.fields.offset(i).bytes_usize(); - let op = op.get(&self)?; + let op = op.get(self)?; result[offset..offset + op.len()].copy_from_slice(op); } Ok(result) @@ -1510,10 +1498,10 @@ impl Evaluator<'_> { } } let layout = self.layout(ty); - if self.assert_placeholder_ty_is_unused { - if matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _))) { - return Ok(Some((0, 1))); - } + if self.assert_placeholder_ty_is_unused + && matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _))) + { + return Ok(Some((0, 1))); } let layout = layout?; Ok(layout @@ -1742,7 +1730,7 @@ impl Evaluator<'_> { let next_ty = self.vtable_map.ty(id)?.clone(); match &next_ty.data(Interner).kind { TyKind::FnDef(def, generic_args) => { - self.exec_fn_def(*def, generic_args, destination, args, &locals, span)?; + self.exec_fn_def(*def, generic_args, destination, args, locals, span)?; } TyKind::Closure(id, subst) => { self.exec_closure(*id, bytes.slice(0..0), subst, destination, args, locals, span)?; @@ -1777,7 +1765,7 @@ impl Evaluator<'_> { closure_data.get(self)?.to_owned() }; let arg_bytes = iter::once(Ok(closure_data)) - .chain(args.iter().map(|x| Ok(x.get(&self)?.to_owned()))) + .chain(args.iter().map(|x| Ok(x.get(self)?.to_owned()))) .collect::>>()?; let bytes = self.interpret_mir(&mir_body, arg_bytes.into_iter()).map_err(|e| { MirEvalError::InFunction(Either::Right(closure), Box::new(e), span, locals.body.owner) @@ -1798,15 +1786,15 @@ impl Evaluator<'_> { let generic_args = generic_args.clone(); match def { CallableDefId::FunctionId(def) => { - if let Some(_) = self.detect_fn_trait(def) { - self.exec_fn_trait(&args, destination, locals, span)?; + if self.detect_fn_trait(def).is_some() { + self.exec_fn_trait(args, destination, locals, span)?; return Ok(()); } self.exec_fn_with_args(def, args, generic_args, locals, destination, span)?; } CallableDefId::StructId(id) => { let (size, variant_layout, tag) = - self.layout_of_variant(id.into(), generic_args, &locals)?; + self.layout_of_variant(id.into(), generic_args, locals)?; let result = self.make_by_layout( size, &variant_layout, @@ -1817,7 +1805,7 @@ impl Evaluator<'_> { } CallableDefId::EnumVariantId(id) => { let (size, variant_layout, tag) = - self.layout_of_variant(id.into(), generic_args, &locals)?; + self.layout_of_variant(id.into(), generic_args, locals)?; let result = self.make_by_layout( size, &variant_layout, @@ -1850,7 +1838,7 @@ impl Evaluator<'_> { return Ok(()); } let arg_bytes = - args.iter().map(|x| Ok(x.get(&self)?.to_owned())).collect::>>()?; + args.iter().map(|x| Ok(x.get(self)?.to_owned())).collect::>>()?; if let Some(self_ty_idx) = is_dyn_method(self.db, self.trait_env.clone(), def, generic_args.clone()) { @@ -1977,13 +1965,13 @@ impl Evaluator<'_> { })?; let data = &konst.data(Interner); if let chalk_ir::ConstValue::Concrete(c) = &data.value { - self.allocate_const_in_heap(&c, &data.ty, locals, &konst)? + self.allocate_const_in_heap(c, &data.ty, locals, &konst)? } else { not_supported!("unevaluatable static"); } } else { let ty = &self.db.infer(st.into())[self.db.body(st.into()).body_expr]; - let Some((size, align)) = self.size_align_of(&ty, locals)? else { + let Some((size, align)) = self.size_align_of(ty, locals)? else { not_supported!("unsized extern static"); }; let addr = self.heap_allocate(size, align); diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs index 3b9ef03c369f..4ca22dc72fde 100644 --- a/crates/hir-ty/src/mir/eval/shim.rs +++ b/crates/hir-ty/src/mir/eval/shim.rs @@ -48,7 +48,7 @@ impl Evaluator<'_> { args, generic_args, destination, - &locals, + locals, span, )?; return Ok(true); @@ -66,7 +66,7 @@ impl Evaluator<'_> { args, generic_args, destination, - &locals, + locals, span, )?; return Ok(true); @@ -91,7 +91,7 @@ impl Evaluator<'_> { } if let Some(x) = self.detect_lang_function(def) { let arg_bytes = - args.iter().map(|x| Ok(x.get(&self)?.to_owned())).collect::>>()?; + args.iter().map(|x| Ok(x.get(self)?.to_owned())).collect::>>()?; let result = self.exec_lang_item(x, generic_args, &arg_bytes, locals, span)?; destination.write_from_bytes(self, &result)?; return Ok(true); @@ -489,7 +489,7 @@ impl Evaluator<'_> { let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else { return Err(MirEvalError::TypeError("size_of generic arg is not provided")); }; - let result = !ty.clone().is_copy(self.db, locals.body.owner); + let result = !ty.clone().implements_copy(self.db, locals.body.owner); destination.write_from_bytes(self, &[u8::from(result)]) } "ptr_guaranteed_cmp" => { diff --git a/crates/hir-ty/src/mir/eval/tests.rs b/crates/hir-ty/src/mir/eval/tests.rs index ca4268b8fb00..0111d893bd72 100644 --- a/crates/hir-ty/src/mir/eval/tests.rs +++ b/crates/hir-ty/src/mir/eval/tests.rs @@ -29,7 +29,7 @@ fn eval_main(db: &TestDB, file_id: FileId) -> Result<(String, String), MirEvalEr Substitution::empty(Interner), db.trait_environment(func_id.into()), ) - .map_err(|e| MirEvalError::MirLowerError(func_id.into(), e))?; + .map_err(|e| MirEvalError::MirLowerError(func_id, e))?; let (result, stdout, stderr) = interpret_mir(db, &body, false); result?; Ok((stdout, stderr)) @@ -48,8 +48,8 @@ fn check_pass_and_stdio(ra_fixture: &str, expected_stdout: &str, expected_stderr let mut err = String::new(); let line_index = |size: TextSize| { let mut size = u32::from(size) as usize; - let mut lines = ra_fixture.lines().enumerate(); - while let Some((i, l)) = lines.next() { + let lines = ra_fixture.lines().enumerate(); + for (i, l) in lines { if let Some(x) = size.checked_sub(l.len()) { size = x; } else { diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index aad1a82f2981..3d269caadb57 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -105,6 +105,7 @@ pub enum MirLowerError { /// A token to ensuring that each drop scope is popped at most once, thanks to the compiler that checks moves. struct DropScopeToken; impl DropScopeToken { + #[allow(clippy::forget_non_drop)] fn pop_and_drop(self, ctx: &mut MirLowerCtx<'_>, current: BasicBlockId) -> BasicBlockId { std::mem::forget(self); ctx.pop_drop_scope_internal(current) @@ -114,6 +115,7 @@ impl DropScopeToken { /// code. Either when the control flow is diverging (so drop code doesn't reached) or when drop is handled /// for us (for example a block that ended with a return statement. Return will drop everything, so the block shouldn't /// do anything) + #[allow(clippy::forget_non_drop)] fn pop_assume_dropped(self, ctx: &mut MirLowerCtx<'_>) { std::mem::forget(self); ctx.pop_drop_scope_assume_dropped_internal(); @@ -252,7 +254,8 @@ impl<'ctx> MirLowerCtx<'ctx> { owner, closures: vec![], }; - let ctx = MirLowerCtx { + + MirLowerCtx { result: mir, db, infer, @@ -262,8 +265,7 @@ impl<'ctx> MirLowerCtx<'ctx> { labeled_loop_blocks: Default::default(), discr_temp: None, drop_scopes: vec![DropScope::default()], - }; - ctx + } } fn temp(&mut self, ty: Ty, current: BasicBlockId, span: MirSpan) -> Result { @@ -281,12 +283,9 @@ impl<'ctx> MirLowerCtx<'ctx> { current: BasicBlockId, ) -> Result> { if !self.has_adjustments(expr_id) { - match &self.body.exprs[expr_id] { - Expr::Literal(l) => { - let ty = self.expr_ty_without_adjust(expr_id); - return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); - } - _ => (), + if let Expr::Literal(l) = &self.body.exprs[expr_id] { + let ty = self.expr_ty_without_adjust(expr_id); + return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); } } let Some((p, current)) = self.lower_expr_as_place(current, expr_id, true)? else { @@ -332,8 +331,8 @@ impl<'ctx> MirLowerCtx<'ctx> { current, place, Rvalue::Cast( - CastKind::Pointer(cast.clone()), - Operand::Copy(p).into(), + CastKind::Pointer(*cast), + Operand::Copy(p), last.target.clone(), ), expr_id.into(), @@ -612,8 +611,8 @@ impl<'ctx> MirLowerCtx<'ctx> { }; self.lower_call_and_args(func, args.iter().copied(), place, current, self.is_uninhabited(expr_id), expr_id.into()) } - TyKind::Error => return Err(MirLowerError::MissingFunctionDefinition(self.owner, expr_id)), - _ => return Err(MirLowerError::TypeError("function call on bad type")), + TyKind::Error => Err(MirLowerError::MissingFunctionDefinition(self.owner, expr_id)), + _ => Err(MirLowerError::TypeError("function call on bad type")), } } Expr::MethodCall { receiver, args, method_name, .. } => { @@ -861,10 +860,8 @@ impl<'ctx> MirLowerCtx<'ctx> { // for binary operator, and use without adjust to simplify our conditions. let lhs_ty = self.expr_ty_without_adjust(*lhs); let rhs_ty = self.expr_ty_without_adjust(*rhs); - if matches!(op ,BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) { - if lhs_ty.as_raw_ptr().is_some() && rhs_ty.as_raw_ptr().is_some() { - break 'b true; - } + if matches!(op ,BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) && lhs_ty.as_raw_ptr().is_some() && rhs_ty.as_raw_ptr().is_some() { + break 'b true; } let builtin_inequal_impls = matches!( op, @@ -1040,7 +1037,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.push_assignment( current, tmp.clone(), - Rvalue::Ref(bk.clone(), p), + Rvalue::Ref(*bk, p), capture.span, ); operands.push(Operand::Move(tmp)); @@ -1135,11 +1132,10 @@ impl<'ctx> MirLowerCtx<'ctx> { } fn placeholder_subst(&mut self) -> Substitution { - let placeholder_subst = match self.owner.as_generic_def_id() { + match self.owner.as_generic_def_id() { Some(x) => TyBuilder::placeholder_subst(self.db, x), None => Substitution::empty(Interner), - }; - placeholder_subst + } } fn push_field_projection(&self, place: &mut Place, expr_id: ExprId) -> Result<()> { @@ -1269,7 +1265,7 @@ impl<'ctx> MirLowerCtx<'ctx> { } else { let name = const_id.name(self.db.upcast()); self.db - .const_eval(const_id.into(), subst) + .const_eval(const_id, subst) .map_err(|e| MirLowerError::ConstEvalError(name, Box::new(e)))? }; Ok(Operand::Constant(c)) @@ -1713,7 +1709,7 @@ impl<'ctx> MirLowerCtx<'ctx> { current: &mut Idx, ) { for &l in scope.locals.iter().rev() { - if !self.result.locals[l].ty.clone().is_copy(self.db, self.owner) { + if !self.result.locals[l].ty.clone().implements_copy(self.db, self.owner) { let prev = std::mem::replace(current, self.new_basic_block()); self.set_terminator( prev, @@ -1739,6 +1735,7 @@ fn cast_kind(source_ty: &Ty, target_ty: &Ty) -> Result { }, (TyKind::Scalar(_), TyKind::Raw(..)) => CastKind::PointerFromExposedAddress, (TyKind::Raw(..), TyKind::Scalar(_)) => CastKind::PointerExposeAddress, + #[allow(clippy::if_same_then_else)] (TyKind::Raw(_, a) | TyKind::Ref(_, _, a), TyKind::Raw(_, b) | TyKind::Ref(_, _, b)) => { CastKind::Pointer(if a == b { PointerCast::MutToConstPointer @@ -1842,7 +1839,7 @@ pub fn mir_body_for_closure_query( if x.0.kind != CaptureKind::ByValue { next_projs.push(ProjectionElem::Deref); } - next_projs.extend(prev_projs.iter().cloned().skip(x.0.place.projections.len())); + next_projs.extend(prev_projs.iter().skip(x.0.place.projections.len()).cloned()); p.projection = next_projs.into(); } None => err = Some(p.clone()), diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs index d2c8d9a089e0..98a59a81d9f4 100644 --- a/crates/hir-ty/src/mir/lower/as_place.rs +++ b/crates/hir-ty/src/mir/lower/as_place.rs @@ -151,55 +151,53 @@ impl MirLowerCtx<'_> { _ => try_rvalue(self), } } - Expr::UnaryOp { expr, op } => match op { - hir_def::hir::UnaryOp::Deref => { - let is_builtin = match self.expr_ty_without_adjust(*expr).kind(Interner) { - TyKind::Ref(..) | TyKind::Raw(..) => true, - TyKind::Adt(id, _) => { - if let Some(lang_item) = lang_attr(self.db.upcast(), id.0) { - lang_item == LangItem::OwnedBox - } else { - false - } + Expr::UnaryOp { expr, op: hir_def::hir::UnaryOp::Deref } => { + let is_builtin = match self.expr_ty_without_adjust(*expr).kind(Interner) { + TyKind::Ref(..) | TyKind::Raw(..) => true, + TyKind::Adt(id, _) => { + if let Some(lang_item) = lang_attr(self.db.upcast(), id.0) { + lang_item == LangItem::OwnedBox + } else { + false } - _ => false, - }; - if !is_builtin { - let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)? else { + } + _ => false, + }; + if !is_builtin { + let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)? else { return Ok(None); }; - return self.lower_overloaded_deref( - current, - p, - self.expr_ty_after_adjustments(*expr), - self.expr_ty_without_adjust(expr_id), - expr_id.into(), - 'b: { - if let Some((f, _)) = self.infer.method_resolution(expr_id) { - if let Some(deref_trait) = - self.resolve_lang_item(LangItem::DerefMut)?.as_trait() + return self.lower_overloaded_deref( + current, + p, + self.expr_ty_after_adjustments(*expr), + self.expr_ty_without_adjust(expr_id), + expr_id.into(), + 'b: { + if let Some((f, _)) = self.infer.method_resolution(expr_id) { + if let Some(deref_trait) = + self.resolve_lang_item(LangItem::DerefMut)?.as_trait() + { + if let Some(deref_fn) = self + .db + .trait_data(deref_trait) + .method_by_name(&name![deref_mut]) { - if let Some(deref_fn) = self - .db - .trait_data(deref_trait) - .method_by_name(&name![deref_mut]) - { - break 'b deref_fn == f; - } + break 'b deref_fn == f; } } - false - }, - ); - } - let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else { + } + false + }, + ); + } + let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else { return Ok(None); }; - r = r.project(ProjectionElem::Deref); - Ok(Some((r, current))) - } - _ => try_rvalue(self), - }, + r = r.project(ProjectionElem::Deref); + Ok(Some((r, current))) + } + Expr::UnaryOp { .. } => try_rvalue(self), Expr::Field { expr, .. } => { let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else { return Ok(None); diff --git a/crates/hir-ty/src/mir/lower/pattern_matching.rs b/crates/hir-ty/src/mir/lower/pattern_matching.rs index ff43c64a9e60..54ae8e4a4052 100644 --- a/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -105,8 +105,8 @@ impl MirLowerCtx<'_> { current_else, args, *ellipsis, - (0..subst.len(Interner)).map(|i| PlaceElem::TupleOrClosureField(i)), - &(&mut cond_place), + (0..subst.len(Interner)).map(PlaceElem::TupleOrClosureField), + &cond_place, mode, )? } @@ -117,7 +117,7 @@ impl MirLowerCtx<'_> { let (mut next, next_else) = self.pattern_match_inner( current, None, - (&mut cond_place).clone(), + cond_place.clone(), *pat, MatchingMode::Check, )?; @@ -125,7 +125,7 @@ impl MirLowerCtx<'_> { (next, _) = self.pattern_match_inner( next, None, - (&mut cond_place).clone(), + cond_place.clone(), *pat, MatchingMode::Bind, )?; @@ -161,7 +161,7 @@ impl MirLowerCtx<'_> { current, pattern.into(), current_else, - AdtPatternShape::Record { args: &*args }, + AdtPatternShape::Record { args }, mode, )? } @@ -176,11 +176,7 @@ impl MirLowerCtx<'_> { self.push_assignment( current, discr.clone(), - Rvalue::CheckedBinaryOp( - binop, - lv, - Operand::Copy((&mut cond_place).clone()), - ), + Rvalue::CheckedBinaryOp(binop, lv, Operand::Copy(cond_place.clone())), pattern.into(), ); let discr = Operand::Copy(discr); @@ -215,7 +211,7 @@ impl MirLowerCtx<'_> { self.push_assignment( current, place_len.clone(), - Rvalue::Len((&mut cond_place).clone()), + Rvalue::Len(cond_place.clone()), pattern.into(), ); let else_target = @@ -262,7 +258,7 @@ impl MirLowerCtx<'_> { } } for (i, &pat) in prefix.iter().enumerate() { - let next_place = (&mut cond_place).project(ProjectionElem::ConstantIndex { + let next_place = cond_place.project(ProjectionElem::ConstantIndex { offset: i as u64, from_end: false, }); @@ -272,7 +268,7 @@ impl MirLowerCtx<'_> { if let Some(slice) = slice { if mode == MatchingMode::Bind { if let Pat::Bind { id, subpat: _ } = self.body[*slice] { - let next_place = (&mut cond_place).project(ProjectionElem::Subslice { + let next_place = cond_place.project(ProjectionElem::Subslice { from: prefix.len() as u64, to: suffix.len() as u64, }); @@ -287,7 +283,7 @@ impl MirLowerCtx<'_> { } } for (i, &pat) in suffix.iter().enumerate() { - let next_place = (&mut cond_place).project(ProjectionElem::ConstantIndex { + let next_place = cond_place.project(ProjectionElem::ConstantIndex { offset: i as u64, from_end: true, }); @@ -318,10 +314,8 @@ impl MirLowerCtx<'_> { break 'b (c, x.1); } } - if let ResolveValueResult::ValueNs(v) = pr { - if let ValueNs::ConstId(c) = v { - break 'b (c, Substitution::empty(Interner)); - } + if let ResolveValueResult::ValueNs(ValueNs::ConstId(c)) = pr { + break 'b (c, Substitution::empty(Interner)); } not_supported!("path in pattern position that is not const or variant") }; @@ -376,7 +370,7 @@ impl MirLowerCtx<'_> { (current, current_else) = self.pattern_match_inner( current, current_else, - (&mut cond_place).clone(), + cond_place.clone(), *subpat, mode, )? @@ -553,10 +547,7 @@ impl MirLowerCtx<'_> { .map(|x| { let field_id = variant_data.field(&x.name).ok_or(MirLowerError::UnresolvedField)?; - Ok(( - PlaceElem::Field(FieldId { parent: v.into(), local_id: field_id }), - x.pat, - )) + Ok((PlaceElem::Field(FieldId { parent: v, local_id: field_id }), x.pat)) }) .collect::>>()?; self.pattern_match_adt(current, current_else, it.into_iter(), cond_place, mode)? @@ -565,7 +556,7 @@ impl MirLowerCtx<'_> { let fields = variant_data .fields() .iter() - .map(|(x, _)| PlaceElem::Field(FieldId { parent: v.into(), local_id: x })); + .map(|(x, _)| PlaceElem::Field(FieldId { parent: v, local_id: x })); self.pattern_match_tuple_like( current, current_else, diff --git a/crates/hir-ty/src/mir/monomorphization.rs b/crates/hir-ty/src/mir/monomorphization.rs index ce3f7a8e5102..85fbda906b6b 100644 --- a/crates/hir-ty/src/mir/monomorphization.rs +++ b/crates/hir-ty/src/mir/monomorphization.rs @@ -206,11 +206,10 @@ impl Filler<'_> { const_id = GeneralConstId::ConstId(c); subst = s; } - let result = - self.db.const_eval(const_id.into(), subst).map_err(|e| { - let name = const_id.name(self.db.upcast()); - MirLowerError::ConstEvalError(name, Box::new(e)) - })?; + let result = self.db.const_eval(const_id, subst).map_err(|e| { + let name = const_id.name(self.db.upcast()); + MirLowerError::ConstEvalError(name, Box::new(e)) + })?; *c = result; } crate::ConstScalar::Bytes(_, _) | crate::ConstScalar::Unknown => (), @@ -318,7 +317,7 @@ pub fn monomorphized_mir_body_recover( _: &Substitution, _: &Arc, ) -> Result, MirLowerError> { - return Err(MirLowerError::Loop); + Err(MirLowerError::Loop) } pub fn monomorphized_mir_body_for_closure_query( diff --git a/crates/hir-ty/src/test_db.rs b/crates/hir-ty/src/test_db.rs index 7d19e0a19169..ab2ed91506b1 100644 --- a/crates/hir-ty/src/test_db.rs +++ b/crates/hir-ty/src/test_db.rs @@ -43,13 +43,13 @@ impl fmt::Debug for TestDB { impl Upcast for TestDB { fn upcast(&self) -> &(dyn ExpandDatabase + 'static) { - &*self + self } } impl Upcast for TestDB { fn upcast(&self) -> &(dyn DefDatabase + 'static) { - &*self + self } } diff --git a/crates/hir-ty/src/utils.rs b/crates/hir-ty/src/utils.rs index 681d087ede6e..0de5714eb824 100644 --- a/crates/hir-ty/src/utils.rs +++ b/crates/hir-ty/src/utils.rs @@ -435,7 +435,7 @@ pub(crate) fn detect_variant_from_bytes<'a>( e: EnumId, ) -> Option<(LocalEnumVariantId, &'a Layout)> { let (var_id, var_layout) = match &layout.variants { - hir_def::layout::Variants::Single { index } => (index.0, &*layout), + hir_def::layout::Variants::Single { index } => (index.0, layout), hir_def::layout::Variants::Multiple { tag, tag_encoding, variants, .. } => { let target_data_layout = db.target_data_layout(krate)?; let size = tag.size(&*target_data_layout).bytes_usize(); diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 294105dc02ac..72edf40e81c3 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -801,7 +801,7 @@ fn emit_def_diagnostic_( } DefDiagnosticKind::InvalidDeriveTarget { ast, id } => { let node = ast.to_node(db.upcast()); - let derive = node.attrs().nth(*id as usize); + let derive = node.attrs().nth(*id); match derive { Some(derive) => { acc.push( @@ -816,7 +816,7 @@ fn emit_def_diagnostic_( } DefDiagnosticKind::MalformedDerive { ast, id } => { let node = ast.to_node(db.upcast()); - let derive = node.attrs().nth(*id as usize); + let derive = node.attrs().nth(*id); match derive { Some(derive) => { acc.push( @@ -962,7 +962,7 @@ impl Field { } pub fn layout(&self, db: &dyn HirDatabase) -> Result { - db.layout_of_ty(self.ty(db).ty.clone(), self.parent.module(db).krate().into()) + db.layout_of_ty(self.ty(db).ty, self.parent.module(db).krate().into()) .map(|layout| Layout(layout, db.target_data_layout(self.krate(db).into()).unwrap())) } @@ -1297,13 +1297,7 @@ impl Adt { }; resolver .generic_params() - .and_then(|gp| { - (&gp.lifetimes) - .iter() - // there should only be a single lifetime - // but `Arena` requires to use an iterator - .nth(0) - }) + .and_then(|gp| gp.lifetimes.iter().next()) .map(|arena| arena.1.clone()) } @@ -1677,7 +1671,7 @@ impl DefWithBody { } (mir::MutabilityReason::Not, true) => { if !infer.mutated_bindings_in_closure.contains(&binding_id) { - let should_ignore = matches!(body[binding_id].name.as_str(), Some(x) if x.starts_with("_")); + let should_ignore = matches!(body[binding_id].name.as_str(), Some(x) if x.starts_with('_')); if !should_ignore { acc.push(UnusedMut { local }.into()) } @@ -2110,7 +2104,7 @@ impl Const { pub fn render_eval(self, db: &dyn HirDatabase) -> Result { let c = db.const_eval(self.id.into(), Substitution::empty(Interner))?; let r = format!("{}", HexifiedConst(c).display(db)); - return Ok(r); + Ok(r) } } @@ -2198,14 +2192,7 @@ impl Trait { db.generic_params(GenericDefId::from(self.id)) .type_or_consts .iter() - .filter(|(_, ty)| match ty { - TypeOrConstParamData::TypeParamData(ty) - if ty.provenance != TypeParamProvenance::TypeParamList => - { - false - } - _ => true, - }) + .filter(|(_, ty)| !matches!(ty, TypeOrConstParamData::TypeParamData(ty) if ty.provenance != TypeParamProvenance::TypeParamList)) .filter(|(_, ty)| !count_required_only || !ty.has_default()) .count() } @@ -2482,6 +2469,7 @@ pub enum AssocItemContainer { Impl(Impl), } pub trait AsAssocItem { + #[allow(clippy::wrong_self_convention)] fn as_assoc_item(self, db: &dyn HirDatabase) -> Option; } @@ -2819,7 +2807,7 @@ impl DeriveHelper { .and_then(|it| it.get(self.idx as usize)) .cloned(), } - .unwrap_or_else(|| Name::missing()) + .unwrap_or_else(Name::missing) } } @@ -3281,16 +3269,20 @@ impl From for ClosureId { } impl Closure { - fn as_ty(self) -> Ty { + fn into_ty(self) -> Ty { TyKind::Closure(self.id, self.subst).intern(Interner) } pub fn display_with_id(&self, db: &dyn HirDatabase) -> String { - self.clone().as_ty().display(db).with_closure_style(ClosureStyle::ClosureWithId).to_string() + self.clone() + .into_ty() + .display(db) + .with_closure_style(ClosureStyle::ClosureWithId) + .to_string() } pub fn display_with_impl(&self, db: &dyn HirDatabase) -> String { - self.clone().as_ty().display(db).with_closure_style(ClosureStyle::ImplFn).to_string() + self.clone().into_ty().display(db).with_closure_style(ClosureStyle::ImplFn).to_string() } pub fn captured_items(&self, db: &dyn HirDatabase) -> Vec { @@ -3488,10 +3480,7 @@ impl Type { } pub fn is_int_or_uint(&self) -> bool { - match self.ty.kind(Interner) { - TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)) => true, - _ => false, - } + matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))) } pub fn is_scalar(&self) -> bool { @@ -3895,10 +3884,9 @@ impl Type { // arg can be either a `Ty` or `constant` if let Some(ty) = arg.ty(Interner) { Some(SmolStr::new(ty.display(db).to_string())) - } else if let Some(const_) = arg.constant(Interner) { - Some(SmolStr::new_inline(&const_.display(db).to_string())) } else { - None + arg.constant(Interner) + .map(|const_| SmolStr::new_inline(&const_.display(db).to_string())) } }) } @@ -3910,7 +3898,7 @@ impl Type { ) -> impl Iterator + 'a { // iterate the lifetime self.as_adt() - .and_then(|a| a.lifetime(db).and_then(|lt| Some((<.name).to_smol_str()))) + .and_then(|a| a.lifetime(db).map(|lt| lt.name.to_smol_str())) .into_iter() // add the type and const parameters .chain(self.type_and_const_arguments(db)) @@ -4047,7 +4035,7 @@ impl Type { traits_in_scope, with_local_impls.and_then(|b| b.id.containing_block()).into(), name, - &mut |id| callback(id), + callback, ); } diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index 2d2b00b147e5..091d0e93dbfd 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -758,7 +758,7 @@ impl<'db> SemanticsImpl<'db> { res = Some(value); true } else { - if let None = res { + if res.is_none() { res = Some(value) } false @@ -1126,9 +1126,7 @@ impl<'db> SemanticsImpl<'db> { // Update `source_ty` for the next adjustment let source = mem::replace(&mut source_ty, target.clone()); - let adjustment = Adjustment { source, target, kind }; - - adjustment + Adjustment { source, target, kind } }) .collect() }) @@ -1375,7 +1373,7 @@ impl<'db> SemanticsImpl<'db> { assert!(root_node.parent().is_none()); let mut cache = self.cache.borrow_mut(); let prev = cache.insert(root_node, file_id); - assert!(prev == None || prev == Some(file_id)) + assert!(prev.is_none() || prev == Some(file_id)) } fn assert_contains_node(&self, node: &SyntaxNode) { diff --git a/crates/hir/src/semantics/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs index c50ffa4f8b70..db5481f4ca09 100644 --- a/crates/hir/src/semantics/source_to_def.rs +++ b/crates/hir/src/semantics/source_to_def.rs @@ -275,6 +275,7 @@ impl SourceToDefCtx<'_, '_> { self.dyn_map(adt).as_ref().map_or(false, |map| !map[keys::DERIVE_MACRO_CALL].is_empty()) } + #[allow(clippy::wrong_self_convention)] fn to_def( &mut self, src: InFile, @@ -298,7 +299,7 @@ impl SourceToDefCtx<'_, '_> { pub(super) fn type_param_to_def(&mut self, src: InFile) -> Option { let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into(); let dyn_map = self.cache_for(container, src.file_id); - dyn_map[keys::TYPE_PARAM].get(&src.value).copied().map(|x| TypeParamId::from_unchecked(x)) + dyn_map[keys::TYPE_PARAM].get(&src.value).copied().map(TypeParamId::from_unchecked) } pub(super) fn lifetime_param_to_def( @@ -316,7 +317,7 @@ impl SourceToDefCtx<'_, '_> { ) -> Option { let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into(); let dyn_map = self.cache_for(container, src.file_id); - dyn_map[keys::CONST_PARAM].get(&src.value).copied().map(|x| ConstParamId::from_unchecked(x)) + dyn_map[keys::CONST_PARAM].get(&src.value).copied().map(ConstParamId::from_unchecked) } pub(super) fn generic_param_to_def( diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 1374fa332c64..04cb68e39cb4 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -199,10 +199,8 @@ impl SourceAnalyzer { ) -> Option<(Type, Option)> { let pat_id = self.pat_id(pat)?; let infer = self.infer.as_ref()?; - let coerced = infer - .pat_adjustments - .get(&pat_id) - .and_then(|adjusts| adjusts.last().map(|adjust| adjust.clone())); + let coerced = + infer.pat_adjustments.get(&pat_id).and_then(|adjusts| adjusts.last().cloned()); let ty = infer[pat_id].clone(); let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty); Some((mk_ty(ty), coerced.map(mk_ty))) @@ -591,7 +589,7 @@ impl SourceAnalyzer { } None })(); - if let Some(_) = resolved { + if resolved.is_some() { return resolved; } @@ -637,7 +635,7 @@ impl SourceAnalyzer { if let Some(name_ref) = path.as_single_name_ref() { let builtin = BuiltinAttr::by_name(db, self.resolver.krate().into(), &name_ref.text()); - if let Some(_) = builtin { + if builtin.is_some() { return builtin.map(PathResolution::BuiltinAttr); } @@ -1093,7 +1091,7 @@ fn resolve_hir_path_qualifier( path: &Path, ) -> Option { resolver - .resolve_path_in_type_ns_fully(db.upcast(), &path) + .resolve_path_in_type_ns_fully(db.upcast(), path) .map(|ty| match ty { TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()), diff --git a/crates/ide-assists/src/handlers/add_missing_match_arms.rs b/crates/ide-assists/src/handlers/add_missing_match_arms.rs index 7384390f28b5..f561598f64cf 100644 --- a/crates/ide-assists/src/handlers/add_missing_match_arms.rs +++ b/crates/ide-assists/src/handlers/add_missing_match_arms.rs @@ -42,7 +42,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) let match_arm_list = match_expr.match_arm_list()?; let target_range = ctx.sema.original_range(match_expr.syntax()).range; - if let None = cursor_at_trivial_match_arm_list(ctx, &match_expr, &match_arm_list) { + if cursor_at_trivial_match_arm_list(ctx, &match_expr, &match_arm_list).is_none() { let arm_list_range = ctx.sema.original_range(match_arm_list.syntax()).range; let cursor_in_range = arm_list_range.contains_range(ctx.selection_trimmed()); if cursor_in_range { @@ -159,7 +159,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .iter() .any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); let patterns = variants.into_iter().filter_map(|variant| { - build_pat(ctx.db(), module, variant.clone(), ctx.config.prefer_no_std) + build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std) }); (ast::Pat::from(make::slice_pat(patterns)), is_hidden) }) @@ -253,7 +253,7 @@ fn cursor_at_trivial_match_arm_list( match_arm_list: &MatchArmList, ) -> Option<()> { // match x { $0 } - if match_arm_list.arms().next() == None { + if match_arm_list.arms().next().is_none() { cov_mark::hit!(add_missing_match_arms_empty_body); return Some(()); } diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index 7acf2ea0a0de..531bf2ff189e 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -158,7 +158,7 @@ pub(super) fn find_importable_node( { ImportAssets::for_method_call(&method_under_caret, &ctx.sema) .zip(Some(method_under_caret.syntax().clone().into())) - } else if let Some(_) = ctx.find_node_at_offset_with_descend::() { + } else if ctx.find_node_at_offset_with_descend::().is_some() { None } else if let Some(pat) = ctx .find_node_at_offset_with_descend::() diff --git a/crates/ide-assists/src/handlers/convert_match_to_let_else.rs b/crates/ide-assists/src/handlers/convert_match_to_let_else.rs index fc6236a17558..5657f2dbfb3f 100644 --- a/crates/ide-assists/src/handlers/convert_match_to_let_else.rs +++ b/crates/ide-assists/src/handlers/convert_match_to_let_else.rs @@ -113,7 +113,7 @@ fn find_extracted_variable(ctx: &AssistContext<'_>, arm: &ast::MatchArm) -> Opti } _ => { cov_mark::hit!(extracting_arm_is_not_an_identity_expr); - return None; + None } } } diff --git a/crates/ide-assists/src/handlers/convert_nested_function_to_closure.rs b/crates/ide-assists/src/handlers/convert_nested_function_to_closure.rs index 399f87c8f509..c30f3e1c3b2b 100644 --- a/crates/ide-assists/src/handlers/convert_nested_function_to_closure.rs +++ b/crates/ide-assists/src/handlers/convert_nested_function_to_closure.rs @@ -49,8 +49,8 @@ pub(crate) fn convert_nested_function_to_closure( target, |edit| { let params = ¶m_list.syntax().text().to_string(); - let params = params.strip_prefix("(").unwrap_or(params); - let params = params.strip_suffix(")").unwrap_or(params); + let params = params.strip_prefix('(').unwrap_or(params); + let params = params.strip_suffix(')').unwrap_or(params); let mut body = body.to_string(); if !has_semicolon(&function) { 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 b1b0f587cd33..a55b88497a94 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 @@ -80,7 +80,7 @@ fn is_bool_literal_expr(expr: &Option, expect_bool: bool) -> bool { } } - return false; + false } #[cfg(test)] diff --git a/crates/ide-assists/src/handlers/extract_expressions_from_format_string.rs b/crates/ide-assists/src/handlers/extract_expressions_from_format_string.rs index 4f3b6e0c287c..fa862f57c4bb 100644 --- a/crates/ide-assists/src/handlers/extract_expressions_from_format_string.rs +++ b/crates/ide-assists/src/handlers/extract_expressions_from_format_string.rs @@ -158,7 +158,7 @@ mod tests { use super::*; use crate::tests::check_assist; - const MACRO_DECL: &'static str = r#" + const MACRO_DECL: &str = r#" macro_rules! format_args { ($lit:literal $(tt:tt)*) => { 0 }, } diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index 2a67909e6371..d8ec1c8e8e50 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -531,7 +531,7 @@ impl FunctionBody { fn extracted_from_trait_impl(&self) -> bool { match self.node().ancestors().find_map(ast::Impl::cast) { - Some(c) => return c.trait_().is_some(), + Some(c) => c.trait_().is_some(), None => false, } } @@ -1048,23 +1048,17 @@ impl GenericParent { fn generic_parents(parent: &SyntaxNode) -> Vec { let mut list = Vec::new(); if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) { - match parent_item { - ast::Item::Fn(ref fn_) => { - 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 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 @@ -1876,10 +1870,9 @@ fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr if let Some(stmt_list) = block.stmt_list() { stmt_list.syntax().children_with_tokens().for_each(|node_or_token| { - match &node_or_token { - syntax::NodeOrToken::Token(_) => elements.push(node_or_token), - _ => (), - }; + if let syntax::NodeOrToken::Token(_) = &node_or_token { + elements.push(node_or_token) + } }); } diff --git a/crates/ide-assists/src/handlers/extract_module.rs b/crates/ide-assists/src/handlers/extract_module.rs index de37f5f130fc..7c797f967006 100644 --- a/crates/ide-assists/src/handlers/extract_module.rs +++ b/crates/ide-assists/src/handlers/extract_module.rs @@ -668,7 +668,7 @@ fn check_intersection_and_push( // check for intersection between all current members // and combine all such ranges into one. let s: SmallVec<[_; 2]> = import_paths_to_be_removed - .into_iter() + .iter_mut() .positions(|it| it.intersect(import_path).is_some()) .collect(); for pos in s.into_iter().rev() { @@ -704,12 +704,9 @@ fn does_source_exists_outside_sel_in_same_mod( } if have_same_parent { - match source.value { - ModuleSource::Module(module_) => { - source_exists_outside_sel_in_same_mod = - !selection_range.contains_range(module_.syntax().text_range()); - } - _ => {} + if let ModuleSource::Module(module_) = source.value { + source_exists_outside_sel_in_same_mod = + !selection_range.contains_range(module_.syntax().text_range()); } } } diff --git a/crates/ide-assists/src/handlers/extract_type_alias.rs b/crates/ide-assists/src/handlers/extract_type_alias.rs index 71b45d88cb8c..c6e3b713b084 100644 --- a/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -185,7 +185,7 @@ fn collect_used_generics<'gp>( ast::GenericParam::TypeParam(_) => 1, }); - Some(generics).filter(|it| it.len() > 0) + Some(generics).filter(|it| !it.is_empty()) } #[cfg(test)] diff --git a/crates/ide-assists/src/handlers/generate_constant.rs b/crates/ide-assists/src/handlers/generate_constant.rs index eccd7675fbaa..edf839652260 100644 --- a/crates/ide-assists/src/handlers/generate_constant.rs +++ b/crates/ide-assists/src/handlers/generate_constant.rs @@ -103,10 +103,10 @@ fn get_text_for_generate_constant( type_name: String, ) -> Option { let constant_token = not_exist_name_ref.pop()?; - let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " }; + let vis = if not_exist_name_ref.is_empty() && !outer_exists { "" } else { "\npub " }; let mut text = format!("{vis}const {constant_token}: {type_name} = $0;"); while let Some(name_ref) = not_exist_name_ref.pop() { - let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " }; + let vis = if not_exist_name_ref.is_empty() && !outer_exists { "" } else { "\npub " }; text = text.replace('\n', "\n "); text = format!("{vis}mod {name_ref} {{{text}\n}}"); } @@ -132,8 +132,7 @@ fn target_data_for_generate_constant( let siblings_has_newline = l_curly_token .siblings_with_tokens(Direction::Next) - .find(|it| it.kind() == SyntaxKind::WHITESPACE && it.to_string().contains('\n')) - .is_some(); + .any(|it| it.kind() == SyntaxKind::WHITESPACE && it.to_string().contains('\n')); let post_string = if siblings_has_newline { format!("{indent}") } else { format!("\n{indent}") }; Some((offset, indent + 1, Some(file_id), post_string)) diff --git a/crates/ide-assists/src/handlers/generate_delegate_methods.rs b/crates/ide-assists/src/handlers/generate_delegate_methods.rs index 3667fc375b43..d7ca0b96394f 100644 --- a/crates/ide-assists/src/handlers/generate_delegate_methods.rs +++ b/crates/ide-assists/src/handlers/generate_delegate_methods.rs @@ -168,7 +168,7 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<' // Attach the function to the impl block let name = &strukt_name.to_string(); let params = strukt.generic_param_list(); - let ty_params = params.clone(); + let ty_params = params; let where_clause = strukt.where_clause(); let impl_def = make::impl_( diff --git a/crates/ide-assists/src/handlers/generate_documentation_template.rs b/crates/ide-assists/src/handlers/generate_documentation_template.rs index e87132218ea9..f298ce8916db 100644 --- a/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -148,7 +148,7 @@ fn make_example_for_fn(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option>(); - if info_of_record_fields_in_selection.len() == 0 { + if info_of_record_fields_in_selection.is_empty() { return None; } Some((info_of_record_fields_in_selection, field_names)) } - ast::FieldList::TupleFieldList(_) => { - return None; - } + ast::FieldList::TupleFieldList(_) => None, } } diff --git a/crates/ide-assists/src/handlers/generate_impl.rs b/crates/ide-assists/src/handlers/generate_impl.rs index 9ad14a819d97..d52d778d344a 100644 --- a/crates/ide-assists/src/handlers/generate_impl.rs +++ b/crates/ide-assists/src/handlers/generate_impl.rs @@ -29,7 +29,7 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio let name = nominal.name()?; let target = nominal.syntax().text_range(); - if let Some(_) = ctx.find_node_at_offset::() { + if ctx.find_node_at_offset::().is_some() { return None; } @@ -77,7 +77,7 @@ pub(crate) fn generate_trait_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> let name = nominal.name()?; let target = nominal.syntax().text_range(); - if let Some(_) = ctx.find_node_at_offset::() { + if ctx.find_node_at_offset::().is_some() { return None; } diff --git a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs index 442918619604..6bfc69b0ada6 100644 --- a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs +++ b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs @@ -95,7 +95,7 @@ fn get_impl_method( let scope = ctx.sema.scope(impl_.syntax())?; let ty = impl_def.self_ty(db); - ty.iterate_method_candidates(db, &scope, None, Some(fn_name), |func| Some(func)) + ty.iterate_method_candidates(db, &scope, None, Some(fn_name), Some) } #[cfg(test)] diff --git a/crates/ide-assists/src/handlers/inline_const_as_literal.rs b/crates/ide-assists/src/handlers/inline_const_as_literal.rs index 5b1540b50ca4..18437453761c 100644 --- a/crates/ide-assists/src/handlers/inline_const_as_literal.rs +++ b/crates/ide-assists/src/handlers/inline_const_as_literal.rs @@ -60,7 +60,7 @@ pub(crate) fn inline_const_as_literal(acc: &mut Assists, ctx: &AssistContext<'_> let id = AssistId("inline_const_as_literal", AssistKind::RefactorInline); - let label = format!("Inline const as literal"); + let label = "Inline const as literal".to_string(); let target = variable.syntax().text_range(); return acc.add(id, label, target, |edit| { @@ -100,7 +100,7 @@ fn validate_type_recursively( } (_, Some(ty)) => match ty.as_builtin() { // `const A: str` is not correct, but `const A: &builtin` is. - Some(builtin) if refed || (!refed && !builtin.is_str()) => Some(()), + Some(builtin) if refed || !builtin.is_str() => Some(()), _ => None, }, _ => None, @@ -138,7 +138,7 @@ mod tests { // -----------Not supported----------- #[test] fn inline_const_as_literal_const_fn_call_slice() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist_not_applicable( inline_const_as_literal, &format!( @@ -240,7 +240,7 @@ mod tests { #[test] fn inline_const_as_literal_const_expr() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -261,7 +261,7 @@ mod tests { #[test] fn inline_const_as_literal_const_block_expr() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -282,7 +282,7 @@ mod tests { #[test] fn inline_const_as_literal_const_block_eval_expr() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -303,7 +303,7 @@ mod tests { #[test] fn inline_const_as_literal_const_block_eval_block_expr() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -324,7 +324,7 @@ mod tests { #[test] fn inline_const_as_literal_const_fn_call_block_nested_builtin() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -347,7 +347,7 @@ mod tests { #[test] fn inline_const_as_literal_const_fn_call_tuple() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( @@ -370,7 +370,7 @@ mod tests { #[test] fn inline_const_as_literal_const_fn_call_builtin() { - TEST_PAIRS.into_iter().for_each(|(ty, val, _)| { + TEST_PAIRS.iter().for_each(|(ty, val, _)| { check_assist( inline_const_as_literal, &format!( diff --git a/crates/ide-assists/src/handlers/inline_macro.rs b/crates/ide-assists/src/handlers/inline_macro.rs index 5aa8e56f5626..e19f04b10b62 100644 --- a/crates/ide-assists/src/handlers/inline_macro.rs +++ b/crates/ide-assists/src/handlers/inline_macro.rs @@ -42,7 +42,7 @@ pub(crate) fn inline_macro(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option acc.add( AssistId("inline_macro", AssistKind::RefactorRewrite), - format!("Inline macro"), + "Inline macro".to_string(), text_range, |builder| builder.replace(text_range, expanded.to_string()), ) diff --git a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs index c5aa9755bc0b..7fd52aaecf8a 100644 --- a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs +++ b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs @@ -87,7 +87,7 @@ fn generate_fn_def_assist( let fn_def = builder.make_mut(fn_def); let lifetime = builder.make_mut(lifetime); let loc_needing_lifetime = - loc_needing_lifetime.and_then(|it| it.make_mut(builder).to_position()); + loc_needing_lifetime.and_then(|it| it.make_mut(builder).into_position()); fn_def.get_or_create_generic_param_list().add_generic_param( make::lifetime_param(new_lifetime_param.clone()).clone_for_update().into(), @@ -147,7 +147,7 @@ impl NeedsLifetime { } } - fn to_position(self) -> Option { + fn into_position(self) -> Option { match self { Self::SelfParam(it) => Some(Position::after(it.amp_token()?)), Self::RefType(it) => Some(Position::after(it.amp_token()?)), diff --git a/crates/ide-assists/src/handlers/replace_if_let_with_match.rs b/crates/ide-assists/src/handlers/replace_if_let_with_match.rs index 5e31d38fbd6a..f13b0b0713d5 100644 --- a/crates/ide-assists/src/handlers/replace_if_let_with_match.rs +++ b/crates/ide-assists/src/handlers/replace_if_let_with_match.rs @@ -279,7 +279,7 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<' let then_block = make_block_expr(then_expr.reset_indent()); let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) }; let if_let_expr = make::expr_if( - condition.into(), + condition, then_block, else_expr.map(make_block_expr).map(ast::ElseBranch::Block), ) diff --git a/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs b/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs index a7e3ed793f17..7f3b0d758839 100644 --- a/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs +++ b/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs @@ -133,7 +133,7 @@ pub(crate) fn replace_with_eager_method(acc: &mut Assists, ctx: &AssistContext<' None, None, |func| { - let valid = func.name(ctx.sema.db).as_str() == Some(&*method_name_eager) + let valid = func.name(ctx.sema.db).as_str() == Some(method_name_eager) && func.num_params(ctx.sema.db) == n_params; valid.then_some(func) }, diff --git a/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs b/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs index 43a97d7d3a55..1794c8874399 100644 --- a/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs +++ b/crates/ide-assists/src/handlers/replace_turbofish_with_explicit_type.rs @@ -69,7 +69,7 @@ pub(crate) fn replace_turbofish_with_explicit_type( return None; } - if let None = let_stmt.colon_token() { + if let_stmt.colon_token().is_none() { // If there's no colon in a let statement, then there is no explicit type. // let x = fn::<...>(); let ident_range = let_stmt.pat()?.syntax().text_range(); @@ -111,7 +111,7 @@ fn generic_arg_list(expr: &Expr) -> Option { pe.path()?.segment()?.generic_arg_list() } else { cov_mark::hit!(not_applicable_if_non_path_function_call); - return None; + None } } Expr::AwaitExpr(expr) => generic_arg_list(&expr.expr()?), diff --git a/crates/ide-assists/src/handlers/unnecessary_async.rs b/crates/ide-assists/src/handlers/unnecessary_async.rs index 7f612c2a142c..aa7ea4f39ae0 100644 --- a/crates/ide-assists/src/handlers/unnecessary_async.rs +++ b/crates/ide-assists/src/handlers/unnecessary_async.rs @@ -37,7 +37,7 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_>) -> O return None; } // Do nothing if the function isn't async. - if let None = function.async_token() { + if function.async_token().is_none() { return None; } // Do nothing if the function has an `await` expression in its body. @@ -46,7 +46,7 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_>) -> O } // Do nothing if the method is a member of trait. if let Some(impl_) = function.syntax().ancestors().nth(2).and_then(ast::Impl::cast) { - if let Some(_) = impl_.trait_() { + if impl_.trait_().is_some() { return None; } } diff --git a/crates/ide-assists/src/handlers/unwrap_block.rs b/crates/ide-assists/src/handlers/unwrap_block.rs index 939055f148c4..de801279a0e1 100644 --- a/crates/ide-assists/src/handlers/unwrap_block.rs +++ b/crates/ide-assists/src/handlers/unwrap_block.rs @@ -53,7 +53,7 @@ pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option let stmts: Vec = list.statements().collect(); let initializer = ast::Expr::cast(last)?; let let_stmt = make::let_stmt(pattern, ty, Some(initializer)); - if stmts.len() > 0 { + if !stmts.is_empty() { let block = make::block_expr(stmts, None); format!("{}\n {}", update_expr_string(block.to_string()), let_stmt) } else { diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs index 344f2bfcce14..fa6f23d9f453 100644 --- a/crates/ide-assists/src/tests.rs +++ b/crates/ide-assists/src/tests.rs @@ -188,7 +188,7 @@ fn check_with_config( .filter(|it| !it.source_file_edits.is_empty() || !it.file_system_edits.is_empty()) .expect("Assist did not contain any source changes"); let skip_header = source_change.source_file_edits.len() == 1 - && source_change.file_system_edits.len() == 0; + && source_change.file_system_edits.is_empty(); let mut buf = String::new(); for (file_id, edit) in source_change.source_file_edits { diff --git a/crates/ide-assists/src/tests/sourcegen.rs b/crates/ide-assists/src/tests/sourcegen.rs index 3da90e9052f2..ad5ec8328752 100644 --- a/crates/ide-assists/src/tests/sourcegen.rs +++ b/crates/ide-assists/src/tests/sourcegen.rs @@ -103,7 +103,7 @@ impl Assist { let doc = take_until(lines.by_ref(), "```").trim().to_string(); assert!( (doc.chars().next().unwrap().is_ascii_uppercase() && doc.ends_with('.')) - || assist.sections.len() > 0, + || !assist.sections.is_empty(), "\n\n{}: assist docs should be proper sentences, with capitalization and a full stop at the end.\n\n{}\n\n", &assist.id, doc, diff --git a/crates/ide-assists/src/utils/suggest_name.rs b/crates/ide-assists/src/utils/suggest_name.rs index f74ebfae02c7..10dee38783d0 100644 --- a/crates/ide-assists/src/utils/suggest_name.rs +++ b/crates/ide-assists/src/utils/suggest_name.rs @@ -137,10 +137,10 @@ fn normalize(name: &str) -> Option { } fn is_valid_name(name: &str) -> bool { - match ide_db::syntax_helpers::LexedStr::single_token(name) { - Some((syntax::SyntaxKind::IDENT, _error)) => true, - _ => false, - } + matches!( + ide_db::syntax_helpers::LexedStr::single_token(name), + Some((syntax::SyntaxKind::IDENT, _error)) + ) } fn is_useless_method(method: &ast::MethodCallExpr) -> bool { diff --git a/crates/ide-completion/src/completions/env_vars.rs b/crates/ide-completion/src/completions/env_vars.rs index 419b86456555..35e6b97eb783 100644 --- a/crates/ide-completion/src/completions/env_vars.rs +++ b/crates/ide-completion/src/completions/env_vars.rs @@ -37,7 +37,7 @@ pub(crate) fn complete_cargo_env_vars( guard_env_macro(expanded, &ctx.sema)?; let range = expanded.text_range_between_quotes()?; - CARGO_DEFINED_VARS.into_iter().for_each(|&(var, detail)| { + CARGO_DEFINED_VARS.iter().for_each(|&(var, detail)| { let mut item = CompletionItem::new(CompletionItemKind::Keyword, range, var); item.detail(detail); item.add_to(acc, ctx.db); diff --git a/crates/ide-completion/src/completions/field.rs b/crates/ide-completion/src/completions/field.rs index 870df63b7bf2..b0635e2d11bf 100644 --- a/crates/ide-completion/src/completions/field.rs +++ b/crates/ide-completion/src/completions/field.rs @@ -13,20 +13,18 @@ pub(crate) fn complete_field_list_tuple_variant( if ctx.qualifier_ctx.vis_node.is_some() { return; } - match path_ctx { - PathCompletionCtx { - has_macro_bang: false, - qualified: Qualified::No, - parent: None, - has_type_args: false, - .. - } => { - let mut add_keyword = |kw, snippet| acc.add_keyword_snippet(ctx, kw, snippet); - add_keyword("pub(crate)", "pub(crate)"); - add_keyword("pub(super)", "pub(super)"); - add_keyword("pub", "pub"); - } - _ => (), + if let PathCompletionCtx { + has_macro_bang: false, + qualified: Qualified::No, + parent: None, + has_type_args: false, + .. + } = path_ctx + { + let mut add_keyword = |kw, snippet| acc.add_keyword_snippet(ctx, kw, snippet); + add_keyword("pub(crate)", "pub(crate)"); + add_keyword("pub(super)", "pub(super)"); + add_keyword("pub", "pub"); } } diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index 39c1b7f7b3fb..854bbdd7898d 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -346,11 +346,10 @@ fn import_on_the_fly_method( .sorted_by_key(|located_import| { compute_fuzzy_completion_order_key(&located_import.import_path, &user_input_lowercased) }) - .for_each(|import| match import.original_item { - ItemInNs::Values(hir::ModuleDef::Function(f)) => { + .for_each(|import| { + if let ItemInNs::Values(hir::ModuleDef::Function(f)) = import.original_item { acc.add_method_with_import(ctx, dot_access, f, import); } - _ => (), }); Some(()) } diff --git a/crates/ide-completion/src/completions/fn_param.rs b/crates/ide-completion/src/completions/fn_param.rs index 8b38d4f01f67..d67c00c6c694 100644 --- a/crates/ide-completion/src/completions/fn_param.rs +++ b/crates/ide-completion/src/completions/fn_param.rs @@ -108,7 +108,7 @@ fn fill_fn_params( remove_duplicated(&mut file_params, param_list.params()); let self_completion_items = ["self", "&self", "mut self", "&mut self"]; if should_add_self_completions(ctx.token.text_range().start(), param_list, impl_) { - self_completion_items.into_iter().for_each(|self_item| add_new_item_to_acc(self_item)); + self_completion_items.into_iter().for_each(&mut add_new_item_to_acc); } file_params.keys().for_each(|whole_param| add_new_item_to_acc(whole_param)); diff --git a/crates/ide-completion/src/completions/item_list.rs b/crates/ide-completion/src/completions/item_list.rs index 5ea6a49b1ae1..4de15ab75962 100644 --- a/crates/ide-completion/src/completions/item_list.rs +++ b/crates/ide-completion/src/completions/item_list.rs @@ -80,7 +80,7 @@ fn add_keywords(acc: &mut Completions, ctx: &CompletionContext<'_>, kind: Option let in_trait_impl = matches!(kind, Some(ItemListKind::TraitImpl(_))); let in_inherent_impl = matches!(kind, Some(ItemListKind::Impl)); let no_qualifiers = ctx.qualifier_ctx.vis_node.is_none(); - let in_block = matches!(kind, None); + let in_block = kind.is_none(); if !in_trait_impl { if ctx.qualifier_ctx.unsafe_tok.is_some() { diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs index cc5221cfccbd..17b8dd8f2b71 100644 --- a/crates/ide-completion/src/context/analysis.rs +++ b/crates/ide-completion/src/context/analysis.rs @@ -1139,8 +1139,7 @@ fn pattern_context_for( pat .syntax() .ancestors() - .skip_while(|it| ast::Pat::can_cast(it.kind())) - .next() + .find(|it| !ast::Pat::can_cast(it.kind())) .map_or((PatternRefutability::Irrefutable, false), |node| { let refutability = match_ast! { match node { @@ -1175,7 +1174,7 @@ fn pattern_context_for( .parent() .and_then(ast::MatchExpr::cast) .and_then(|match_expr| { - let expr_opt = find_opt_node_in_file(&original_file, match_expr.expr()); + let expr_opt = find_opt_node_in_file(original_file, match_expr.expr()); expr_opt.and_then(|expr| { sema.type_of_expr(&expr)? @@ -1184,24 +1183,20 @@ fn pattern_context_for( .find_map(|ty| match ty.as_adt() { Some(hir::Adt::Enum(e)) => Some(e), _ => None, - }).and_then(|enum_| { - Some(enum_.variants(sema.db)) - }) + }).map(|enum_| enum_.variants(sema.db)) }) - }).and_then(|variants| { - Some(variants.iter().filter_map(|variant| { + }).map(|variants| variants.iter().filter_map(|variant| { let variant_name = variant.name(sema.db).display(sema.db).to_string(); let variant_already_present = match_arm_list.arms().any(|arm| { arm.pat().and_then(|pat| { let pat_already_present = pat.syntax().to_string().contains(&variant_name); - pat_already_present.then(|| pat_already_present) + pat_already_present.then_some(pat_already_present) }).is_some() }); - (!variant_already_present).then_some(variant.clone()) + (!variant_already_present).then_some(*variant) }).collect::>()) - }) }); if let Some(missing_variants_) = missing_variants_opt { diff --git a/crates/ide-completion/src/item.rs b/crates/ide-completion/src/item.rs index e850f7bfdf3f..4956ae9eb2d8 100644 --- a/crates/ide-completion/src/item.rs +++ b/crates/ide-completion/src/item.rs @@ -516,7 +516,7 @@ impl 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.splitn(2, '\n').next().unwrap().to_string()); + self.detail = Some(detail.split('\n').next().unwrap().to_string()); } } self diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index 1953eb479577..4093d14f8427 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -256,12 +256,9 @@ fn render_resolution_pat( let _p = profile::span("render_resolution"); use hir::ModuleDef::*; - match resolution { - ScopeDef::ModuleDef(Macro(mac)) => { - let ctx = ctx.import_to_add(import_to_add); - return render_macro_pat(ctx, pattern_ctx, local_name, mac); - } - _ => (), + if let ScopeDef::ModuleDef(Macro(mac)) = resolution { + let ctx = ctx.import_to_add(import_to_add); + return render_macro_pat(ctx, pattern_ctx, local_name, mac); } render_resolution_simple_(ctx, &local_name, import_to_add, resolution) diff --git a/crates/ide-completion/src/render/function.rs b/crates/ide-completion/src/render/function.rs index 8afce8db5ea8..89c3e3b84df4 100644 --- a/crates/ide-completion/src/render/function.rs +++ b/crates/ide-completion/src/render/function.rs @@ -103,42 +103,30 @@ fn render( .detail(detail(db, func)) .lookup_by(name.unescaped().to_smol_str()); - match ctx.completion.config.snippet_cap { - Some(cap) => { - let complete_params = match func_kind { - FuncKind::Function(PathCompletionCtx { - kind: PathKind::Expr { .. }, - has_call_parens: false, + if let Some(cap) = ctx.completion.config.snippet_cap { + let complete_params = match func_kind { + FuncKind::Function(PathCompletionCtx { + kind: PathKind::Expr { .. }, + has_call_parens: false, + .. + }) => Some(false), + FuncKind::Method( + DotAccess { + kind: DotAccessKind::Method { has_parens: false } | DotAccessKind::Field { .. }, .. - }) => Some(false), - FuncKind::Method( - DotAccess { - kind: - DotAccessKind::Method { has_parens: false } | DotAccessKind::Field { .. }, - .. - }, - _, - ) => Some(true), - _ => None, - }; - if let Some(has_dot_receiver) = complete_params { - if let Some((self_param, params)) = - params(ctx.completion, func, &func_kind, has_dot_receiver) - { - add_call_parens( - &mut item, - completion, - cap, - call, - escaped_call, - self_param, - params, - ); - } + }, + _, + ) => Some(true), + _ => None, + }; + if let Some(has_dot_receiver) = complete_params { + if let Some((self_param, params)) = + params(ctx.completion, func, &func_kind, has_dot_receiver) + { + add_call_parens(&mut item, completion, cap, call, escaped_call, self_param, params); } } - _ => (), - }; + } match ctx.import_to_add { Some(import_to_add) => { diff --git a/crates/ide-completion/src/render/literal.rs b/crates/ide-completion/src/render/literal.rs index 728d236dff47..63b2feebe2dc 100644 --- a/crates/ide-completion/src/render/literal.rs +++ b/crates/ide-completion/src/render/literal.rs @@ -54,11 +54,11 @@ fn render( ) -> Option { let db = completion.db; let mut kind = thing.kind(db); - let should_add_parens = match &path_ctx { - PathCompletionCtx { has_call_parens: true, .. } => false, - PathCompletionCtx { kind: PathKind::Use | PathKind::Type { .. }, .. } => false, - _ => true, - }; + let should_add_parens = !matches!( + path_ctx, + PathCompletionCtx { has_call_parens: true, .. } + | PathCompletionCtx { kind: PathKind::Use | PathKind::Type { .. }, .. } + ); let fields = thing.fields(completion)?; let (qualified_name, short_qualified_name, qualified) = match path { diff --git a/crates/ide-completion/src/render/macro_.rs b/crates/ide-completion/src/render/macro_.rs index ce7af1d3400e..d3b78cd63026 100644 --- a/crates/ide-completion/src/render/macro_.rs +++ b/crates/ide-completion/src/render/macro_.rs @@ -94,7 +94,7 @@ fn label( ) -> SmolStr { if needs_bang { if ctx.snippet_cap().is_some() { - SmolStr::from_iter([&*name, "!", bra, "…", ket]) + SmolStr::from_iter([name, "!", bra, "…", ket]) } else { banged_name(name) } diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs index 2464e8d5f817..5044e07c1c38 100644 --- a/crates/ide-completion/src/tests.rs +++ b/crates/ide-completion/src/tests.rs @@ -202,7 +202,7 @@ pub(crate) fn check_edit_with_config( .import_to_add .iter() .cloned() - .filter_map(|(import_path, import_name)| Some((import_path, import_name))), + .map(|(import_path, import_name)| (import_path, import_name)), ) .into_iter() .flatten() diff --git a/crates/ide-db/src/active_parameter.rs b/crates/ide-db/src/active_parameter.rs index 0da4e729a8dd..5780b5a5bb93 100644 --- a/crates/ide-db/src/active_parameter.rs +++ b/crates/ide-db/src/active_parameter.rs @@ -23,7 +23,7 @@ impl ActiveParameter { let idx = active_parameter?; let mut params = signature.params(sema.db); - if !(idx < params.len()) { + if idx >= params.len() { cov_mark::hit!(too_many_arguments); return None; } @@ -66,19 +66,15 @@ pub fn callable_for_node( } ast::CallableExpr::MethodCall(call) => sema.resolve_method_call_as_callable(call), }?; - let active_param = if let Some(arg_list) = calling_node.arg_list() { - Some( - arg_list - .syntax() - .children_with_tokens() - .filter_map(NodeOrToken::into_token) - .filter(|t| t.kind() == T![,]) - .take_while(|t| t.text_range().start() <= token.text_range().start()) - .count(), - ) - } else { - None - }; + let active_param = calling_node.arg_list().map(|arg_list| { + arg_list + .syntax() + .children_with_tokens() + .filter_map(NodeOrToken::into_token) + .filter(|t| t.kind() == T![,]) + .take_while(|t| t.text_range().start() <= token.text_range().start()) + .count() + }); Some((callable, active_param)) } diff --git a/crates/ide-db/src/items_locator.rs b/crates/ide-db/src/items_locator.rs index 46f1353e2e1b..3592c09f2da7 100644 --- a/crates/ide-db/src/items_locator.rs +++ b/crates/ide-db/src/items_locator.rs @@ -112,9 +112,9 @@ fn find_items<'a>( let local_results = local_query .search(&symbol_index::crate_symbols(db, krate)) .into_iter() - .filter_map(|local_candidate| match local_candidate.def { - hir::ModuleDef::Macro(macro_def) => Some(ItemInNs::Macros(macro_def)), - def => Some(ItemInNs::from(def)), + .map(|local_candidate| match local_candidate.def { + hir::ModuleDef::Macro(macro_def) => ItemInNs::Macros(macro_def), + def => ItemInNs::from(def), }); external_importables.chain(local_results).filter(move |&item| match assoc_item_search { diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index ff1a20f03f44..3258c1cf9ad2 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -95,19 +95,19 @@ impl fmt::Debug for RootDatabase { impl Upcast for RootDatabase { fn upcast(&self) -> &(dyn ExpandDatabase + 'static) { - &*self + self } } impl Upcast for RootDatabase { fn upcast(&self) -> &(dyn DefDatabase + 'static) { - &*self + self } } impl Upcast for RootDatabase { fn upcast(&self) -> &(dyn HirDatabase + 'static) { - &*self + self } } diff --git a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs index 72af9ebfcbb6..c2846ed09289 100644 --- a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs +++ b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs @@ -8,7 +8,7 @@ use crate::{Diagnostic, DiagnosticsContext, Severity}; pub(crate) fn incoherent_impl(ctx: &DiagnosticsContext<'_>, d: &hir::IncoherentImpl) -> Diagnostic { Diagnostic::new( "incoherent-impl", - format!("cannot define inherent `impl` for foreign type"), + "cannot define inherent `impl` for foreign type".to_string(), ctx.sema.diagnostics_display_range(InFile::new(d.file_id, d.impl_.clone().into())).range, ) .severity(Severity::Error) diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index 60ccc41df01c..6f148effd0b9 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -102,7 +102,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option make::ext::expr_todo(), crate::ExprFillDefaultMode::Default => { - get_default_constructor(ctx, d, ty).unwrap_or_else(|| make::ext::expr_todo()) + get_default_constructor(ctx, d, ty).unwrap_or_else(make::ext::expr_todo) } }; diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs index c28f98d8333e..9e6c36ce910e 100644 --- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -183,7 +183,7 @@ fn str_ref_to_owned( let expr = expr_ptr.value.to_node(&root); let expr_range = expr.syntax().text_range(); - let to_owned = format!(".to_owned()"); + let to_owned = ".to_owned()".to_string(); let edit = TextEdit::insert(expr.syntax().text_range().end(), to_owned); let source_change = diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs index 55a4a482d3b2..48c109299889 100644 --- a/crates/ide-diagnostics/src/lib.rs +++ b/crates/ide-diagnostics/src/lib.rs @@ -310,8 +310,8 @@ pub fn diagnostics( } res.retain(|d| { - !ctx.config.disabled.contains(d.code.as_str()) - && !(ctx.config.disable_experimental && d.experimental) + !(ctx.config.disabled.contains(d.code.as_str()) + || ctx.config.disable_experimental && d.experimental) }); res diff --git a/crates/ide-ssr/src/fragments.rs b/crates/ide-ssr/src/fragments.rs index 503754afe7c2..4d6809efbe19 100644 --- a/crates/ide-ssr/src/fragments.rs +++ b/crates/ide-ssr/src/fragments.rs @@ -35,7 +35,9 @@ pub(crate) fn stmt(s: &str) -> Result { parse.tree().syntax().descendants().skip(2).find_map(ast::Stmt::cast).ok_or(())?; if !s.ends_with(';') && node.to_string().ends_with(';') { node = node.clone_for_update(); - node.syntax().last_token().map(|it| it.detach()); + if let Some(it) = node.syntax().last_token() { + it.detach() + } } if node.to_string() != s { return Err(()); diff --git a/crates/ide-ssr/src/matching.rs b/crates/ide-ssr/src/matching.rs index a8e883690883..edb724b03131 100644 --- a/crates/ide-ssr/src/matching.rs +++ b/crates/ide-ssr/src/matching.rs @@ -310,6 +310,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> { Ok(()) } + #[allow(clippy::only_used_in_recursion)] fn check_constraint( &self, constraint: &Constraint, @@ -320,7 +321,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> { kind.matches(code)?; } Constraint::Not(sub) => { - if self.check_constraint(&*sub, code).is_ok() { + if self.check_constraint(sub, code).is_ok() { fail_match!("Constraint {:?} failed for '{}'", constraint, code.text()); } } @@ -762,12 +763,7 @@ impl Iterator for PatternIterator { type Item = SyntaxElement; fn next(&mut self) -> Option { - for element in &mut self.iter { - if !element.kind().is_trivia() { - return Some(element); - } - } - None + self.iter.by_ref().find(|element| !element.kind().is_trivia()) } } diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index f994c284c713..fb79b5dc211a 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -94,10 +94,9 @@ pub(crate) fn annotations( enum_ .variants(db) .into_iter() - .map(|variant| { + .filter_map(|variant| { variant.source(db).and_then(|node| name_range(db, node, file_id)) }) - .flatten() .for_each(|range| { let (annotation_range, target_position) = mk_ranges(range); annotations.push(Annotation { diff --git a/crates/ide/src/annotations/fn_references.rs b/crates/ide/src/annotations/fn_references.rs index 0cadf125feca..a090b60413eb 100644 --- a/crates/ide/src/annotations/fn_references.rs +++ b/crates/ide/src/annotations/fn_references.rs @@ -14,7 +14,7 @@ pub(super) fn find_all_methods( ) -> Vec<(TextRange, Option)> { let sema = Semantics::new(db); let source_file = sema.parse(file_id); - source_file.syntax().descendants().filter_map(|it| method_range(it)).collect() + source_file.syntax().descendants().filter_map(method_range).collect() } fn method_range(item: SyntaxNode) -> Option<(TextRange, Option)> { diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 8112c4f7259c..91f0db943ac0 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -342,8 +342,12 @@ fn get_doc_links( web_url = join_url(web_url, &file); local_url = join_url(local_url, &file); - web_url.as_mut().map(|url| url.set_fragment(frag.as_deref())); - local_url.as_mut().map(|url| url.set_fragment(frag.as_deref())); + if let Some(url) = web_url.as_mut() { + url.set_fragment(frag.as_deref()); + } + if let Some(url) = local_url.as_mut() { + url.set_fragment(frag.as_deref()); + } DocumentationLinks { web_url: web_url.map(|it| it.into()), diff --git a/crates/ide/src/doc_links/tests.rs b/crates/ide/src/doc_links/tests.rs index 05a64b33bfdc..ddacbbac53e9 100644 --- a/crates/ide/src/doc_links/tests.rs +++ b/crates/ide/src/doc_links/tests.rs @@ -28,9 +28,6 @@ fn check_external_docs( let web_url = links.web_url; let local_url = links.local_url; - println!("web_url: {:?}", web_url); - println!("local_url: {:?}", local_url); - match (expect_web_url, web_url) { (Some(expect), Some(url)) => expect.assert_eq(&url), (None, None) => (), @@ -127,10 +124,10 @@ fn external_docs_doc_builtin_type() { //- /main.rs crate:foo let x: u3$02 = 0; "#, - Some(&OsStr::new("/home/user/project")), + Some(OsStr::new("/home/user/project")), Some(expect![[r#"https://doc.rust-lang.org/nightly/core/primitive.u32.html"#]]), Some(expect![[r#"file:///sysroot/share/doc/rust/html/core/primitive.u32.html"#]]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } @@ -143,10 +140,10 @@ use foo$0::Foo; //- /lib.rs crate:foo pub struct Foo; "#, - Some(&OsStr::new("/home/user/project")), + Some(OsStr::new("/home/user/project")), Some(expect![[r#"https://docs.rs/foo/*/foo/index.html"#]]), Some(expect![[r#"file:///home/user/project/doc/foo/index.html"#]]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } @@ -157,10 +154,10 @@ fn external_docs_doc_url_std_crate() { //- /main.rs crate:std use self$0; "#, - Some(&OsStr::new("/home/user/project")), + Some(OsStr::new("/home/user/project")), Some(expect!["https://doc.rust-lang.org/stable/std/index.html"]), Some(expect!["file:///sysroot/share/doc/rust/html/std/index.html"]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } @@ -171,10 +168,10 @@ fn external_docs_doc_url_struct() { //- /main.rs crate:foo pub struct Fo$0o; "#, - Some(&OsStr::new("/home/user/project")), + Some(OsStr::new("/home/user/project")), Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]), Some(expect![[r#"file:///home/user/project/doc/foo/struct.Foo.html"#]]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } @@ -185,10 +182,10 @@ fn external_docs_doc_url_windows_backslash_path() { //- /main.rs crate:foo pub struct Fo$0o; "#, - Some(&OsStr::new(r"C:\Users\user\project")), + Some(OsStr::new(r"C:\Users\user\project")), Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]), Some(expect![[r#"file:///C:/Users/user/project/doc/foo/struct.Foo.html"#]]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } @@ -199,10 +196,10 @@ fn external_docs_doc_url_windows_slash_path() { //- /main.rs crate:foo pub struct Fo$0o; "#, - Some(&OsStr::new(r"C:/Users/user/project")), + Some(OsStr::new(r"C:/Users/user/project")), Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]), Some(expect![[r#"file:///C:/Users/user/project/doc/foo/struct.Foo.html"#]]), - Some(&OsStr::new("/sysroot")), + Some(OsStr::new("/sysroot")), ); } diff --git a/crates/ide/src/fetch_crates.rs b/crates/ide/src/fetch_crates.rs index 46ee671defbc..14c2655f84d2 100644 --- a/crates/ide/src/fetch_crates.rs +++ b/crates/ide/src/fetch_crates.rs @@ -27,7 +27,7 @@ pub(crate) fn fetch_crates(db: &RootDatabase) -> FxIndexSet { .iter() .map(|crate_id| &crate_graph[crate_id]) .filter(|&data| !matches!(data.origin, CrateOrigin::Local { .. })) - .map(|data| crate_info(data)) + .map(crate_info) .collect() } diff --git a/crates/ide/src/folding_ranges.rs b/crates/ide/src/folding_ranges.rs index c694d95d537f..e2b4cfe027a6 100755 --- a/crates/ide/src/folding_ranges.rs +++ b/crates/ide/src/folding_ranges.rs @@ -220,6 +220,7 @@ fn contiguous_range_for_comment( return None; } + #[allow(clippy::redundant_clone)] // false positive let mut last = first.clone(); for element in first.syntax().siblings_with_tokens(Direction::Next) { match element { @@ -271,7 +272,7 @@ fn fold_range_for_where_clause(where_clause: ast::WhereClause) -> Option Option { - if let Some(_) = fold_kind(match_arm.expr()?.syntax().kind()) { + if fold_kind(match_arm.expr()?.syntax().kind()).is_some() { return None; } if match_arm.expr()?.syntax().text().contains_char('\n') { diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index 7e545491f8e7..cf7a7cc7bb00 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -462,8 +462,7 @@ fn find_defs(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> FxHashSe sema.descend_into_macros(token) .into_iter() .filter_map(|token| IdentClass::classify_token(sema, &token)) - .map(IdentClass::definitions_no_ops) - .flatten() + .flat_map(IdentClass::definitions_no_ops) .collect() } diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index 1362146413e0..f8bc64ae9c9e 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -127,7 +127,7 @@ pub(super) fn try_expr( let l = "Propagated as: ".len() - " Type: ".len(); let static_text_len_diff = l as isize - s.len() as isize; let tpad = static_text_len_diff.max(0) as usize; - let ppad = static_text_len_diff.min(0).abs() as usize; + let ppad = static_text_len_diff.min(0).unsigned_abs(); res.markup = format!( "```text\n{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n```\n", @@ -337,7 +337,7 @@ pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option, config: &InlayHintsConfig, ) -> Result<(), HirDisplayError> { - let iter_item_type = hint_iterator(sema, famous_defs, &ty); + let iter_item_type = hint_iterator(sema, famous_defs, ty); match iter_item_type { Some((iter_trait, item, ty)) => { const LABEL_START: &str = "impl "; diff --git a/crates/ide/src/inlay_hints/discriminant.rs b/crates/ide/src/inlay_hints/discriminant.rs index c4d2ac75cfa9..202954100fb9 100644 --- a/crates/ide/src/inlay_hints/discriminant.rs +++ b/crates/ide/src/inlay_hints/discriminant.rs @@ -74,7 +74,7 @@ fn variant_hints( }, Some(InlayTooltip::String(match &d { Ok(_) => "enum variant discriminant".into(), - Err(e) => format!("{e:?}").into(), + Err(e) => format!("{e:?}"), })), None, ); diff --git a/crates/ide/src/inlay_hints/fn_lifetime_fn.rs b/crates/ide/src/inlay_hints/fn_lifetime_fn.rs index 5fce11b785a7..3b196e0922b9 100644 --- a/crates/ide/src/inlay_hints/fn_lifetime_fn.rs +++ b/crates/ide/src/inlay_hints/fn_lifetime_fn.rs @@ -97,15 +97,13 @@ pub(super) fn hints( }; { let mut potential_lt_refs = potential_lt_refs.iter().filter(|&&(.., is_elided)| is_elided); - if let Some(_) = &self_param { - if let Some(_) = potential_lt_refs.next() { - allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints { - // self can't be used as a lifetime, so no need to check for collisions - "'self".into() - } else { - gen_idx_name() - }); - } + if self_param.is_some() && potential_lt_refs.next().is_some() { + allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints { + // self can't be used as a lifetime, so no need to check for collisions + "'self".into() + } else { + gen_idx_name() + }); } potential_lt_refs.for_each(|(name, ..)| { let name = match name { diff --git a/crates/ide/src/inlay_hints/param_name.rs b/crates/ide/src/inlay_hints/param_name.rs index c4f43f411753..96e845b2f323 100644 --- a/crates/ide/src/inlay_hints/param_name.rs +++ b/crates/ide/src/inlay_hints/param_name.rs @@ -47,7 +47,7 @@ pub(super) fn hints( if let Some(name) = param { if let hir::CallableKind::Function(f) = callable.kind() { // assert the file is cached so we can map out of macros - if let Some(_) = sema.source(f) { + if sema.source(f).is_some() { linked_location = sema.original_range_opt(name.syntax()); } } diff --git a/crates/ide/src/interpret_function.rs b/crates/ide/src/interpret_function.rs index cbcbb4b09db4..846d70ac307f 100644 --- a/crates/ide/src/interpret_function.rs +++ b/crates/ide/src/interpret_function.rs @@ -18,7 +18,7 @@ pub(crate) fn interpret_function(db: &RootDatabase, position: FilePosition) -> S let mut result = find_and_interpret(db, position) .unwrap_or_else(|| "Not inside a function body".to_string()); let duration = Instant::now() - start_time; - writeln!(result, "").unwrap(); + writeln!(result).unwrap(); writeln!(result, "----------------------").unwrap(); writeln!(result, " Finished in {}s", duration.as_secs_f32()).unwrap(); result diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index f195f78b3ab8..29c4ff5701f9 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -259,7 +259,7 @@ impl Analysis { /// Debug info about the current state of the analysis. pub fn status(&self, file_id: Option) -> Cancellable { - self.with_db(|db| status::status(&*db, file_id)) + self.with_db(|db| status::status(db, file_id)) } pub fn parallel_prime_caches(&self, num_worker_threads: u8, cb: F) -> Cancellable<()> @@ -338,7 +338,7 @@ impl Analysis { } pub fn fetch_crates(&self) -> Cancellable> { - self.with_db(|db| fetch_crates::fetch_crates(db)) + self.with_db(fetch_crates::fetch_crates) } pub fn expand_macro(&self, position: FilePosition) -> Cancellable> { diff --git a/crates/ide/src/moniker.rs b/crates/ide/src/moniker.rs index 0d57e63d29c9..42d8e50ad2b8 100644 --- a/crates/ide/src/moniker.rs +++ b/crates/ide/src/moniker.rs @@ -39,11 +39,8 @@ pub struct MonikerIdentifier { impl ToString for MonikerIdentifier { fn to_string(&self) -> String { - match self { - MonikerIdentifier { description, crate_name } => { - format!("{}::{}", crate_name, description.iter().map(|x| &x.name).join("::")) - } - } + let MonikerIdentifier { description, crate_name } = self; + format!("{}::{}", crate_name, description.iter().map(|x| &x.name).join("::")) } } diff --git a/crates/ide/src/signature_help.rs b/crates/ide/src/signature_help.rs index 7795be54e264..5c7c2c64f361 100644 --- a/crates/ide/src/signature_help.rs +++ b/crates/ide/src/signature_help.rs @@ -633,7 +633,7 @@ fn signature_help_for_tuple_pat_ish( res.push_call_param(&buf); buf.clear(); } - res.signature.push_str(")"); + res.signature.push(')'); res } #[cfg(test)] diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs index 8c02fe81648a..493d29926609 100644 --- a/crates/ide/src/syntax_highlighting.rs +++ b/crates/ide/src/syntax_highlighting.rs @@ -275,8 +275,8 @@ fn traverse( inside_attribute = false } - Enter(NodeOrToken::Node(node)) => match ast::Item::cast(node.clone()) { - Some(item) => { + Enter(NodeOrToken::Node(node)) => { + if let Some(item) = ast::Item::cast(node.clone()) { match item { ast::Item::MacroRules(mac) => { macro_highlighter.init(); @@ -317,8 +317,7 @@ fn traverse( } } } - _ => (), - }, + } Leave(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => { match ast::Item::cast(node.clone()) { Some(ast::Item::MacroRules(mac)) => { diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs index c7e403f6b1ab..51445ef255b5 100644 --- a/crates/ide/src/typing.rs +++ b/crates/ide/src/typing.rs @@ -342,12 +342,9 @@ fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option".to_string()), is_snippet: true, diff --git a/crates/ide/src/view_crate_graph.rs b/crates/ide/src/view_crate_graph.rs index 8c84461f659f..727012112ebd 100644 --- a/crates/ide/src/view_crate_graph.rs +++ b/crates/ide/src/view_crate_graph.rs @@ -86,7 +86,7 @@ impl<'a> dot::Labeller<'a, CrateId, Edge<'a>> for DotCrateGraph { } fn node_label(&'a self, n: &CrateId) -> LabelText<'a> { - let name = self.graph[*n].display_name.as_ref().map_or("(unnamed crate)", |name| &*name); + let name = self.graph[*n].display_name.as_ref().map_or("(unnamed crate)", |name| name); LabelText::LabelStr(name.into()) } } diff --git a/crates/intern/src/lib.rs b/crates/intern/src/lib.rs index dabbf3a38b50..51f3506849dd 100644 --- a/crates/intern/src/lib.rs +++ b/crates/intern/src/lib.rs @@ -33,13 +33,10 @@ impl Interned { // - if not, box it up, insert it, and return a clone // This needs to be atomic (locking the shard) to avoid races with other thread, which could // insert the same object between us looking it up and inserting it. - match shard.raw_entry_mut().from_key_hashed_nocheck(hash as u64, &obj) { + match shard.raw_entry_mut().from_key_hashed_nocheck(hash, &obj) { RawEntryMut::Occupied(occ) => Self { arc: occ.key().clone() }, RawEntryMut::Vacant(vac) => Self { - arc: vac - .insert_hashed_nocheck(hash as u64, Arc::new(obj), SharedValue::new(())) - .0 - .clone(), + arc: vac.insert_hashed_nocheck(hash, Arc::new(obj), SharedValue::new(())).0.clone(), }, } } @@ -54,13 +51,10 @@ impl Interned { // - if not, box it up, insert it, and return a clone // This needs to be atomic (locking the shard) to avoid races with other thread, which could // insert the same object between us looking it up and inserting it. - match shard.raw_entry_mut().from_key_hashed_nocheck(hash as u64, s) { + match shard.raw_entry_mut().from_key_hashed_nocheck(hash, s) { RawEntryMut::Occupied(occ) => Self { arc: occ.key().clone() }, RawEntryMut::Vacant(vac) => Self { - arc: vac - .insert_hashed_nocheck(hash as u64, Arc::from(s), SharedValue::new(())) - .0 - .clone(), + arc: vac.insert_hashed_nocheck(hash, Arc::from(s), SharedValue::new(())).0.clone(), }, } } diff --git a/crates/mbe/src/expander/transcriber.rs b/crates/mbe/src/expander/transcriber.rs index 6161af185871..b88508b60599 100644 --- a/crates/mbe/src/expander/transcriber.rs +++ b/crates/mbe/src/expander/transcriber.rs @@ -414,16 +414,16 @@ fn push_subtree(buf: &mut Vec, tt: tt::Subtree) { /// Handles `${count(t, depth)}`. `our_depth` is the recursion depth and `count_depth` is the depth /// defined by the metavar expression. fn count( - ctx: &ExpandCtx<'_>, + _ctx: &ExpandCtx<'_>, binding: &Binding, our_depth: usize, count_depth: Option, ) -> Result { match binding { Binding::Nested(bs) => match count_depth { - None => bs.iter().map(|b| count(ctx, b, our_depth + 1, None)).sum(), + None => bs.iter().map(|b| count(_ctx, b, our_depth + 1, None)).sum(), Some(0) => Ok(bs.len()), - Some(d) => bs.iter().map(|b| count(ctx, b, our_depth + 1, Some(d - 1))).sum(), + Some(d) => bs.iter().map(|b| count(_ctx, b, our_depth + 1, Some(d - 1))).sum(), }, Binding::Empty => Ok(0), Binding::Fragment(_) | Binding::Missing(_) => { diff --git a/crates/mbe/src/syntax_bridge.rs b/crates/mbe/src/syntax_bridge.rs index 8cbf0f8fc0bd..f301f6fef5ee 100644 --- a/crates/mbe/src/syntax_bridge.rs +++ b/crates/mbe/src/syntax_bridge.rs @@ -619,9 +619,8 @@ impl Converter { return (None, v); } } - match ele { - SyntaxElement::Token(t) => return (Some(t), Vec::new()), - _ => {} + if let SyntaxElement::Token(t) = ele { + return (Some(t), Vec::new()); } } (None, Vec::new()) diff --git a/crates/proc-macro-api/src/msg.rs b/crates/proc-macro-api/src/msg.rs index 4b01643c2a29..cb7e7f3b2cd5 100644 --- a/crates/proc-macro-api/src/msg.rs +++ b/crates/proc-macro-api/src/msg.rs @@ -19,6 +19,7 @@ pub const ENCODE_CLOSE_SPAN_VERSION: u32 = 2; pub const CURRENT_API_VERSION: u32 = ENCODE_CLOSE_SPAN_VERSION; +#[allow(clippy::large_enum_variant)] #[derive(Debug, Serialize, Deserialize)] pub enum Request { ListMacros { dylib_path: PathBuf }, diff --git a/crates/proc-macro-test/imp/src/lib.rs b/crates/proc-macro-test/imp/src/lib.rs index feeacdb6407a..782a1d2d8a51 100644 --- a/crates/proc-macro-test/imp/src/lib.rs +++ b/crates/proc-macro-test/imp/src/lib.rs @@ -1,6 +1,7 @@ //! Exports a few trivial procedural macros for testing. #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)] +#![allow(clippy::all)] use proc_macro::{Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs index 92b454150c3e..d767a82166ff 100644 --- a/crates/project-model/src/cargo_workspace.rs +++ b/crates/project-model/src/cargo_workspace.rs @@ -275,7 +275,7 @@ impl CargoWorkspace { other_options.append( &mut targets .into_iter() - .flat_map(|target| ["--filter-platform".to_owned().to_string(), target]) + .flat_map(|target| ["--filter-platform".to_owned(), target]) .collect(), ); } @@ -366,7 +366,7 @@ impl CargoWorkspace { name, root: AbsPathBuf::assert(src_path.into()), kind: TargetKind::new(&kind), - is_proc_macro: &*kind == ["proc-macro"], + is_proc_macro: *kind == ["proc-macro"], required_features, }); pkg_data.targets.push(tgt); @@ -439,7 +439,7 @@ impl CargoWorkspace { .collect::>(); // some packages has this pkg as dep. return their manifests - if parent_manifests.len() > 0 { + if !parent_manifests.is_empty() { return Some(parent_manifests); } diff --git a/crates/project-model/src/manifest_path.rs b/crates/project-model/src/manifest_path.rs index 3f60e4dd92f4..5b2266d6ddc1 100644 --- a/crates/project-model/src/manifest_path.rs +++ b/crates/project-model/src/manifest_path.rs @@ -36,7 +36,7 @@ impl ManifestPath { } pub fn canonicalize(&self) -> ! { - (&**self).canonicalize() + (**self).canonicalize() } } diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs index 7815b9dda77f..34e5a4173400 100644 --- a/crates/project-model/src/tests.rs +++ b/crates/project-model/src/tests.rs @@ -106,7 +106,7 @@ fn replace_fake_sys_root(s: &mut String) { let fake_sysroot_path = get_test_path("fake-sysroot"); let fake_sysroot_path = if cfg!(windows) { let normalized_path = - fake_sysroot_path.to_str().expect("expected str").replace(r#"\"#, r#"\\"#); + fake_sysroot_path.to_str().expect("expected str").replace('\\', r#"\\"#); format!(r#"{}\\"#, normalized_path) } else { format!("{}/", fake_sysroot_path.to_str().expect("expected str")) diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs index 0aca620a6755..a085ebbb282e 100644 --- a/crates/project-model/src/workspace.rs +++ b/crates/project-model/src/workspace.rs @@ -2,7 +2,7 @@ //! metadata` or `rust-project.json`) into representation stored in the salsa //! database -- `CrateGraph`. -use std::{collections::VecDeque, fmt, fs, process::Command, sync}; +use std::{collections::VecDeque, fmt, fs, process::Command, str::FromStr, sync}; use anyhow::{format_err, Context, Result}; use base_db::{ @@ -38,7 +38,7 @@ pub struct CfgOverrides { impl CfgOverrides { pub fn len(&self) -> usize { - self.global.len() + self.selective.iter().map(|(_, it)| it.len()).sum::() + self.global.len() + self.selective.values().map(|it| it.len()).sum::() } } @@ -53,6 +53,7 @@ pub struct PackageRoot { pub exclude: Vec, } +#[allow(clippy::large_enum_variant)] #[derive(Clone)] pub enum ProjectWorkspace { /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`. @@ -608,7 +609,9 @@ impl ProjectWorkspace { sysroot.as_ref().ok(), extra_env, Err("rust-project.json projects have no target layout set".into()), - toolchain.as_ref().and_then(|it| ReleaseChannel::from_str(it.pre.as_str())), + toolchain + .as_ref() + .and_then(|it| ReleaseChannel::from_str(it.pre.as_str()).ok()), ) } ProjectWorkspace::Cargo { @@ -633,7 +636,7 @@ impl ProjectWorkspace { Ok(it) => Ok(Arc::from(it.as_str())), Err(it) => Err(Arc::from(it.as_str())), }, - toolchain.as_ref().and_then(|it| ReleaseChannel::from_str(it.pre.as_str())), + toolchain.as_ref().and_then(|it| ReleaseChannel::from_str(it.pre.as_str()).ok()), ), ProjectWorkspace::DetachedFiles { files, sysroot, rustc_cfg } => { detached_files_to_crate_graph( diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 91911dd18096..1947a5a82b5c 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs @@ -17,7 +17,7 @@ use lsp_server::Connection; use rust_analyzer::{cli::flags, config::Config, from_json, Result}; use vfs::AbsPathBuf; -#[cfg(all(feature = "mimalloc"))] +#[cfg(feature = "mimalloc")] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 2c2a9a18d2e3..823a211c6e28 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -54,10 +54,12 @@ impl flags::AnalysisStats { Rand32::new(seed) }; - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = match self.no_sysroot { - true => None, - false => Some(RustLibSource::Discover), + let cargo_config = CargoConfig { + sysroot: match self.no_sysroot { + true => None, + false => Some(RustLibSource::Discover), + }, + ..Default::default() }; let no_progress = &|_| (); @@ -210,7 +212,7 @@ impl flags::AnalysisStats { continue; } all += 1; - let Err(e) = db.layout_of_adt(hir_def::AdtId::from(a).into(), Substitution::empty(Interner), a.krate(db).into()) else { + let Err(e) = db.layout_of_adt(hir_def::AdtId::from(a), Substitution::empty(Interner), a.krate(db).into()) else { continue; }; if verbosity.is_spammy() { diff --git a/crates/rust-analyzer/src/cli/diagnostics.rs b/crates/rust-analyzer/src/cli/diagnostics.rs index 4006d023def5..909b10d2eb8e 100644 --- a/crates/rust-analyzer/src/cli/diagnostics.rs +++ b/crates/rust-analyzer/src/cli/diagnostics.rs @@ -15,8 +15,8 @@ use crate::cli::{ impl flags::Diagnostics { pub fn run(self) -> anyhow::Result<()> { - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: !self.disable_build_scripts, with_proc_macro_server: ProcMacroServerChoice::Sysroot, diff --git a/crates/rust-analyzer/src/cli/lsif.rs b/crates/rust-analyzer/src/cli/lsif.rs index 7f5d08449671..e3fc29cfb604 100644 --- a/crates/rust-analyzer/src/cli/lsif.rs +++ b/crates/rust-analyzer/src/cli/lsif.rs @@ -289,8 +289,8 @@ impl flags::Lsif { pub fn run(self) -> Result<()> { eprintln!("Generating LSIF started..."); let now = Instant::now(); - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let no_progress = &|_| (); let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, diff --git a/crates/rust-analyzer/src/cli/scip.rs b/crates/rust-analyzer/src/cli/scip.rs index b0b724bdfe73..2d318bbec5b9 100644 --- a/crates/rust-analyzer/src/cli/scip.rs +++ b/crates/rust-analyzer/src/cli/scip.rs @@ -29,8 +29,8 @@ impl flags::Scip { pub fn run(self) -> Result<()> { eprintln!("Generating SCIP start..."); let now = Instant::now(); - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let no_progress = &|s| (eprintln!("rust-analyzer: Loading {s}")); let load_cargo_config = LoadCargoConfig { @@ -214,7 +214,7 @@ fn new_descriptor(name: &str, suffix: scip_types::descriptor::Suffix) -> scip_ty if name.contains('\'') { new_descriptor_str(&format!("`{name}`"), suffix) } else { - new_descriptor_str(&name, suffix) + new_descriptor_str(name, suffix) } } @@ -305,7 +305,7 @@ mod test { } } - if expected == "" { + if expected.is_empty() { assert!(found_symbol.is_none(), "must have no symbols {found_symbol:?}"); return; } diff --git a/crates/rust-analyzer/src/cli/ssr.rs b/crates/rust-analyzer/src/cli/ssr.rs index 82a769347df0..4b064a459cca 100644 --- a/crates/rust-analyzer/src/cli/ssr.rs +++ b/crates/rust-analyzer/src/cli/ssr.rs @@ -12,8 +12,8 @@ use crate::cli::{ impl flags::Ssr { pub fn run(self) -> Result<()> { use ide_db::base_db::SourceDatabaseExt; - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, with_proc_macro_server: ProcMacroServerChoice::Sysroot, diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 6355c620f780..c3ea7939a4d8 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -1125,12 +1125,12 @@ impl Config { } pub fn lru_query_capacities(&self) -> Option<&FxHashMap, usize>> { - self.data.lru_query_capacities.is_empty().not().then(|| &self.data.lru_query_capacities) + self.data.lru_query_capacities.is_empty().not().then_some(&self.data.lru_query_capacities) } pub fn proc_macro_srv(&self) -> Option { let path = self.data.procMacro_server.clone()?; - Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(&path))) + Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path))) } pub fn dummy_replacements(&self) -> &FxHashMap, Box<[Box]>> { @@ -1635,7 +1635,7 @@ impl Config { } pub fn main_loop_num_threads(&self) -> usize { - self.data.numThreads.unwrap_or(num_cpus::get_physical().try_into().unwrap_or(1)) + self.data.numThreads.unwrap_or(num_cpus::get_physical()) } pub fn typing_autoclose_angle(&self) -> bool { @@ -1751,18 +1751,14 @@ mod de_unit_v { #[derive(Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] +#[derive(Default)] enum SnippetScopeDef { + #[default] Expr, Item, Type, } -impl Default for SnippetScopeDef { - fn default() -> Self { - SnippetScopeDef::Expr - } -} - #[derive(Deserialize, Debug, Clone, Default)] #[serde(default)] struct SnippetDef { diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs index 9f4dc4440202..d11e4dfd9105 100644 --- a/crates/rust-analyzer/src/global_state.rs +++ b/crates/rust-analyzer/src/global_state.rs @@ -280,10 +280,10 @@ impl GlobalState { let text = if file.exists() { let bytes = vfs.file_contents(file.file_id).to_vec(); - String::from_utf8(bytes).ok().and_then(|text| { + String::from_utf8(bytes).ok().map(|text| { let (text, line_endings) = LineEndings::normalize(text); line_endings_map.insert(file.file_id, line_endings); - Some(Arc::from(text)) + Arc::from(text) }) } else { None diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs index 09de6900c8fb..7b16c9f1f11e 100644 --- a/crates/rust-analyzer/src/handlers/notification.rs +++ b/crates/rust-analyzer/src/handlers/notification.rs @@ -32,7 +32,7 @@ pub(crate) fn handle_work_done_progress_cancel( ) -> Result<()> { if let lsp_types::NumberOrString::String(s) = ¶ms.token { if let Some(id) = s.strip_prefix("rust-analyzer/flycheck/") { - if let Ok(id) = u32::from_str_radix(id, 10) { + if let Ok(id) = id.parse::() { if let Some(flycheck) = state.flycheck.get(id as usize) { flycheck.cancel(); } diff --git a/crates/rust-analyzer/src/lsp_utils.rs b/crates/rust-analyzer/src/lsp_utils.rs index 74e79e8e6050..c45e2ee22267 100644 --- a/crates/rust-analyzer/src/lsp_utils.rs +++ b/crates/rust-analyzer/src/lsp_utils.rs @@ -287,7 +287,7 @@ mod tests { } let encoding = PositionEncoding::Wide(WideEncoding::Utf16); - let text = apply_document_changes(encoding, || String::new(), vec![]); + let text = apply_document_changes(encoding, String::new, vec![]); assert_eq!(text, ""); let text = apply_document_changes( encoding, diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index 12bc638929d6..5c024ddcfd0b 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -480,7 +480,7 @@ impl GlobalState { if self.config.run_build_scripts() && workspaces_updated { self.fetch_build_data_queue - .request_op(format!("workspace updated"), ()); + .request_op("workspace updated".to_string(), ()); } (Progress::End, None) diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index c875c6ba42bb..9db638f6d68e 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -112,7 +112,7 @@ impl GlobalState { status.health = lsp_ext::Health::Warning; message.push_str("Proc-macros have changed and need to be rebuilt.\n\n"); } - if let Err(_) = self.fetch_build_data_error() { + if self.fetch_build_data_error().is_err() { status.health = lsp_ext::Health::Warning; message.push_str("Failed to run build scripts of some packages.\n\n"); } @@ -171,7 +171,7 @@ impl GlobalState { } } - if let Err(_) = self.fetch_workspace_error() { + if self.fetch_workspace_error().is_err() { status.health = lsp_ext::Health::Error; message.push_str("Failed to load workspaces.\n\n"); } @@ -336,12 +336,10 @@ impl GlobalState { let _p = profile::span("GlobalState::switch_workspaces"); tracing::info!(%cause, "will switch workspaces"); - if let Err(_) = self.fetch_workspace_error() { - if !self.workspaces.is_empty() { - // It only makes sense to switch to a partially broken workspace - // if we don't have any workspace at all yet. - return; - } + if self.fetch_workspace_error().is_err() && !self.workspaces.is_empty() { + // It only makes sense to switch to a partially broken workspace + // if we don't have any workspace at all yet. + return; } let Some(workspaces) = self.fetch_workspaces_queue.last_op_result() else { return; }; @@ -422,37 +420,37 @@ impl GlobalState { let files_config = self.config.files(); let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude); - if self.proc_macro_clients.is_empty() || !same_workspaces { - if self.config.expand_proc_macros() { - tracing::info!("Spawning proc-macro servers"); + if (self.proc_macro_clients.is_empty() || !same_workspaces) + && self.config.expand_proc_macros() + { + tracing::info!("Spawning proc-macro servers"); - // FIXME: use `Arc::from_iter` when it becomes available - self.proc_macro_clients = Arc::from( - self.workspaces - .iter() - .map(|ws| { - let path = match self.config.proc_macro_srv() { - Some(path) => path, - None => ws.find_sysroot_proc_macro_srv()?, - }; - - tracing::info!("Using proc-macro server at {}", path.display(),); - ProcMacroServer::spawn(path.clone()).map_err(|err| { - tracing::error!( - "Failed to run proc-macro server from path {}, error: {:?}", - path.display(), - err - ); - anyhow::anyhow!( - "Failed to run proc-macro server from path {}, error: {:?}", - path.display(), - err - ) - }) + // FIXME: use `Arc::from_iter` when it becomes available + self.proc_macro_clients = Arc::from( + self.workspaces + .iter() + .map(|ws| { + let path = match self.config.proc_macro_srv() { + Some(path) => path, + None => ws.find_sysroot_proc_macro_srv()?, + }; + + tracing::info!("Using proc-macro server at {}", path.display(),); + ProcMacroServer::spawn(path.clone()).map_err(|err| { + tracing::error!( + "Failed to run proc-macro server from path {}, error: {:?}", + path.display(), + err + ); + anyhow::anyhow!( + "Failed to run proc-macro server from path {}, error: {:?}", + path.display(), + err + ) }) - .collect::>(), - ) - }; + }) + .collect::>(), + ) } let watch = match files_config.watcher { @@ -490,7 +488,7 @@ impl GlobalState { let mut proc_macros = Vec::default(); for ws in &**self.workspaces { let (other, mut crate_proc_macros) = - ws.to_crate_graph(&mut load, &self.config.extra_env()); + ws.to_crate_graph(&mut load, self.config.extra_env()); crate_graph.extend(other, &mut crate_proc_macros); proc_macros.push(crate_proc_macros); } @@ -536,10 +534,11 @@ impl GlobalState { for ws in &self.fetch_build_data_queue.last_op_result().1 { match ws { - Ok(data) => match data.error() { - Some(stderr) => stdx::format_to!(buf, "{:#}\n", stderr), - _ => (), - }, + Ok(data) => { + if let Some(stderr) = data.error() { + stdx::format_to!(buf, "{:#}\n", stderr) + } + } // io errors Err(err) => stdx::format_to!(buf, "{:#}\n", err), } @@ -787,7 +786,7 @@ pub(crate) fn load_proc_macro( proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr, }; let expander: sync::Arc = - if dummy_replace.iter().any(|replace| &**replace == name) { + if dummy_replace.iter().any(|replace| **replace == name) { match kind { ProcMacroKind::Attr => sync::Arc::new(IdentityExpander), _ => sync::Arc::new(EmptyExpander), diff --git a/crates/rust-analyzer/src/semantic_tokens.rs b/crates/rust-analyzer/src/semantic_tokens.rs index d4bb20c8f448..b1a9d66c29ba 100644 --- a/crates/rust-analyzer/src/semantic_tokens.rs +++ b/crates/rust-analyzer/src/semantic_tokens.rs @@ -156,7 +156,7 @@ pub(crate) struct ModifierSet(pub(crate) u32); impl ModifierSet { pub(crate) fn standard_fallback(&mut self) { // Remove all non standard modifiers - self.0 = self.0 & !(!0u32 << LAST_STANDARD_MOD) + self.0 &= !(!0u32 << LAST_STANDARD_MOD) } } diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs index 8a9e947ded0a..0dcc3e6b2652 100644 --- a/crates/rust-analyzer/src/to_proto.rs +++ b/crates/rust-analyzer/src/to_proto.rs @@ -301,22 +301,18 @@ fn completion_item( set_score(&mut lsp_item, max_relevance, item.relevance); - if config.completion().enable_imports_on_the_fly { - if !item.import_to_add.is_empty() { - let imports: Vec<_> = item - .import_to_add - .into_iter() - .filter_map(|(import_path, import_name)| { - Some(lsp_ext::CompletionImport { - full_import_path: import_path, - imported_name: import_name, - }) - }) - .collect(); - if !imports.is_empty() { - let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports }; - lsp_item.data = Some(to_value(data).unwrap()); - } + if config.completion().enable_imports_on_the_fly && !item.import_to_add.is_empty() { + let imports: Vec<_> = item + .import_to_add + .into_iter() + .map(|(import_path, import_name)| lsp_ext::CompletionImport { + full_import_path: import_path, + imported_name: import_name, + }) + .collect(); + if !imports.is_empty() { + let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports }; + lsp_item.data = Some(to_value(data).unwrap()); } } diff --git a/crates/rust-analyzer/tests/slow-tests/support.rs b/crates/rust-analyzer/tests/slow-tests/support.rs index b2a8041ae9b5..689d4ebe5722 100644 --- a/crates/rust-analyzer/tests/slow-tests/support.rs +++ b/crates/rust-analyzer/tests/slow-tests/support.rs @@ -217,6 +217,7 @@ impl Server { self.send_request_(r) } fn send_request_(&self, r: Request) -> Value { + #[allow(clippy::redundant_clone)] // false positive let id = r.id.clone(); self.client.sender.send(r.clone().into()).unwrap(); while let Some(msg) = self.recv().unwrap_or_else(|Timeout| panic!("timeout: {r:?}")) { diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs index b3ea6ca8d46a..650cff7fde9f 100644 --- a/crates/syntax/src/ast/edit_in_place.rs +++ b/crates/syntax/src/ast/edit_in_place.rs @@ -391,7 +391,9 @@ impl ast::UseTree { if &path == prefix && self.use_tree_list().is_none() { if self.star_token().is_some() { // path$0::* -> * - self.coloncolon_token().map(ted::remove); + if let Some(a) = self.coloncolon_token() { + ted::remove(a); + } ted::remove(prefix.syntax()); } else { // path$0 -> self @@ -418,7 +420,9 @@ impl ast::UseTree { for p in successors(parent.parent_path(), |it| it.parent_path()) { p.segment()?; } - prefix.parent_path().and_then(|p| p.coloncolon_token()).map(ted::remove); + if let Some(a) = prefix.parent_path().and_then(|p| p.coloncolon_token()) { + ted::remove(a) + } ted::remove(prefix.syntax()); Some(()) } @@ -903,7 +907,9 @@ enum Foo { fn check_add_variant(before: &str, expected: &str, variant: ast::Variant) { let enum_ = ast_mut_from_text::(before); - enum_.variant_list().map(|it| it.add_variant(variant)); + if let Some(it) = enum_.variant_list() { + it.add_variant(variant); + } let after = enum_.to_string(); assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(after.trim())); } diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 3c2b7e56b065..93e35229c149 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -279,14 +279,14 @@ pub fn impl_trait( let where_clause = match (ty_where_clause, trait_where_clause) { (None, None) => " ".to_string(), - (None, Some(tr)) => format!("\n{}\n", tr).to_string(), - (Some(ty), None) => format!("\n{}\n", ty).to_string(), + (None, Some(tr)) => format!("\n{}\n", tr), + (Some(ty), None) => format!("\n{}\n", ty), (Some(ty), Some(tr)) => { let updated = ty.clone_for_update(); tr.predicates().for_each(|p| { ty.add_predicate(p); }); - format!("\n{}\n", updated).to_string() + format!("\n{}\n", updated) } }; diff --git a/crates/tt/src/buffer.rs b/crates/tt/src/buffer.rs index 0615a3763dfa..ea051a5cfe64 100644 --- a/crates/tt/src/buffer.rs +++ b/crates/tt/src/buffer.rs @@ -33,6 +33,7 @@ pub struct TokenBuffer<'t, Span> { buffers: Vec]>>, } +#[allow(clippy::type_complexity)] trait TokenList<'a, Span> { fn entries( &self, diff --git a/lib/line-index/tests/it.rs b/lib/line-index/tests/it.rs index ce1c0bc6f143..266f0b974958 100644 --- a/lib/line-index/tests/it.rs +++ b/lib/line-index/tests/it.rs @@ -1,15 +1,16 @@ use line_index::{LineCol, LineIndex, TextRange}; #[test] +#[rustfmt::skip] fn test_line_index() { let text = "hello\nworld"; let table = [ - (00, 0, 0), - (01, 0, 1), - (05, 0, 5), - (06, 1, 0), - (07, 1, 1), - (08, 1, 2), + ( 0, 0, 0), + ( 1, 0, 1), + ( 5, 0, 5), + ( 6, 1, 0), + ( 7, 1, 1), + ( 8, 1, 2), (10, 1, 4), (11, 1, 5), ]; From a31989aa46fb3e9dd557b7071cb15269844c4b26 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Sat, 10 Jun 2023 19:25:51 +0200 Subject: [PATCH 3/3] Add some restriction lints --- Cargo.toml | 33 ++++++++++++++++--- crates/base-db/src/fixture.rs | 12 +++---- crates/hir-def/src/body/pretty.rs | 4 +-- crates/hir-def/src/dyn_map.rs | 2 +- crates/hir-def/src/import_map.rs | 28 ++++++++-------- crates/hir-def/src/item_scope.rs | 2 +- .../hir-def/src/macro_expansion_tests/mod.rs | 2 +- crates/hir-expand/src/builtin_fn_macro.rs | 2 +- crates/hir-ty/src/chalk_db.rs | 1 + crates/hir-ty/src/consteval/tests.rs | 4 +-- .../match_check/deconstruct_pat.rs | 4 +-- crates/hir-ty/src/display.rs | 4 +-- crates/hir-ty/src/infer/closure.rs | 2 +- crates/hir-ty/src/infer/expr.rs | 1 + crates/hir-ty/src/layout.rs | 2 +- crates/hir-ty/src/layout/adt.rs | 2 +- crates/hir-ty/src/layout/tests.rs | 4 +-- crates/hir-ty/src/mir/eval.rs | 8 ++--- crates/hir-ty/src/mir/eval/shim.rs | 6 ++-- crates/hir-ty/src/mir/lower.rs | 6 ++-- crates/hir-ty/src/mir/lower/as_place.rs | 2 +- crates/hir-ty/src/tests.rs | 4 +-- crates/hir-ty/src/traits.rs | 4 +-- crates/hir/src/lib.rs | 2 +- .../src/handlers/extract_function.rs | 2 +- .../generate_documentation_template.rs | 4 +-- .../src/handlers/generate_enum_variant.rs | 2 +- .../src/handlers/generate_function.rs | 2 +- .../src/handlers/inline_const_as_literal.rs | 2 +- .../ide-assists/src/handlers/inline_macro.rs | 2 +- .../src/handlers/introduce_named_lifetime.rs | 2 +- crates/ide-assists/src/tests.rs | 4 +-- crates/ide-assists/src/utils.rs | 2 +- crates/ide-assists/src/utils/suggest_name.rs | 2 +- crates/ide-completion/src/render/function.rs | 4 +-- crates/ide-db/src/generated/lints.rs | 12 +++---- .../src/syntax_helpers/format_string_exprs.rs | 2 +- .../src/handlers/inactive_code.rs | 2 +- .../src/handlers/incoherent_impl.rs | 2 +- .../src/handlers/json_is_not_rust.rs | 6 ++-- .../src/handlers/macro_error.rs | 2 +- .../src/handlers/missing_fields.rs | 2 +- .../src/handlers/missing_unsafe.rs | 4 +-- .../src/handlers/mutability_errors.rs | 2 +- .../replace_filter_map_next_with_find_map.rs | 4 +-- .../src/handlers/type_mismatch.rs | 4 +-- .../handlers/unimplemented_builtin_macro.rs | 2 +- .../src/handlers/unresolved_field.rs | 2 +- .../src/handlers/unresolved_method.rs | 2 +- .../src/handlers/unresolved_module.rs | 4 +-- .../src/handlers/unresolved_proc_macro.rs | 2 +- .../src/handlers/useless_braces.rs | 2 +- crates/ide-diagnostics/src/tests.rs | 4 +-- crates/ide/src/hover/render.rs | 2 +- crates/ide/src/interpret_function.rs | 4 +-- crates/ide/src/join_lines.rs | 2 +- crates/ide/src/lib.rs | 2 +- crates/ide/src/markdown_remove.rs | 4 +-- crates/ide/src/moniker.rs | 4 +-- crates/ide/src/navigation_target.rs | 4 +-- crates/ide/src/runnables.rs | 2 +- crates/ide/src/typing.rs | 20 ++++------- crates/ide/src/view_hir.rs | 2 +- crates/ide/src/view_mir.rs | 2 +- crates/proc-macro-api/src/lib.rs | 2 +- crates/proc-macro-api/src/process.rs | 4 +-- crates/proc-macro-srv/src/dylib.rs | 2 +- crates/proc-macro-srv/src/proc_macros.rs | 2 +- crates/proc-macro-test/build.rs | 2 +- crates/project-model/src/build_scripts.rs | 4 +-- crates/project-model/src/cargo_workspace.rs | 2 +- crates/project-model/src/tests.rs | 2 +- crates/rust-analyzer/src/caps.rs | 16 ++++----- .../rust-analyzer/src/cli/analysis_stats.rs | 4 +-- crates/rust-analyzer/src/cli/lsif.rs | 10 +++--- crates/rust-analyzer/src/cli/scip.rs | 8 ++--- crates/rust-analyzer/src/config.rs | 2 +- .../rust-analyzer/src/diagnostics/to_proto.rs | 12 +++---- crates/rust-analyzer/src/dispatch.rs | 6 ++-- crates/rust-analyzer/src/from_proto.rs | 2 +- .../src/handlers/notification.rs | 4 +-- crates/rust-analyzer/src/handlers/request.rs | 14 ++++---- crates/rust-analyzer/src/lsp_utils.rs | 27 ++++++++------- crates/rust-analyzer/src/main_loop.rs | 20 +++++------ crates/rust-analyzer/src/reload.rs | 8 ++--- crates/rust-analyzer/tests/slow-tests/main.rs | 4 +-- .../rust-analyzer/tests/slow-tests/support.rs | 2 +- crates/sourcegen/src/lib.rs | 4 +-- crates/syntax/src/ast/make.rs | 10 +++--- crates/test-utils/src/bench_fixture.rs | 2 +- crates/test-utils/src/fixture.rs | 8 ++--- crates/text-edit/src/lib.rs | 6 ++-- crates/tt/src/lib.rs | 4 +-- crates/vfs/src/file_set.rs | 8 ++--- crates/vfs/src/loader.rs | 2 +- crates/vfs/src/vfs_path.rs | 2 +- crates/vfs/src/vfs_path/tests.rs | 14 ++++---- 97 files changed, 255 insertions(+), 241 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fbbcf198ce7c..73d16c885f03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -99,18 +99,41 @@ unused_lifetimes = "warn" semicolon_in_expressions_from_macros = "warn" [workspace.lints.clippy] -all = { level = "warn", priority = -1 } +# complexity lints +complexity = { level = "warn", priority = -1 } +# Should be tackled at some point where relevant +too_many_arguments = "allow" +# Should be tackled at some point +type_complexity = "allow" + +# correctness lints +correctness = { level = "deny", priority = -1 } + +# perf lints +perf = { level = "deny", priority = -1 } + +# style lints +style = { level = "warn", priority = -1 } # () makes a fine error in most cases result_unit_err = "allow" # We don't expose public APIs that matter like this len_without_is_empty = "allow" -# Should be tackled at some point -too_many_arguments = "allow" -# Should be tackled at some point -type_complexity = "allow" # we currently prefer explicit control flow return over `...?;` statements whose result is unused question_mark = "allow" # We have macros that rely on this currently enum_variant_names = "allow" # Builder pattern disagrees new_ret_no_self = "allow" + +# suspicious lints +suspicious = { level = "warn", priority = -1 } + +# suspicious lints +restriction = { level = "allow", priority = -1 } +# Remove the tidy test once the lint table is stable +dbg_macro = "warn" +todo = "warn" +unimplemented = "warn" +rc_buffer = "warn" +# FIXME enable this, we use this pattern a lot so its annoying work ... +# str_to_string = "warn" diff --git a/crates/base-db/src/fixture.rs b/crates/base-db/src/fixture.rs index 1759733f2e0f..07b08b16935a 100644 --- a/crates/base-db/src/fixture.rs +++ b/crates/base-db/src/fixture.rs @@ -131,7 +131,7 @@ impl ChangeFixture { let mut file_set = FileSet::default(); let mut current_source_root_kind = SourceRootKind::Local; - let source_root_prefix = "/".to_string(); + let source_root_prefix = "/".to_owned(); let mut file_id = FileId(0); let mut roots = Vec::new(); @@ -245,7 +245,7 @@ impl ChangeFixture { file_id.0 += 1; let mut fs = FileSet::default(); - fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_string())); + fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_owned())); roots.push(SourceRoot::new_library(fs)); change.change_file(core_file, Some(Arc::from(mini_core.source_code()))); @@ -255,7 +255,7 @@ impl ChangeFixture { let core_crate = crate_graph.add_crate_root( core_file, Edition::Edition2021, - Some(CrateDisplayName::from_canonical_name("core".to_string())), + Some(CrateDisplayName::from_canonical_name("core".to_owned())), None, Default::default(), Default::default(), @@ -283,7 +283,7 @@ impl ChangeFixture { let mut fs = FileSet::default(); fs.insert( proc_lib_file, - VfsPath::new_virtual_path("/sysroot/proc_macros/lib.rs".to_string()), + VfsPath::new_virtual_path("/sysroot/proc_macros/lib.rs".to_owned()), ); roots.push(SourceRoot::new_library(fs)); @@ -294,7 +294,7 @@ impl ChangeFixture { let proc_macros_crate = crate_graph.add_crate_root( proc_lib_file, Edition::Edition2021, - Some(CrateDisplayName::from_canonical_name("proc_macros".to_string())), + Some(CrateDisplayName::from_canonical_name("proc_macros".to_owned())), None, Default::default(), Default::default(), @@ -453,7 +453,7 @@ fn parse_crate(crate_str: String) -> (String, CrateOrigin, Option) { }, _ => panic!("Bad string for crate origin: {b}"), }; - (a.to_owned(), origin, Some(version.to_string())) + (a.to_owned(), origin, Some(version.to_owned())) } else { let crate_origin = match LangCrateOrigin::from(&*crate_str) { LangCrateOrigin::Other => CrateOrigin::Local { repo: None, name: None }, diff --git a/crates/hir-def/src/body/pretty.rs b/crates/hir-def/src/body/pretty.rs index 88380aa355d1..be9ede6081b6 100644 --- a/crates/hir-def/src/body/pretty.rs +++ b/crates/hir-def/src/body/pretty.rs @@ -36,7 +36,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo let item_tree_id = it.lookup(db).id; let name = match &item_tree_id.item_tree(db)[item_tree_id.value].name { Some(name) => name.display(db.upcast()).to_string(), - None => "_".to_string(), + None => "_".to_owned(), }; format!("const {name} = ") } @@ -45,7 +45,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo let variant = &src.value[it.local_id]; match &variant.name() { Some(name) => name.to_string(), - None => "_".to_string(), + None => "_".to_owned(), } } }; diff --git a/crates/hir-def/src/dyn_map.rs b/crates/hir-def/src/dyn_map.rs index 63138aa6ad78..86134d6f18aa 100644 --- a/crates/hir-def/src/dyn_map.rs +++ b/crates/hir-def/src/dyn_map.rs @@ -14,7 +14,7 @@ //! let mut map = DynMap::new(); //! //! // To access a specific map, index the `DynMap` by `Key`: -//! map[STRING_TO_U32].insert("hello".to_string(), 92); +//! map[STRING_TO_U32].insert("hello".to_owned(), 92); //! let value = map[U32_TO_VEC].get(92); //! assert!(value.is_none()); //! ``` diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs index ec150dc0689c..129c09da1aff 100644 --- a/crates/hir-def/src/import_map.rs +++ b/crates/hir-def/src/import_map.rs @@ -872,7 +872,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy), + Query::new("fmt".to_owned()).search_mode(SearchMode::Fuzzy), expect![[r#" dep::fmt (t) dep::fmt::Display (t) @@ -902,7 +902,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(), + Query::new("fmt".to_owned()).search_mode(SearchMode::Fuzzy).assoc_items_only(), expect![[r#" dep::fmt::Display::FMT_CONST (a) dep::fmt::Display::format_function (a) @@ -913,7 +913,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()) + Query::new("fmt".to_owned()) .search_mode(SearchMode::Fuzzy) .exclude_import_kind(ImportKind::AssociatedItem), expect![[r#" @@ -925,7 +925,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()) + Query::new("fmt".to_owned()) .search_mode(SearchMode::Fuzzy) .assoc_items_only() .exclude_import_kind(ImportKind::AssociatedItem), @@ -962,7 +962,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy), + Query::new("fmt".to_owned()).search_mode(SearchMode::Fuzzy), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -977,7 +977,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).search_mode(SearchMode::Equals), + Query::new("fmt".to_owned()).search_mode(SearchMode::Equals), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -990,7 +990,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).search_mode(SearchMode::Contains), + Query::new("fmt".to_owned()).search_mode(SearchMode::Contains), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -1031,7 +1031,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()), + Query::new("fmt".to_owned()), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -1045,7 +1045,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).name_only(), + Query::new("fmt".to_owned()).name_only(), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -1069,7 +1069,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("FMT".to_string()), + Query::new("FMT".to_owned()), expect![[r#" dep::FMT (t) dep::FMT (v) @@ -1081,7 +1081,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("FMT".to_string()).case_sensitive(), + Query::new("FMT".to_owned()).case_sensitive(), expect![[r#" dep::FMT (t) dep::FMT (v) @@ -1110,7 +1110,7 @@ mod tests { pub fn no() {} "#, "main", - Query::new("".to_string()).limit(2), + Query::new("".to_owned()).limit(2), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -1133,7 +1133,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("FMT".to_string()), + Query::new("FMT".to_owned()), expect![[r#" dep::FMT (t) dep::FMT (v) @@ -1145,7 +1145,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt), + Query::new("FMT".to_owned()).exclude_import_kind(ImportKind::Adt), expect![[r#""#]], ); } diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index 3ed321d189d3..759a64c6c6d6 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -366,7 +366,7 @@ impl ItemScope { format_to!( buf, "{}:", - name.map_or("_".to_string(), |name| name.display(db).to_string()) + name.map_or("_".to_owned(), |name| name.display(db).to_string()) ); if def.types.is_some() { diff --git a/crates/hir-def/src/macro_expansion_tests/mod.rs b/crates/hir-def/src/macro_expansion_tests/mod.rs index 4a62696df081..93d333fe2c2b 100644 --- a/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -108,7 +108,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream if let TokenExpander::DeclarativeMacro { mac, def_site_token_map } = &*macro_def { let tt = match ¯o_ { ast::Macro::MacroRules(mac) => mac.token_tree().unwrap(), - ast::Macro::MacroDef(_) => unimplemented!(""), + ast::Macro::MacroDef(m) => m.body().unwrap(), }; let tt_start = tt.syntax().text_range().start(); diff --git a/crates/hir-expand/src/builtin_fn_macro.rs b/crates/hir-expand/src/builtin_fn_macro.rs index 93c44395a64f..f04eac91492e 100644 --- a/crates/hir-expand/src/builtin_fn_macro.rs +++ b/crates/hir-expand/src/builtin_fn_macro.rs @@ -777,7 +777,7 @@ fn env_expand( // We cannot use an empty string here, because for // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become // `include!("foo.rs"), which might go to infinite loop - "UNRESOLVED_ENV_VAR".to_string() + "UNRESOLVED_ENV_VAR".to_owned() }); let expanded = quote! { #s }; diff --git a/crates/hir-ty/src/chalk_db.rs b/crates/hir-ty/src/chalk_db.rs index 1e8253794ca3..a84a900ce5eb 100644 --- a/crates/hir-ty/src/chalk_db.rs +++ b/crates/hir-ty/src/chalk_db.rs @@ -188,6 +188,7 @@ impl<'a> chalk_solve::RustIrDatabase for ChalkContext<'a> { fn custom_clauses(&self) -> Vec> { vec![] } + #[allow(clippy::unimplemented)] fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec { // We don't do coherence checking (yet) unimplemented!() diff --git a/crates/hir-ty/src/consteval/tests.rs b/crates/hir-ty/src/consteval/tests.rs index 06fff08b7d35..b144ad66e7a3 100644 --- a/crates/hir-ty/src/consteval/tests.rs +++ b/crates/hir-ty/src/consteval/tests.rs @@ -106,7 +106,7 @@ fn bit_op() { check_number(r#"const GOAL: i8 = 1 << 7"#, (1i8 << 7) as i128); check_number(r#"const GOAL: i8 = -1 << 2"#, (-1i8 << 2) as i128); check_fail(r#"const GOAL: i8 = 1 << 8"#, |e| { - e == ConstEvalError::MirEvalError(MirEvalError::Panic("Overflow in Shl".to_string())) + e == ConstEvalError::MirEvalError(MirEvalError::Panic("Overflow in Shl".to_owned())) }); } @@ -2309,7 +2309,7 @@ fn panic_messages() { panic!("hello"); }; "#, - |e| e == ConstEvalError::MirEvalError(MirEvalError::Panic("hello".to_string())), + |e| e == ConstEvalError::MirEvalError(MirEvalError::Panic("hello".to_owned())), ); } diff --git a/crates/hir-ty/src/diagnostics/match_check/deconstruct_pat.rs b/crates/hir-ty/src/diagnostics/match_check/deconstruct_pat.rs index a0f6b9368ee0..2de37491b6a6 100644 --- a/crates/hir-ty/src/diagnostics/match_check/deconstruct_pat.rs +++ b/crates/hir-ty/src/diagnostics/match_check/deconstruct_pat.rs @@ -129,7 +129,7 @@ impl IntRange { fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange { match scalar_ty { Scalar::Bool => IntRange { range: lo..=hi }, - _ => unimplemented!(), + s => panic!("unexpected scalar {s:?}"), } } @@ -161,7 +161,7 @@ impl IntRange { }; Pat { ty, kind: kind.into() } } - _ => unimplemented!(), + t => panic!("unexpected type {t:?}"), } } diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index 0c580faa59f1..7edb2755bc70 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -561,9 +561,7 @@ fn render_const_scalar( write!(f, "&{}", data.name.display(f.db.upcast()))?; Ok(()) } - _ => { - return f.write_str(""); - } + _ => f.write_str(""), }, _ => { let addr = usize::from_le_bytes(match b.try_into() { diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index 5da759dbdcee..9efdb84a56c4 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -199,7 +199,7 @@ impl CapturedItem { .position(|x| x.0 == f.local_id) .unwrap_or_default() .to_string(), - VariantData::Unit => "[missing field]".to_string(), + VariantData::Unit => "[missing field]".to_owned(), }; result = format!("{result}.{field}"); field_need_paren = false; diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index 3acfd323b2f1..d2f89075522d 100644 --- a/crates/hir-ty/src/infer/expr.rs +++ b/crates/hir-ty/src/infer/expr.rs @@ -576,6 +576,7 @@ impl<'a> InferenceContext<'a> { let cast_ty = self.make_ty(type_ref); // FIXME: propagate the "castable to" expectation let inner_ty = self.infer_expr_no_expect(*expr); + #[allow(clippy::single_match)] match (inner_ty.kind(Interner), cast_ty.kind(Interner)) { (TyKind::Ref(_, _, inner), TyKind::Raw(_, cast)) => { // FIXME: record invalid cast diagnostic in case of mismatch diff --git a/crates/hir-ty/src/layout.rs b/crates/hir-ty/src/layout.rs index d2413280790b..c90de9548319 100644 --- a/crates/hir-ty/src/layout.rs +++ b/crates/hir-ty/src/layout.rs @@ -153,7 +153,7 @@ pub fn layout_of_ty_query( } TyKind::Array(element, count) => { let count = try_const_usize(db, count).ok_or(LayoutError::UserError( - "unevaluated or mistyped const generic parameter".to_string(), + "unevaluated or mistyped const generic parameter".to_owned(), ))? as u64; let element = db.layout_of_ty(element.clone(), krate)?; let size = element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow)?; diff --git a/crates/hir-ty/src/layout/adt.rs b/crates/hir-ty/src/layout/adt.rs index c2e2a4244147..6c48ad5078ca 100644 --- a/crates/hir-ty/src/layout/adt.rs +++ b/crates/hir-ty/src/layout/adt.rs @@ -161,7 +161,7 @@ fn repr_discr( return Err(LayoutError::UserError( "Integer::repr_discr: `#[repr]` hint too small for \ discriminant range of enum " - .to_string(), + .to_owned(), )); } return Ok((discr, ity.is_signed())); diff --git a/crates/hir-ty/src/layout/tests.rs b/crates/hir-ty/src/layout/tests.rs index b26dce15c61e..9874619f1966 100644 --- a/crates/hir-ty/src/layout/tests.rs +++ b/crates/hir-ty/src/layout/tests.rs @@ -196,14 +196,14 @@ fn recursive() { } check_fail( r#"struct Goal(Goal);"#, - LayoutError::UserError("infinite sized recursive type".to_string()), + LayoutError::UserError("infinite sized recursive type".to_owned()), ); check_fail( r#" struct Foo(Foo); struct Goal(Foo); "#, - LayoutError::UserError("infinite sized recursive type".to_string()), + LayoutError::UserError("infinite sized recursive type".to_owned()), ); } diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index 6fca088175ef..5081c11e7328 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -1463,7 +1463,7 @@ impl Evaluator<'_> { } }; mem.get(pos..pos + size) - .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_string())) + .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_owned())) } fn write_memory(&mut self, addr: Address, r: &[u8]) -> Result<()> { @@ -1480,9 +1480,7 @@ impl Evaluator<'_> { } }; mem.get_mut(pos..pos + r.len()) - .ok_or_else(|| { - MirEvalError::UndefinedBehavior("out of bound memory write".to_string()) - })? + .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory write".to_owned()))? .copy_from_slice(r); Ok(()) } @@ -1584,7 +1582,7 @@ impl Evaluator<'_> { if let Some(ty) = check_inner { for i in 0..count { let offset = element_size * i; - rec(this, &b[offset..offset + element_size], &ty, locals, mm)?; + rec(this, &b[offset..offset + element_size], ty, locals, mm)?; } } } diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs index 4ca22dc72fde..fbcf382571c2 100644 --- a/crates/hir-ty/src/mir/eval/shim.rs +++ b/crates/hir-ty/src/mir/eval/shim.rs @@ -155,7 +155,7 @@ impl Evaluator<'_> { use LangItem::*; let mut args = args.iter(); match x { - BeginPanic => Err(MirEvalError::Panic("".to_string())), + BeginPanic => Err(MirEvalError::Panic("".to_owned())), PanicFmt => { let message = (|| { let arguments_struct = @@ -178,7 +178,7 @@ impl Evaluator<'_> { .try_into() .ok()?, ); - let mut message = "".to_string(); + let mut message = "".to_owned(); for i in 0..pieces_array_len { let piece_ptr_addr = pieces_array_addr.offset(2 * i * ptr_size); let piece_addr = @@ -195,7 +195,7 @@ impl Evaluator<'_> { } Some(message) })() - .unwrap_or_else(|| "".to_string()); + .unwrap_or_else(|| "".to_owned()); Err(MirEvalError::Panic(message)) } SliceLen => { diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index 3d269caadb57..eb8b2a380c95 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -1435,7 +1435,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.set_goto(prev_block, begin, span); f(self, begin)?; let my = mem::replace(&mut self.current_loop_blocks, prev).ok_or( - MirLowerError::ImplementationError("current_loop_blocks is corrupt".to_string()), + MirLowerError::ImplementationError("current_loop_blocks is corrupt".to_owned()), )?; if let Some(prev) = prev_label { self.labeled_loop_blocks.insert(label.unwrap(), prev); @@ -1470,7 +1470,7 @@ impl<'ctx> MirLowerCtx<'ctx> { .current_loop_blocks .as_mut() .ok_or(MirLowerError::ImplementationError( - "Current loop access out of loop".to_string(), + "Current loop access out of loop".to_owned(), ))? .end { @@ -1480,7 +1480,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.current_loop_blocks .as_mut() .ok_or(MirLowerError::ImplementationError( - "Current loop access out of loop".to_string(), + "Current loop access out of loop".to_owned(), ))? .end = Some(s); s diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs index 98a59a81d9f4..20becbe5e8f9 100644 --- a/crates/hir-ty/src/mir/lower/as_place.rs +++ b/crates/hir-ty/src/mir/lower/as_place.rs @@ -215,7 +215,7 @@ impl MirLowerCtx<'_> { ) { let Some(index_fn) = self.infer.method_resolution(expr_id) else { - return Err(MirLowerError::UnresolvedMethod("[overloaded index]".to_string())); + return Err(MirLowerError::UnresolvedMethod("[overloaded index]".to_owned())); }; let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true)? else { return Ok(None); diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs index 2db04024b7b6..9f804fa1bb21 100644 --- a/crates/hir-ty/src/tests.rs +++ b/crates/hir-ty/src/tests.rs @@ -107,7 +107,7 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour .trim_start_matches("adjustments:") .trim() .split(',') - .map(|it| it.trim().to_string()) + .map(|it| it.trim().to_owned()) .filter(|it| !it.is_empty()) .collect(), ); @@ -335,7 +335,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { }); for (node, ty) in &types { let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) { - (self_param.name().unwrap().syntax().text_range(), "self".to_string()) + (self_param.name().unwrap().syntax().text_range(), "self".to_owned()) } else { (node.value.text_range(), node.value.text().to_string().replace('\n', " ")) }; diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index f40b7db3a551..29b2efdc6ad1 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -90,8 +90,8 @@ pub(crate) fn trait_solve_query( GoalData::DomainGoal(DomainGoal::Holds(WhereClause::Implemented(it))) => { db.trait_data(it.hir_trait_id()).name.display(db.upcast()).to_string() } - GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_string(), - _ => "??".to_string(), + GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_owned(), + _ => "??".to_owned(), }); tracing::info!("trait_solve_query({:?})", goal.value.goal); diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 72edf40e81c3..fc6a58eba42c 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1946,7 +1946,7 @@ impl Function { }; let (result, stdout, stderr) = interpret_mir(db, &body, false); let mut text = match result { - Ok(_) => "pass".to_string(), + Ok(_) => "pass".to_owned(), Err(e) => { let mut r = String::new(); _ = e.pretty_print(&mut r, db, &span_formatter); diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index d8ec1c8e8e50..cbfd289a85ac 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -1884,7 +1884,7 @@ fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr } fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String { - ty.display_source_code(ctx.db(), module.into(), true).ok().unwrap_or_else(|| "_".to_string()) + ty.display_source_code(ctx.db(), module.into(), true).ok().unwrap_or_else(|| "_".to_owned()) } fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type { diff --git a/crates/ide-assists/src/handlers/generate_documentation_template.rs b/crates/ide-assists/src/handlers/generate_documentation_template.rs index f298ce8916db..f720391cc82e 100644 --- a/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -416,9 +416,9 @@ fn arguments_from_params(param_list: &ast::ParamList) -> String { true => format!("&mut {name}"), false => name.to_string(), }, - None => "_".to_string(), + None => "_".to_owned(), }, - _ => "_".to_string(), + _ => "_".to_owned(), }); args_iter.format(", ").to_string() } diff --git a/crates/ide-assists/src/handlers/generate_enum_variant.rs b/crates/ide-assists/src/handlers/generate_enum_variant.rs index 5b6ce22a2ca7..fba400ab159e 100644 --- a/crates/ide-assists/src/handlers/generate_enum_variant.rs +++ b/crates/ide-assists/src/handlers/generate_enum_variant.rs @@ -162,7 +162,7 @@ fn make_record_field_list( fn name_from_field(field: &ast::RecordExprField) -> ast::Name { let text = match field.name_ref() { Some(it) => it.to_string(), - None => name_from_field_shorthand(field).unwrap_or("unknown".to_string()), + None => name_from_field_shorthand(field).unwrap_or("unknown".to_owned()), }; make::name(&text) } diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs index c579f6780db8..a622166a915c 100644 --- a/crates/ide-assists/src/handlers/generate_function.rs +++ b/crates/ide-assists/src/handlers/generate_function.rs @@ -961,7 +961,7 @@ fn fn_arg_name(sema: &Semantics<'_, RootDatabase>, arg_expr: &ast::Expr) -> Stri name } Some(name) => name, - None => "arg".to_string(), + None => "arg".to_owned(), } } diff --git a/crates/ide-assists/src/handlers/inline_const_as_literal.rs b/crates/ide-assists/src/handlers/inline_const_as_literal.rs index 18437453761c..111ea50fdc94 100644 --- a/crates/ide-assists/src/handlers/inline_const_as_literal.rs +++ b/crates/ide-assists/src/handlers/inline_const_as_literal.rs @@ -60,7 +60,7 @@ pub(crate) fn inline_const_as_literal(acc: &mut Assists, ctx: &AssistContext<'_> let id = AssistId("inline_const_as_literal", AssistKind::RefactorInline); - let label = "Inline const as literal".to_string(); + let label = "Inline const as literal".to_owned(); let target = variable.syntax().text_range(); return acc.add(id, label, target, |edit| { diff --git a/crates/ide-assists/src/handlers/inline_macro.rs b/crates/ide-assists/src/handlers/inline_macro.rs index e19f04b10b62..b1d927fe6fda 100644 --- a/crates/ide-assists/src/handlers/inline_macro.rs +++ b/crates/ide-assists/src/handlers/inline_macro.rs @@ -42,7 +42,7 @@ pub(crate) fn inline_macro(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option acc.add( AssistId("inline_macro", AssistKind::RefactorRewrite), - "Inline macro".to_string(), + "Inline macro".to_owned(), text_range, |builder| builder.replace(text_range, expanded.to_string()), ) diff --git a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs index 7fd52aaecf8a..6890aeacfc63 100644 --- a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs +++ b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs @@ -129,7 +129,7 @@ fn generate_unique_lifetime_param_name( type_params.lifetime_params().map(|p| p.syntax().text().to_string()).collect(); ('a'..='z').map(|it| format!("'{it}")).find(|it| !used_lifetime_params.contains(it)) } - None => Some("'a".to_string()), + None => Some("'a".to_owned()), } .map(|it| make::lifetime(&it)) } diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs index fa6f23d9f453..64448580693b 100644 --- a/crates/ide-assists/src/tests.rs +++ b/crates/ide-assists/src/tests.rs @@ -416,7 +416,7 @@ pub fn test_some_range(a: int) -> bool { &db, &cfg, AssistResolveStrategy::Single(SingleResolve { - assist_id: "SOMETHING_MISMATCHING".to_string(), + assist_id: "SOMETHING_MISMATCHING".to_owned(), assist_kind: AssistKind::RefactorExtract, }), frange, @@ -462,7 +462,7 @@ pub fn test_some_range(a: int) -> bool { &db, &cfg, AssistResolveStrategy::Single(SingleResolve { - assist_id: "extract_variable".to_string(), + assist_id: "extract_variable".to_owned(), assist_kind: AssistKind::RefactorExtract, }), frange, diff --git a/crates/ide-assists/src/utils.rs b/crates/ide-assists/src/utils.rs index cc4a7f3c0adb..2aa474ce841a 100644 --- a/crates/ide-assists/src/utils.rs +++ b/crates/ide-assists/src/utils.rs @@ -578,7 +578,7 @@ impl ReferenceConversion { pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String { match self.conversion { ReferenceConversionType::Copy => self.ty.display(db).to_string(), - ReferenceConversionType::AsRefStr => "&str".to_string(), + ReferenceConversionType::AsRefStr => "&str".to_owned(), ReferenceConversionType::AsRefSlice => { let type_argument_name = self.ty.type_arguments().next().unwrap().display(db).to_string(); diff --git a/crates/ide-assists/src/utils/suggest_name.rs b/crates/ide-assists/src/utils/suggest_name.rs index 10dee38783d0..b97e6795c520 100644 --- a/crates/ide-assists/src/utils/suggest_name.rs +++ b/crates/ide-assists/src/utils/suggest_name.rs @@ -119,7 +119,7 @@ pub(crate) fn for_variable(expr: &ast::Expr, sema: &Semantics<'_, RootDatabase>) } } - "var_name".to_string() + "var_name".to_owned() } fn normalize(name: &str) -> Option { diff --git a/crates/ide-completion/src/render/function.rs b/crates/ide-completion/src/render/function.rs index 89c3e3b84df4..1b1e78e9e465 100644 --- a/crates/ide-completion/src/render/function.rs +++ b/crates/ide-completion/src/render/function.rs @@ -173,12 +173,12 @@ pub(super) fn add_call_parens<'b>( } None => { let name = match param.ty().as_adt() { - None => "_".to_string(), + None => "_".to_owned(), Some(adt) => adt .name(ctx.db) .as_text() .map(|s| to_lower_snake_case(s.as_str())) - .unwrap_or_else(|| "_".to_string()), + .unwrap_or_else(|| "_".to_owned()), }; f(&format_args!("${{{}:{name}}}", index + offset)) } diff --git a/crates/ide-db/src/generated/lints.rs b/crates/ide-db/src/generated/lints.rs index e488300b41ca..240546379e65 100644 --- a/crates/ide-db/src/generated/lints.rs +++ b/crates/ide-db/src/generated/lints.rs @@ -2056,7 +2056,7 @@ A simple example is: fn foo(_f: impl AsRef) {} fn main() { - foo::("".to_string()); + foo::("".to_owned()); } ``` @@ -2066,7 +2066,7 @@ This is currently rejected: error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position --> src/main.rs:6:11 | -6 | foo::("".to_string()); +6 | foo::("".to_owned()); | ^^^ explicit generic argument not allowed ``` @@ -2083,11 +2083,11 @@ fn foo(_f: impl AsRef) {} fn bar>(_f: F) {} fn main() { - bar::("".to_string()); // Okay - bar::("".to_string()); // Okay + bar::("".to_owned()); // Okay + bar::("".to_owned()); // Okay - foo::("".to_string()); // Okay - foo::("".to_string()); // Error, you cannot specify `impl Trait` explicitly + foo::("".to_owned()); // Okay + foo::("".to_owned()); // Error, you cannot specify `impl Trait` explicitly } ``` "##, diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs index fc230818193d..49594aee9f35 100644 --- a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs +++ b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs @@ -203,7 +203,7 @@ mod tests { use expect_test::{expect, Expect}; fn check(input: &str, expect: &Expect) { - let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_string(), vec![])); + let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_owned(), vec![])); let outcome_repr = if !exprs.is_empty() { format!("{output}; {}", with_placeholders(exprs).join(", ")) } else { diff --git a/crates/ide-diagnostics/src/handlers/inactive_code.rs b/crates/ide-diagnostics/src/handlers/inactive_code.rs index f558b7256a4c..f85f10b4db16 100644 --- a/crates/ide-diagnostics/src/handlers/inactive_code.rs +++ b/crates/ide-diagnostics/src/handlers/inactive_code.rs @@ -16,7 +16,7 @@ pub(crate) fn inactive_code( } let inactive = DnfExpr::new(d.cfg.clone()).why_inactive(&d.opts); - let mut message = "code is inactive due to #[cfg] directives".to_string(); + let mut message = "code is inactive due to #[cfg] directives".to_owned(); if let Some(inactive) = inactive { let inactive_reasons = inactive.to_string(); diff --git a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs index c2846ed09289..5f41d02a9953 100644 --- a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs +++ b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs @@ -8,7 +8,7 @@ use crate::{Diagnostic, DiagnosticsContext, Severity}; pub(crate) fn incoherent_impl(ctx: &DiagnosticsContext<'_>, d: &hir::IncoherentImpl) -> Diagnostic { Diagnostic::new( "incoherent-impl", - "cannot define inherent `impl` for foreign type".to_string(), + "cannot define inherent `impl` for foreign type".to_owned(), ctx.sema.diagnostics_display_range(InFile::new(d.file_id, d.impl_.clone().into())).range, ) .severity(Severity::Error) 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 04ce1e0feeed..c319c4491abd 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -42,12 +42,12 @@ impl State { v.push("Deserialize"); } match v.as_slice() { - [] => "".to_string(), + [] => "".to_owned(), [x] => format!("#[derive({x})]\n"), [x, y] => format!("#[derive({x}, {y})]\n"), _ => { never!(); - "".to_string() + "".to_owned() } } } @@ -175,7 +175,7 @@ mod tests { #[test] fn diagnostic_for_simple_case() { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("syntax-error".to_string()); + config.disabled.insert("syntax-error".to_owned()); check_diagnostics_with_config( config, r#" diff --git a/crates/ide-diagnostics/src/handlers/macro_error.rs b/crates/ide-diagnostics/src/handlers/macro_error.rs index 7547779a95c7..abe08f627c8a 100644 --- a/crates/ide-diagnostics/src/handlers/macro_error.rs +++ b/crates/ide-diagnostics/src/handlers/macro_error.rs @@ -90,7 +90,7 @@ pub macro panic { // FIXME: This is a false-positive, the file is actually linked in via // `include!` macro - config.disabled.insert("unlinked-file".to_string()); + config.disabled.insert("unlinked-file".to_owned()); check_diagnostics_with_config( config, diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index 6f148effd0b9..fda0ce16fb75 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -177,7 +177,7 @@ fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Ty let ty_str = match ty.as_adt() { Some(adt) => adt.name(db).display(db.upcast()).to_string(), None => { - ty.display_source_code(db, module.into(), false).ok().unwrap_or_else(|| "_".to_string()) + ty.display_source_code(db, module.into(), false).ok().unwrap_or_else(|| "_".to_owned()) } }; diff --git a/crates/ide-diagnostics/src/handlers/missing_unsafe.rs b/crates/ide-diagnostics/src/handlers/missing_unsafe.rs index 2026b6fcef53..94de777f65da 100644 --- a/crates/ide-diagnostics/src/handlers/missing_unsafe.rs +++ b/crates/ide-diagnostics/src/handlers/missing_unsafe.rs @@ -312,7 +312,7 @@ fn main() { check_fix( r#" unsafe fn foo() -> String { - "string".to_string() + "string".to_owned() } fn main() { @@ -321,7 +321,7 @@ fn main() { "#, r#" unsafe fn foo() -> String { - "string".to_string() + "string".to_owned() } fn main() { diff --git a/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/crates/ide-diagnostics/src/handlers/mutability_errors.rs index f61460e317f7..2ecda5e8156a 100644 --- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -19,7 +19,7 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Diagno for source in d.local.sources(ctx.sema.db) { let Some(ast) = source.name() else { continue }; // FIXME: macros - edit_builder.insert(ast.value.syntax().text_range().start(), "mut ".to_string()); + edit_builder.insert(ast.value.syntax().text_range().start(), "mut ".to_owned()); } let edit = edit_builder.finish(); Some(vec![fix( diff --git a/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs b/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs index d3eda3c5ebce..6b9aa7640c0b 100644 --- a/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs +++ b/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs @@ -63,8 +63,8 @@ mod tests { #[track_caller] pub(crate) fn check_diagnostics(ra_fixture: &str) { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("inactive-code".to_string()); - config.disabled.insert("unresolved-method".to_string()); + config.disabled.insert("inactive-code".to_owned()); + config.disabled.insert("unresolved-method".to_owned()); check_diagnostics_with_config(config, ra_fixture) } diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 9e6c36ce910e..b4232fcf0512 100644 --- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -129,7 +129,7 @@ fn add_missing_ok_or_some( let mut builder = TextEdit::builder(); builder.insert(expr.syntax().text_range().start(), format!("{variant_name}(")); - builder.insert(expr.syntax().text_range().end(), ")".to_string()); + builder.insert(expr.syntax().text_range().end(), ")".to_owned()); let source_change = SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), builder.finish()); let name = format!("Wrap in {variant_name}"); @@ -183,7 +183,7 @@ fn str_ref_to_owned( let expr = expr_ptr.value.to_node(&root); let expr_range = expr.syntax().text_range(); - let to_owned = ".to_owned()".to_string(); + let to_owned = ".to_owned()".to_owned(); let edit = TextEdit::insert(expr.syntax().text_range().end(), to_owned); let source_change = diff --git a/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs b/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs index e879de75cd84..0cfba59e8698 100644 --- a/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs +++ b/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs @@ -9,7 +9,7 @@ pub(crate) fn unimplemented_builtin_macro( ) -> Diagnostic { Diagnostic::new( "unimplemented-builtin-macro", - "unimplemented built-in macro".to_string(), + "unimplemented built-in macro".to_owned(), ctx.sema.diagnostics_display_range(d.node.clone()).range, ) .severity(Severity::WeakWarning) diff --git a/crates/ide-diagnostics/src/handlers/unresolved_field.rs b/crates/ide-diagnostics/src/handlers/unresolved_field.rs index 5e4efa41fd9c..892b4944f203 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_field.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_field.rs @@ -55,7 +55,7 @@ fn method_fix( let FileRange { range, file_id } = ctx.sema.original_range_opt(expr.syntax())?; Some(vec![Assist { id: AssistId("expected-field-found-method-call-fix", AssistKind::QuickFix), - label: Label::new("Use parentheses to call the method".to_string()), + label: Label::new("Use parentheses to call the method".to_owned()), group: None, target: range, source_change: Some(SourceChange::from_text_edit( diff --git a/crates/ide-diagnostics/src/handlers/unresolved_method.rs b/crates/ide-diagnostics/src/handlers/unresolved_method.rs index 8bbb837e6709..4106d9501bb9 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_method.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_method.rs @@ -70,7 +70,7 @@ fn field_fix( }; Some(vec![Assist { id: AssistId("expected-method-found-field-fix", AssistKind::QuickFix), - label: Label::new("Use parentheses to call the value of the field".to_string()), + label: Label::new("Use parentheses to call the value of the field".to_owned()), group: None, target: range, source_change: Some(SourceChange::from_iter([ diff --git a/crates/ide-diagnostics/src/handlers/unresolved_module.rs b/crates/ide-diagnostics/src/handlers/unresolved_module.rs index 6e3fd3b42b0c..bd1b020ae2ac 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_module.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_module.rs @@ -15,7 +15,7 @@ pub(crate) fn unresolved_module( Diagnostic::new( "unresolved-module", match &*d.candidates { - [] => "unresolved module".to_string(), + [] => "unresolved module".to_owned(), [candidate] => format!("unresolved module, can't find module file: {candidate}"), [candidates @ .., last] => { format!( @@ -45,7 +45,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedModule) -> Option format!("proc macro `{name}` not expanded"), - None => "proc macro not expanded".to_string(), + None => "proc macro not expanded".to_owned(), }; let severity = if config_enabled { Severity::Error } else { Severity::WeakWarning }; let def_map = ctx.sema.db.crate_def_map(d.krate); diff --git a/crates/ide-diagnostics/src/handlers/useless_braces.rs b/crates/ide-diagnostics/src/handlers/useless_braces.rs index 289ed0458c67..344160c9923e 100644 --- a/crates/ide-diagnostics/src/handlers/useless_braces.rs +++ b/crates/ide-diagnostics/src/handlers/useless_braces.rs @@ -33,7 +33,7 @@ pub(crate) fn useless_braces( acc.push( Diagnostic::new( "unnecessary-braces", - "Unnecessary braces in use statement".to_string(), + "Unnecessary braces in use statement".to_owned(), use_range, ) .severity(Severity::WeakWarning) diff --git a/crates/ide-diagnostics/src/tests.rs b/crates/ide-diagnostics/src/tests.rs index b5cd4e0d6891..31f6b39e8c7a 100644 --- a/crates/ide-diagnostics/src/tests.rs +++ b/crates/ide-diagnostics/src/tests.rs @@ -92,7 +92,7 @@ pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) { #[track_caller] pub(crate) fn check_diagnostics(ra_fixture: &str) { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("inactive-code".to_string()); + config.disabled.insert("inactive-code".to_owned()); check_diagnostics_with_config(config, ra_fixture) } @@ -159,7 +159,7 @@ fn minicore_smoke_test() { let source = minicore.source_code(); let mut config = DiagnosticsConfig::test_sample(); // This should be ignored since we conditionaly remove code which creates single item use with braces - config.disabled.insert("unnecessary-braces".to_string()); + config.disabled.insert("unnecessary-braces".to_owned()); check_diagnostics_with_config(config, &source); } diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index f8bc64ae9c9e..dc4dd052f00f 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -552,7 +552,7 @@ fn closure_ty( }) .join("\n"); if captures_rendered.trim().is_empty() { - captures_rendered = "This closure captures nothing".to_string(); + captures_rendered = "This closure captures nothing".to_owned(); } let mut targets: Vec = Vec::new(); let mut push_new_def = |item: hir::ModuleDef| { diff --git a/crates/ide/src/interpret_function.rs b/crates/ide/src/interpret_function.rs index 846d70ac307f..9ea826af2e33 100644 --- a/crates/ide/src/interpret_function.rs +++ b/crates/ide/src/interpret_function.rs @@ -15,8 +15,8 @@ use syntax::{algo::find_node_at_offset, ast, AstNode}; // |=== pub(crate) fn interpret_function(db: &RootDatabase, position: FilePosition) -> String { let start_time = Instant::now(); - let mut result = find_and_interpret(db, position) - .unwrap_or_else(|| "Not inside a function body".to_string()); + let mut result = + find_and_interpret(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()); let duration = Instant::now() - start_time; writeln!(result).unwrap(); writeln!(result, "----------------------").unwrap(); diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs index 1cfde2362455..c0a4f6873bfc 100644 --- a/crates/ide/src/join_lines.rs +++ b/crates/ide/src/join_lines.rs @@ -154,7 +154,7 @@ fn remove_newline( Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), None => { cov_mark::hit!(join_two_ifs); - edit.replace(token.text_range(), " else ".to_string()); + edit.replace(token.text_range(), " else ".to_owned()); return; } } diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 29c4ff5701f9..5411162b9c4b 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -228,7 +228,7 @@ impl Analysis { let mut host = AnalysisHost::default(); let file_id = FileId(0); let mut file_set = FileSet::default(); - file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string())); + file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned())); let source_root = SourceRoot::new_local(file_set); let mut change = Change::new(); diff --git a/crates/ide/src/markdown_remove.rs b/crates/ide/src/markdown_remove.rs index 718868c8747b..1bc2c36c528b 100644 --- a/crates/ide/src/markdown_remove.rs +++ b/crates/ide/src/markdown_remove.rs @@ -59,7 +59,7 @@ fn standalone_function() { pub fn public_thing(argument: bool) -> String { // code - # "".to_string() + # "".to_owned() } struct Thing { @@ -120,7 +120,7 @@ book] or the [Reference]. pub fn public_thing(argument: bool) -> String { // code - # "".to_string() + # "".to_owned() } struct Thing { diff --git a/crates/ide/src/moniker.rs b/crates/ide/src/moniker.rs index 42d8e50ad2b8..cf5996902c6e 100644 --- a/crates/ide/src/moniker.rs +++ b/crates/ide/src/moniker.rs @@ -264,12 +264,12 @@ pub(crate) fn def_to_moniker( ), CrateOrigin::Rustc { name } => ( name.clone(), - Some("https://github.com/rust-lang/rust/".to_string()), + Some("https://github.com/rust-lang/rust/".to_owned()), Some(format!("https://github.com/rust-lang/rust/compiler/{name}",)), ), CrateOrigin::Lang(lang) => ( krate.display_name(db)?.canonical_name().to_string(), - Some("https://github.com/rust-lang/rust/".to_string()), + Some("https://github.com/rust-lang/rust/".to_owned()), Some(match lang { LangCrateOrigin::Other => { "https://github.com/rust-lang/rust/library/".into() diff --git a/crates/ide/src/navigation_target.rs b/crates/ide/src/navigation_target.rs index 385c1b0c0081..654dbd362710 100644 --- a/crates/ide/src/navigation_target.rs +++ b/crates/ide/src/navigation_target.rs @@ -630,7 +630,7 @@ fn foo() { enum FooInner { } } "#, ); - let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap(); + let navs = analysis.symbol_search(Query::new("FooInner".to_owned())).unwrap(); expect![[r#" [ NavigationTarget { @@ -668,7 +668,7 @@ struct Foo; "#, ); - let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap(); + let navs = analysis.symbol_search(Query::new("foo".to_owned())).unwrap(); assert_eq!(navs.len(), 2) } } diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 27ad63d820d6..94144bb70abc 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -71,7 +71,7 @@ impl Runnable { RunnableKind::Bench { test_id } => format!("bench {test_id}"), RunnableKind::DocTest { test_id, .. } => format!("doctest {test_id}"), RunnableKind::Bin => { - target.map_or_else(|| "run binary".to_string(), |t| format!("run {t}")) + target.map_or_else(|| "run binary".to_owned(), |t| format!("run {t}")) } } } diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs index 51445ef255b5..3ae4f74fd1f7 100644 --- a/crates/ide/src/typing.rs +++ b/crates/ide/src/typing.rs @@ -137,10 +137,7 @@ fn on_opening_brace_typed(file: &Parse, offset: TextSize) -> Option< let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?; - Some(TextEdit::insert( - tree.syntax().text_range().end() + TextSize::of("{"), - "}".to_string(), - )) + Some(TextEdit::insert(tree.syntax().text_range().end() + TextSize::of("{"), "}".to_owned())) } fn brace_expr(file: &SourceFile, offset: TextSize) -> Option { @@ -167,10 +164,7 @@ fn on_opening_brace_typed(file: &Parse, offset: TextSize) -> Option< } // Insert `}` right after the expression. - Some(TextEdit::insert( - expr.syntax().text_range().end() + TextSize::of("{"), - "}".to_string(), - )) + Some(TextEdit::insert(expr.syntax().text_range().end() + TextSize::of("{"), "}".to_owned())) } } @@ -218,7 +212,7 @@ fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option { return None; } let offset = expr.syntax().text_range().end(); - Some(TextEdit::insert(offset, ";".to_string())) + Some(TextEdit::insert(offset, ";".to_owned())) } /// `a =$0 b;` removes the semicolon if an expression is valid in this context. @@ -258,7 +252,7 @@ fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option { return None; } let offset = let_stmt.syntax().text_range().end(); - Some(TextEdit::insert(offset, ";".to_string())) + Some(TextEdit::insert(offset, ";".to_owned())) } } @@ -336,7 +330,7 @@ fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option".to_string()), + edit: TextEdit::replace(range, "<$0>".to_owned()), is_snippet: true, }); } @@ -346,7 +340,7 @@ fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option".to_string()), + edit: TextEdit::replace(range, "<$0>".to_owned()), is_snippet: true, }); } @@ -368,7 +362,7 @@ fn on_right_angle_typed(file: &SourceFile, offset: TextSize) -> Option return None; } - Some(TextEdit::insert(after_arrow, " ".to_string())) + Some(TextEdit::insert(after_arrow, " ".to_owned())) } #[cfg(test)] diff --git a/crates/ide/src/view_hir.rs b/crates/ide/src/view_hir.rs index d2bbbf6d26ab..eac244b49971 100644 --- a/crates/ide/src/view_hir.rs +++ b/crates/ide/src/view_hir.rs @@ -12,7 +12,7 @@ use syntax::{algo::find_node_at_offset, ast, AstNode}; // |=== // image::https://user-images.githubusercontent.com/48062697/113065588-068bdb80-91b1-11eb-9a78-0b4ef1e972fb.gif[] pub(crate) fn view_hir(db: &RootDatabase, position: FilePosition) -> String { - body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_string()) + body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()) } fn body_hir(db: &RootDatabase, position: FilePosition) -> Option { diff --git a/crates/ide/src/view_mir.rs b/crates/ide/src/view_mir.rs index a36aba58bc0e..2b0d1026c61b 100644 --- a/crates/ide/src/view_mir.rs +++ b/crates/ide/src/view_mir.rs @@ -11,7 +11,7 @@ use syntax::{algo::find_node_at_offset, ast, AstNode}; // | VS Code | **rust-analyzer: View Mir** // |=== pub(crate) fn view_mir(db: &RootDatabase, position: FilePosition) -> String { - body_mir(db, position).unwrap_or_else(|| "Not inside a function body".to_string()) + body_mir(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()) } fn body_mir(db: &RootDatabase, position: FilePosition) -> Option { diff --git a/crates/proc-macro-api/src/lib.rs b/crates/proc-macro-api/src/lib.rs index 1603458f756e..195f0bbb6f18 100644 --- a/crates/proc-macro-api/src/lib.rs +++ b/crates/proc-macro-api/src/lib.rs @@ -162,7 +162,7 @@ impl ProcMacro { Ok(it.map(|tree| FlatTree::to_subtree(tree, version))) } msg::Response::ListMacros(..) | msg::Response::ApiVersionCheck(..) => { - Err(ServerError { message: "unexpected response".to_string(), io: None }) + Err(ServerError { message: "unexpected response".to_owned(), io: None }) } } } diff --git a/crates/proc-macro-api/src/process.rs b/crates/proc-macro-api/src/process.rs index 9a20fa63ed70..9bb78599d6d6 100644 --- a/crates/proc-macro-api/src/process.rs +++ b/crates/proc-macro-api/src/process.rs @@ -63,7 +63,7 @@ impl ProcMacroProcessSrv { match response { Response::ApiVersionCheck(version) => Ok(version), Response::ExpandMacro { .. } | Response::ListMacros { .. } => { - Err(ServerError { message: "unexpected response".to_string(), io: None }) + Err(ServerError { message: "unexpected response".to_owned(), io: None }) } } } @@ -79,7 +79,7 @@ impl ProcMacroProcessSrv { match response { Response::ListMacros(it) => Ok(it), Response::ExpandMacro { .. } | Response::ApiVersionCheck { .. } => { - Err(ServerError { message: "unexpected response".to_string(), io: None }) + Err(ServerError { message: "unexpected response".to_owned(), io: None }) } } } diff --git a/crates/proc-macro-srv/src/dylib.rs b/crates/proc-macro-srv/src/dylib.rs index dd05e250c2de..456b000b5278 100644 --- a/crates/proc-macro-srv/src/dylib.rs +++ b/crates/proc-macro-srv/src/dylib.rs @@ -154,7 +154,7 @@ impl Expander { attributes: Option<&crate::tt::Subtree>, ) -> Result { let result = self.inner.proc_macros.expand(macro_name, macro_body, attributes); - result.map_err(|e| e.as_str().unwrap_or_else(|| "".to_string())) + result.map_err(|e| e.as_str().unwrap_or_else(|| "".to_owned())) } pub fn list_macros(&self) -> Vec<(String, ProcMacroKind)> { diff --git a/crates/proc-macro-srv/src/proc_macros.rs b/crates/proc-macro-srv/src/proc_macros.rs index 3c6f32033192..7998ba5fd97d 100644 --- a/crates/proc-macro-srv/src/proc_macros.rs +++ b/crates/proc-macro-srv/src/proc_macros.rs @@ -92,7 +92,7 @@ impl ProcMacros { } } - Err(proc_macro::bridge::PanicMessage::String("Nothing to expand".to_string()).into()) + Err(proc_macro::bridge::PanicMessage::String("Nothing to expand".to_owned()).into()) } pub(crate) fn list_macros(&self) -> Vec<(String, ProcMacroKind)> { diff --git a/crates/proc-macro-test/build.rs b/crates/proc-macro-test/build.rs index 19a5caa4ccda..2a5e55d43217 100644 --- a/crates/proc-macro-test/build.rs +++ b/crates/proc-macro-test/build.rs @@ -86,7 +86,7 @@ fn main() { let mut artifact_path = None; for message in Message::parse_stream(output.stdout.as_slice()) { if let Message::CompilerArtifact(artifact) = message.unwrap() { - if artifact.target.kind.contains(&"proc-macro".to_string()) { + if artifact.target.kind.contains(&"proc-macro".to_owned()) { let repr = format!("{name} {version}"); if artifact.package_id.repr.starts_with(&repr) { artifact_path = Some(PathBuf::from(&artifact.filenames[0])); diff --git a/crates/project-model/src/build_scripts.rs b/crates/project-model/src/build_scripts.rs index 6cbf403cb2e1..98d0232db890 100644 --- a/crates/project-model/src/build_scripts.rs +++ b/crates/project-model/src/build_scripts.rs @@ -341,7 +341,7 @@ impl WorkspaceBuildScripts { if let Some(out_dir) = out_dir.as_os_str().to_str().map(|s| s.to_owned()) { - data.envs.push(("OUT_DIR".to_string(), out_dir)); + data.envs.push(("OUT_DIR".to_owned(), out_dir)); } data.out_dir = Some(out_dir); data.cfgs = cfgs; @@ -381,7 +381,7 @@ impl WorkspaceBuildScripts { let errors = if !output.status.success() { let errors = errors.into_inner(); - Some(if errors.is_empty() { "cargo check failed".to_string() } else { errors }) + Some(if errors.is_empty() { "cargo check failed".to_owned() } else { errors }) } else { None }; diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs index d767a82166ff..18dc6ce30d21 100644 --- a/crates/project-model/src/cargo_workspace.rs +++ b/crates/project-model/src/cargo_workspace.rs @@ -284,7 +284,7 @@ impl CargoWorkspace { // FIXME: Fetching metadata is a slow process, as it might require // calling crates.io. We should be reporting progress here, but it's // unclear whether cargo itself supports it. - progress("metadata".to_string()); + progress("metadata".to_owned()); (|| -> Result { let mut command = meta.cargo_command(); diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs index 34e5a4173400..a9d828b8a19e 100644 --- a/crates/project-model/src/tests.rs +++ b/crates/project-model/src/tests.rs @@ -129,7 +129,7 @@ fn get_fake_sysroot() -> Sysroot { } fn rooted_project_json(data: ProjectJsonData) -> ProjectJson { - let mut root = "$ROOT$".to_string(); + let mut root = "$ROOT$".to_owned(); replace_root(&mut root, true); let path = Path::new(&root); let base = AbsPath::assert(path); diff --git a/crates/rust-analyzer/src/caps.rs b/crates/rust-analyzer/src/caps.rs index ab06b96814a2..5211bda318e5 100644 --- a/crates/rust-analyzer/src/caps.rs +++ b/crates/rust-analyzer/src/caps.rs @@ -42,17 +42,17 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities { completion_provider: Some(CompletionOptions { resolve_provider: completions_resolve_provider(config.caps()), trigger_characters: Some(vec![ - ":".to_string(), - ".".to_string(), - "'".to_string(), - "(".to_string(), + ":".to_owned(), + ".".to_owned(), + "'".to_owned(), + "(".to_owned(), ]), all_commit_characters: None, completion_item: completion_item(config), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, }), signature_help_provider: Some(SignatureHelpOptions { - trigger_characters: Some(vec!["(".to_string(), ",".to_string(), "<".to_string()]), + trigger_characters: Some(vec!["(".to_owned(), ",".to_owned(), "<".to_owned()]), retrigger_characters: None, work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, }), @@ -72,7 +72,7 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities { _ => Some(OneOf::Left(false)), }, document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions { - first_trigger_character: "=".to_string(), + first_trigger_character: "=".to_owned(), more_trigger_character: Some(more_trigger_character(config)), }), selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)), @@ -218,9 +218,9 @@ fn code_action_capabilities(client_caps: &ClientCapabilities) -> CodeActionProvi } fn more_trigger_character(config: &Config) -> Vec { - let mut res = vec![".".to_string(), ">".to_string(), "{".to_string()]; + let mut res = vec![".".to_owned(), ">".to_owned(), "{".to_owned()]; if config.snippet_cap() { - res.push("<".to_string()); + res.push("<".to_owned()); } res } diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 823a211c6e28..b4f8b7ccf287 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -609,7 +609,7 @@ fn location_csv_expr( ) -> String { let src = match sm.expr_syntax(expr_id) { Ok(s) => s, - Err(SyntheticSyntax) => return "synthetic,,".to_string(), + Err(SyntheticSyntax) => return "synthetic,,".to_owned(), }; let root = db.parse_or_expand(src.file_id); let node = src.map(|e| e.to_node(&root).syntax().clone()); @@ -631,7 +631,7 @@ fn location_csv_pat( ) -> String { let src = match sm.pat_syntax(pat_id) { Ok(s) => s, - Err(SyntheticSyntax) => return "synthetic,,".to_string(), + Err(SyntheticSyntax) => return "synthetic,,".to_owned(), }; let root = db.parse_or_expand(src.file_id); let node = src.map(|e| { diff --git a/crates/rust-analyzer/src/cli/lsif.rs b/crates/rust-analyzer/src/cli/lsif.rs index e3fc29cfb604..ece8d904bfe9 100644 --- a/crates/rust-analyzer/src/cli/lsif.rs +++ b/crates/rust-analyzer/src/cli/lsif.rs @@ -105,12 +105,12 @@ impl LsifManager<'_> { let result_set_id = self.add_vertex(lsif::Vertex::PackageInformation(lsif::PackageInformation { name: pi.name, - manager: "cargo".to_string(), + manager: "cargo".to_owned(), uri: None, content: None, repository: pi.repo.map(|url| lsif::Repository { url, - r#type: "git".to_string(), + r#type: "git".to_owned(), commit_id: None, }), version: pi.version, @@ -149,7 +149,7 @@ impl LsifManager<'_> { let path = self.vfs.file_path(id); let path = path.as_path().unwrap(); let doc_id = self.add_vertex(lsif::Vertex::Document(lsif::Document { - language_id: "rust".to_string(), + language_id: "rust".to_owned(), uri: lsp_types::Url::from_file_path(path).unwrap(), })); self.file_map.insert(id, doc_id); @@ -176,7 +176,7 @@ impl LsifManager<'_> { if let Some(moniker) = token.moniker { let package_id = self.get_package_id(moniker.package_information); let moniker_id = self.add_vertex(lsif::Vertex::Moniker(lsp_types::Moniker { - scheme: "rust-analyzer".to_string(), + scheme: "rust-analyzer".to_owned(), identifier: moniker.identifier.to_string(), unique: lsp_types::UniquenessLevel::Scheme, kind: Some(match moniker.kind { @@ -315,7 +315,7 @@ impl flags::Lsif { project_root: lsp_types::Url::from_file_path(path).unwrap(), position_encoding: lsif::Encoding::Utf16, tool_info: Some(lsp_types::lsif::ToolInfo { - name: "rust-analyzer".to_string(), + name: "rust-analyzer".to_owned(), args: vec![], version: Some(version().to_string()), }), diff --git a/crates/rust-analyzer/src/cli/scip.rs b/crates/rust-analyzer/src/cli/scip.rs index 2d318bbec5b9..3d35f4fc5fd7 100644 --- a/crates/rust-analyzer/src/cli/scip.rs +++ b/crates/rust-analyzer/src/cli/scip.rs @@ -152,7 +152,7 @@ impl flags::Scip { documents.push(scip_types::Document { relative_path, - language: "rust".to_string(), + language: "rust".to_owned(), occurrences, symbols, special_fields: Default::default(), @@ -204,7 +204,7 @@ fn new_descriptor_str( ) -> scip_types::Descriptor { scip_types::Descriptor { name: name.to_string(), - disambiguator: "".to_string(), + disambiguator: "".to_owned(), suffix: suffix.into(), special_fields: Default::default(), } @@ -253,9 +253,9 @@ fn token_to_symbol(token: &TokenStaticData) -> Option { Some(scip_types::Symbol { scheme: "rust-analyzer".into(), package: Some(scip_types::Package { - manager: "cargo".to_string(), + manager: "cargo".to_owned(), name: package_name, - version: version.unwrap_or_else(|| ".".to_string()), + version: version.unwrap_or_else(|| ".".to_owned()), special_fields: Default::default(), }) .into(), diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index c3ea7939a4d8..3ef88ac556d2 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -841,7 +841,7 @@ impl Config { use serde::de::Error; if self.data.check_command.is_empty() { error_sink.push(( - "/check/command".to_string(), + "/check/command".to_owned(), serde_json::Error::custom("expected a non-empty string"), )); } diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs index e1d1130ff1b8..36e1bfeab13c 100644 --- a/crates/rust-analyzer/src/diagnostics/to_proto.rs +++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs @@ -396,16 +396,16 @@ pub(crate) fn map_rust_diagnostic_to_lsp( related_info_macro_calls.push(lsp_types::DiagnosticRelatedInformation { location: secondary_location.clone(), message: if is_in_macro_call { - "Error originated from macro call here".to_string() + "Error originated from macro call here".to_owned() } else { - "Actual error occurred here".to_string() + "Actual error occurred here".to_owned() }, }); // For the additional in-macro diagnostic we add the inverse message pointing to the error location in code. let information_for_additional_diagnostic = vec![lsp_types::DiagnosticRelatedInformation { location: primary_location.clone(), - message: "Exact error occurred here".to_string(), + message: "Exact error occurred here".to_owned(), }]; let diagnostic = lsp_types::Diagnostic { @@ -460,7 +460,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp( // `related_information`, which just produces hard-to-read links, at least in VS Code. let back_ref = lsp_types::DiagnosticRelatedInformation { location: primary_location, - message: "original diagnostic".to_string(), + message: "original diagnostic".to_owned(), }; for sub in &subdiagnostics { diagnostics.push(MappedRustDiagnostic { @@ -673,7 +673,7 @@ mod tests { fn rustc_unused_variable_as_info() { check_with_config( DiagnosticsMapConfig { - warnings_as_info: vec!["unused_variables".to_string()], + warnings_as_info: vec!["unused_variables".to_owned()], ..DiagnosticsMapConfig::default() }, r##"{ @@ -757,7 +757,7 @@ mod tests { fn rustc_unused_variable_as_hint() { check_with_config( DiagnosticsMapConfig { - warnings_as_hint: vec!["unused_variables".to_string()], + warnings_as_hint: vec!["unused_variables".to_owned()], ..DiagnosticsMapConfig::default() }, r##"{ diff --git a/crates/rust-analyzer/src/dispatch.rs b/crates/rust-analyzer/src/dispatch.rs index ebe77b8dfe72..dae00afb1dd3 100644 --- a/crates/rust-analyzer/src/dispatch.rs +++ b/crates/rust-analyzer/src/dispatch.rs @@ -116,7 +116,7 @@ impl<'a> RequestDispatcher<'a> { Err(_) => Task::Response(lsp_server::Response::new_err( req.id, lsp_server::ErrorCode::ContentModified as i32, - "content modified".to_string(), + "content modified".to_owned(), )), } } @@ -157,7 +157,7 @@ impl<'a> RequestDispatcher<'a> { let response = lsp_server::Response::new_err( req.id, lsp_server::ErrorCode::MethodNotFound as i32, - "unknown request".to_string(), + "unknown request".to_owned(), ); self.global_state.respond(response); } @@ -242,7 +242,7 @@ where .map(String::as_str) .or_else(|| panic.downcast_ref::<&str>().copied()); - let mut message = "request handler panicked".to_string(); + let mut message = "request handler panicked".to_owned(); if let Some(panic_message) = panic_message { message.push_str(": "); message.push_str(panic_message) diff --git a/crates/rust-analyzer/src/from_proto.rs b/crates/rust-analyzer/src/from_proto.rs index cd74a5500d0a..1f2a9051c7fe 100644 --- a/crates/rust-analyzer/src/from_proto.rs +++ b/crates/rust-analyzer/src/from_proto.rs @@ -103,7 +103,7 @@ pub(crate) fn annotation( code_lens: lsp_types::CodeLens, ) -> Result> { let data = - code_lens.data.ok_or_else(|| invalid_params_error("code lens without data".to_string()))?; + code_lens.data.ok_or_else(|| invalid_params_error("code lens without data".to_owned()))?; let resolve = from_json::("CodeLensResolveData", &data)?; match resolve.kind { diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs index 7b16c9f1f11e..a1655f00be9b 100644 --- a/crates/rust-analyzer/src/handlers/notification.rs +++ b/crates/rust-analyzer/src/handlers/notification.rs @@ -153,7 +153,7 @@ pub(crate) fn handle_did_change_configuration( lsp_types::ConfigurationParams { items: vec![lsp_types::ConfigurationItem { scope_uri: None, - section: Some("rust-analyzer".to_string()), + section: Some("rust-analyzer".to_owned()), }], }, |this, resp| { @@ -205,7 +205,7 @@ pub(crate) fn handle_did_change_workspace_folders( if !config.has_linked_projects() && config.detached_files().is_empty() { config.rediscover_workspaces(); - state.fetch_workspaces_queue.request_op("client workspaces changed".to_string(), ()) + state.fetch_workspaces_queue.request_op("client workspaces changed".to_owned(), ()) } Ok(()) diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs index 52a85054ea31..3410777667a3 100644 --- a/crates/rust-analyzer/src/handlers/request.rs +++ b/crates/rust-analyzer/src/handlers/request.rs @@ -52,7 +52,7 @@ pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> Result< state.proc_macro_clients = Arc::from(Vec::new()); state.proc_macro_changed = false; - state.fetch_workspaces_queue.request_op("reload workspace request".to_string(), ()); + state.fetch_workspaces_queue.request_op("reload workspace request".to_owned(), ()); Ok(()) } @@ -61,7 +61,7 @@ pub(crate) fn handle_proc_macros_rebuild(state: &mut GlobalState, _: ()) -> Resu state.proc_macro_clients = Arc::from(Vec::new()); state.proc_macro_changed = false; - state.fetch_build_data_queue.request_op("rebuild proc macros request".to_string(), ()); + state.fetch_build_data_queue.request_op("rebuild proc macros request".to_owned(), ()); Ok(()) } @@ -798,13 +798,13 @@ pub(crate) fn handle_runnables( None => { if !snap.config.linked_projects().is_empty() { res.push(lsp_ext::Runnable { - label: "cargo check --workspace".to_string(), + label: "cargo check --workspace".to_owned(), location: None, kind: lsp_ext::RunnableKind::Cargo, args: lsp_ext::CargoRunnable { workspace_root: None, override_cargo: config.override_cargo, - cargo_args: vec!["check".to_string(), "--workspace".to_string()], + cargo_args: vec!["check".to_owned(), "--workspace".to_owned()], cargo_extra_args: config.cargo_extra_args, executable_args: Vec::new(), expect_test: None, @@ -878,7 +878,7 @@ pub(crate) fn handle_completion_resolve( if !all_edits_are_disjoint(&original_completion, &[]) { return Err(invalid_params_error( - "Received a completion with overlapping edits, this is not LSP-compliant".to_string(), + "Received a completion with overlapping edits, this is not LSP-compliant".to_owned(), ) .into()); } @@ -1163,7 +1163,7 @@ pub(crate) fn handle_code_action_resolve( let _p = profile::span("handle_code_action_resolve"); let params = match code_action.data.take() { Some(it) => it, - None => return Err(invalid_params_error("code action without data".to_string()).into()), + None => return Err(invalid_params_error("code action without data".to_owned()).into()), }; let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?; @@ -1231,7 +1231,7 @@ fn parse_action_id(action_id: &str) -> Result<(usize, SingleResolve), String> { }; Ok((index, SingleResolve { assist_id: assist_id_string.to_string(), assist_kind })) } - _ => Err("Action id contains incorrect number of segments".to_string()), + _ => Err("Action id contains incorrect number of segments".to_owned()), } } diff --git a/crates/rust-analyzer/src/lsp_utils.rs b/crates/rust-analyzer/src/lsp_utils.rs index c45e2ee22267..8fe7a64990aa 100644 --- a/crates/rust-analyzer/src/lsp_utils.rs +++ b/crates/rust-analyzer/src/lsp_utils.rs @@ -347,21 +347,20 @@ mod tests { #[test] fn empty_completion_disjoint_tests() { - let empty_completion = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + let empty_completion = CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); let disjoint_edit_1 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(3, 3), Position::new(4, 4)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); assert!( @@ -389,19 +388,19 @@ mod tests { fn completion_with_joint_edits_disjoint_tests() { let disjoint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(2, 2)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); let mut completion_with_joint_edits = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); completion_with_joint_edits.additional_text_edits = Some(vec![disjoint_edit.clone(), joint_edit.clone()]); assert!( @@ -419,7 +418,7 @@ mod tests { completion_with_joint_edits.text_edit = Some(CompletionTextEdit::InsertAndReplace(InsertReplaceEdit { - new_text: "new_text".to_string(), + new_text: "new_text".to_owned(), insert: disjoint_edit.range, replace: disjoint_edit_2.range, })); @@ -434,19 +433,19 @@ mod tests { fn completion_with_disjoint_edits_disjoint_tests() { let disjoint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(2, 2)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); let mut completion_with_disjoint_edits = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); completion_with_disjoint_edits.text_edit = Some(CompletionTextEdit::Edit(disjoint_edit)); let completion_with_disjoint_edits = completion_with_disjoint_edits; diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index 5c024ddcfd0b..cad3849b5c33 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -115,7 +115,7 @@ impl GlobalState { self.register_did_save_capability(); } - self.fetch_workspaces_queue.request_op("startup".to_string(), ()); + self.fetch_workspaces_queue.request_op("startup".to_owned(), ()); if let Some((cause, ())) = self.fetch_workspaces_queue.should_start_op() { self.fetch_workspaces(cause); } @@ -159,8 +159,8 @@ impl GlobalState { }; let registration = lsp_types::Registration { - id: "textDocument/didSave".to_string(), - method: "textDocument/didSave".to_string(), + id: "textDocument/didSave".to_owned(), + method: "textDocument/didSave".to_owned(), register_options: Some(serde_json::to_value(save_registration_options).unwrap()), }; self.send_request::( @@ -252,7 +252,7 @@ impl GlobalState { self.prime_caches_queue.op_completed(()); if cancelled { self.prime_caches_queue - .request_op("restart after cancellation".to_string(), ()); + .request_op("restart after cancellation".to_owned(), ()); } } }; @@ -293,7 +293,7 @@ impl GlobalState { self.flycheck.iter().for_each(FlycheckHandle::restart); } if self.config.prefill_caches() { - self.prime_caches_queue.request_op("became quiescent".to_string(), ()); + self.prime_caches_queue.request_op("became quiescent".to_owned(), ()); } } @@ -340,7 +340,7 @@ impl GlobalState { // See https://github.com/rust-lang/rust-analyzer/issues/13130 let patch_empty = |message: &mut String| { if message.is_empty() { - *message = " ".to_string(); + *message = " ".to_owned(); } }; @@ -475,12 +475,12 @@ impl GlobalState { } let old = Arc::clone(&self.workspaces); - self.switch_workspaces("fetched workspace".to_string()); + self.switch_workspaces("fetched workspace".to_owned()); let workspaces_updated = !Arc::ptr_eq(&old, &self.workspaces); if self.config.run_build_scripts() && workspaces_updated { self.fetch_build_data_queue - .request_op("workspace updated".to_string(), ()); + .request_op("workspace updated".to_owned(), ()); } (Progress::End, None) @@ -499,7 +499,7 @@ impl GlobalState { tracing::error!("FetchBuildDataError:\n{e}"); } - self.switch_workspaces("fetched build data".to_string()); + self.switch_workspaces("fetched build data".to_owned()); (Some(Progress::End), None) } @@ -833,7 +833,7 @@ impl GlobalState { )) .unwrap(), }), - source: Some("rust-analyzer".to_string()), + source: Some("rust-analyzer".to_owned()), message: d.message, related_information: None, tags: if d.unused { diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index 9db638f6d68e..fd468d2b1a43 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -85,7 +85,7 @@ impl GlobalState { ); } if self.config.linked_projects() != old_config.linked_projects() { - self.fetch_workspaces_queue.request_op("linked projects changed".to_string(), ()) + self.fetch_workspaces_queue.request_op("linked projects changed".to_owned(), ()) } else if self.config.flycheck() != old_config.flycheck() { self.reload_flycheck(); } @@ -407,8 +407,8 @@ impl GlobalState { .collect(), }; let registration = lsp_types::Registration { - id: "workspace/didChangeWatchedFiles".to_string(), - method: "workspace/didChangeWatchedFiles".to_string(), + id: "workspace/didChangeWatchedFiles".to_owned(), + method: "workspace/didChangeWatchedFiles".to_owned(), register_options: Some(serde_json::to_value(registration_options).unwrap()), }; self.send_request::( @@ -753,7 +753,7 @@ pub(crate) fn load_proc_macro( let dylib = MacroDylib::new(path.to_path_buf()); let vec = server.load_dylib(dylib).map_err(|e| format!("{e}"))?; if vec.is_empty() { - return Err("proc macro library returned no proc macros".to_string()); + return Err("proc macro library returned no proc macros".to_owned()); } Ok(vec .into_iter() diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs index 0bb29e7080fb..18d44d36881a 100644 --- a/crates/rust-analyzer/tests/slow-tests/main.rs +++ b/crates/rust-analyzer/tests/slow-tests/main.rs @@ -621,9 +621,9 @@ fn main() {{}} server.notification::(DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: server.doc_id(&format!("src/m{i}.rs")).uri, - language_id: "rust".to_string(), + language_id: "rust".to_owned(), version: 0, - text: "/// Docs\nfn foo() {}".to_string(), + text: "/// Docs\nfn foo() {}".to_owned(), }, }); } diff --git a/crates/rust-analyzer/tests/slow-tests/support.rs b/crates/rust-analyzer/tests/slow-tests/support.rs index 689d4ebe5722..a2ae17a0e4cf 100644 --- a/crates/rust-analyzer/tests/slow-tests/support.rs +++ b/crates/rust-analyzer/tests/slow-tests/support.rs @@ -166,7 +166,7 @@ impl Server { let (connection, client) = Connection::memory(); let _thread = stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker) - .name("test server".to_string()) + .name("test server".to_owned()) .spawn(move || main_loop(config, connection).unwrap()) .expect("failed to spawn a thread"); diff --git a/crates/sourcegen/src/lib.rs b/crates/sourcegen/src/lib.rs index c5da6ceb4d19..75810bf7f701 100644 --- a/crates/sourcegen/src/lib.rs +++ b/crates/sourcegen/src/lib.rs @@ -67,7 +67,7 @@ impl CommentBlock { panic!("Use plain (non-doc) comments with tags like {tag}:\n {first}"); } - block.id = id.trim().to_string(); + block.id = id.trim().to_owned(); true }); blocks @@ -91,7 +91,7 @@ impl CommentBlock { if let Some(' ') = contents.chars().next() { contents = &contents[1..]; } - block.contents.push(contents.to_string()); + block.contents.push(contents.to_owned()); } None => { if !block.contents.is_empty() { diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 93e35229c149..c90ed98bb6c2 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -232,7 +232,7 @@ pub fn impl_( let where_clause = match where_clause { Some(pr) => pr.to_string(), - None => " ".to_string(), + None => " ".to_owned(), }; let body = match body { @@ -278,7 +278,7 @@ pub fn impl_trait( let is_negative = if is_negative { "! " } else { "" }; let where_clause = match (ty_where_clause, trait_where_clause) { - (None, None) => " ".to_string(), + (None, None) => " ".to_owned(), (None, Some(tr)) => format!("\n{}\n", tr), (Some(ty), None) => format!("\n{}\n", ty), (Some(ty), Some(tr)) => { @@ -369,7 +369,7 @@ pub fn use_tree( alias: Option, add_star: bool, ) -> ast::UseTree { - let mut buf = "use ".to_string(); + let mut buf = "use ".to_owned(); buf += &path.syntax().to_string(); if let Some(use_tree_list) = use_tree_list { format_to!(buf, "::{use_tree_list}"); @@ -436,7 +436,7 @@ pub fn block_expr( stmts: impl IntoIterator, tail_expr: Option, ) -> ast::BlockExpr { - let mut buf = "{\n".to_string(); + let mut buf = "{\n".to_owned(); for stmt in stmts.into_iter() { format_to!(buf, " {stmt}\n"); } @@ -459,7 +459,7 @@ pub fn hacky_block_expr( elements: impl IntoIterator, tail_expr: Option, ) -> ast::BlockExpr { - let mut buf = "{\n".to_string(); + let mut buf = "{\n".to_owned(); for node_or_token in elements.into_iter() { match node_or_token { rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"), diff --git a/crates/test-utils/src/bench_fixture.rs b/crates/test-utils/src/bench_fixture.rs index 9296fd2e6835..d83f95768628 100644 --- a/crates/test-utils/src/bench_fixture.rs +++ b/crates/test-utils/src/bench_fixture.rs @@ -12,7 +12,7 @@ pub fn big_struct() -> String { } pub fn big_struct_n(n: u32) -> String { - let mut buf = "pub struct RegisterBlock {".to_string(); + let mut buf = "pub struct RegisterBlock {".to_owned(); for i in 0..n { format_to!(buf, " /// Doc comment for {}.\n", i); format_to!(buf, " pub s{}: S{},\n", i, i); diff --git a/crates/test-utils/src/fixture.rs b/crates/test-utils/src/fixture.rs index 05f32f8e51ea..b54717064ad3 100644 --- a/crates/test-utils/src/fixture.rs +++ b/crates/test-utils/src/fixture.rs @@ -192,7 +192,7 @@ impl FixtureWithProjectMeta { let mut env = FxHashMap::default(); let mut introduce_new_source_root = None; let mut target_data_layout = Some( - "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128".to_string(), + "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128".to_owned(), ); for component in components[1..].iter() { let (key, value) = @@ -423,9 +423,9 @@ fn parse_fixture_gets_full_meta() { mod m; "#, ); - assert_eq!(toolchain, Some("nightly".to_string())); - assert_eq!(proc_macro_names, vec!["identity".to_string()]); - assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]); + assert_eq!(toolchain, Some("nightly".to_owned())); + assert_eq!(proc_macro_names, vec!["identity".to_owned()]); + assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_owned()]); assert_eq!(1, parsed.len()); let meta = &parsed[0]; diff --git a/crates/text-edit/src/lib.rs b/crates/text-edit/src/lib.rs index 4705d18187af..1108f06f9cfb 100644 --- a/crates/text-edit/src/lib.rs +++ b/crates/text-edit/src/lib.rs @@ -231,11 +231,11 @@ mod tests { #[test] fn test_apply() { - let mut text = "_11h1_2222_xx3333_4444_6666".to_string(); + let mut text = "_11h1_2222_xx3333_4444_6666".to_owned(); let mut builder = TextEditBuilder::default(); - builder.replace(range(3, 4), "1".to_string()); + builder.replace(range(3, 4), "1".to_owned()); builder.delete(range(11, 13)); - builder.insert(22.into(), "_5555".to_string()); + builder.insert(22.into(), "_5555".to_owned()); let text_edit = builder.finish(); text_edit.apply(&mut text); diff --git a/crates/tt/src/lib.rs b/crates/tt/src/lib.rs index c2ebf03746a8..eeae1b212394 100644 --- a/crates/tt/src/lib.rs +++ b/crates/tt/src/lib.rs @@ -327,11 +327,11 @@ impl Subtree { }; match (it, last) { (Leaf::Ident(_), Some(&TokenTree::Leaf(Leaf::Ident(_)))) => { - " ".to_string() + &s + " ".to_owned() + &s } (Leaf::Punct(_), Some(TokenTree::Leaf(Leaf::Punct(punct)))) => { if punct.spacing == Spacing::Alone { - " ".to_string() + &s + " ".to_owned() + &s } else { s } diff --git a/crates/vfs/src/file_set.rs b/crates/vfs/src/file_set.rs index 0392ef3cebe9..6b8dec976d6b 100644 --- a/crates/vfs/src/file_set.rs +++ b/crates/vfs/src/file_set.rs @@ -71,12 +71,12 @@ impl fmt::Debug for FileSet { /// ```rust /// # use vfs::{file_set::FileSetConfigBuilder, VfsPath, Vfs}; /// let mut builder = FileSetConfigBuilder::default(); -/// builder.add_file_set(vec![VfsPath::new_virtual_path("/src".to_string())]); +/// builder.add_file_set(vec![VfsPath::new_virtual_path("/src".to_owned())]); /// let config = builder.build(); /// let mut file_system = Vfs::default(); -/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/main.rs".to_string()), Some(vec![])); -/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/lib.rs".to_string()), Some(vec![])); -/// file_system.set_file_contents(VfsPath::new_virtual_path("/build.rs".to_string()), Some(vec![])); +/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/main.rs".to_owned()), Some(vec![])); +/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/lib.rs".to_owned()), Some(vec![])); +/// file_system.set_file_contents(VfsPath::new_virtual_path("/build.rs".to_owned()), Some(vec![])); /// // contains the sets : /// // { "/src/main.rs", "/src/lib.rs" } /// // { "build.rs" } diff --git a/crates/vfs/src/loader.rs b/crates/vfs/src/loader.rs index e2d74782ae52..835d30f859c9 100644 --- a/crates/vfs/src/loader.rs +++ b/crates/vfs/src/loader.rs @@ -190,7 +190,7 @@ impl Directories { /// ``` fn dirs(base: AbsPathBuf, exclude: &[&str]) -> Directories { let exclude = exclude.iter().map(|it| base.join(it)).collect::>(); - Directories { extensions: vec!["rs".to_string()], include: vec![base], exclude } + Directories { extensions: vec!["rs".to_owned()], include: vec![base], exclude } } impl fmt::Debug for Message { diff --git a/crates/vfs/src/vfs_path.rs b/crates/vfs/src/vfs_path.rs index d327f2edf144..732cc967ad55 100644 --- a/crates/vfs/src/vfs_path.rs +++ b/crates/vfs/src/vfs_path.rs @@ -342,7 +342,7 @@ impl VirtualPath { /// # Example /// /// ```rust,ignore - /// let mut path = VirtualPath("/foo/bar".to_string()); + /// let mut path = VirtualPath("/foo/bar".to_owned()); /// path.pop(); /// assert_eq!(path.0, "/foo"); /// path.pop(); diff --git a/crates/vfs/src/vfs_path/tests.rs b/crates/vfs/src/vfs_path/tests.rs index 510e021e8903..2d89362ee069 100644 --- a/crates/vfs/src/vfs_path/tests.rs +++ b/crates/vfs/src/vfs_path/tests.rs @@ -2,29 +2,29 @@ use super::*; #[test] fn virtual_path_extensions() { - assert_eq!(VirtualPath("/".to_string()).name_and_extension(), None); + assert_eq!(VirtualPath("/".to_owned()).name_and_extension(), None); assert_eq!( - VirtualPath("/directory".to_string()).name_and_extension(), + VirtualPath("/directory".to_owned()).name_and_extension(), Some(("directory", None)) ); assert_eq!( - VirtualPath("/directory/".to_string()).name_and_extension(), + VirtualPath("/directory/".to_owned()).name_and_extension(), Some(("directory", None)) ); assert_eq!( - VirtualPath("/directory/file".to_string()).name_and_extension(), + VirtualPath("/directory/file".to_owned()).name_and_extension(), Some(("file", None)) ); assert_eq!( - VirtualPath("/directory/.file".to_string()).name_and_extension(), + VirtualPath("/directory/.file".to_owned()).name_and_extension(), Some((".file", None)) ); assert_eq!( - VirtualPath("/directory/.file.rs".to_string()).name_and_extension(), + VirtualPath("/directory/.file.rs".to_owned()).name_and_extension(), Some((".file", Some("rs"))) ); assert_eq!( - VirtualPath("/directory/file.rs".to_string()).name_and_extension(), + VirtualPath("/directory/file.rs".to_owned()).name_and_extension(), Some(("file", Some("rs"))) ); }