]> git.lizzy.rs Git - rust.git/commitdiff
Inline all format arguments where possible
authorYuri Astrakhan <YuriAstrakhan@gmail.com>
Fri, 23 Dec 2022 18:42:58 +0000 (13:42 -0500)
committerYuri Astrakhan <YuriAstrakhan@gmail.com>
Sat, 24 Dec 2022 19:36:10 +0000 (14:36 -0500)
This makes code more readale and concise,
moving all format arguments like `format!("{}", foo)`
into the more compact `format!("{foo}")` form.

The change was automatically created with, so there are far less change
of an accidental typo.

```
cargo clippy --fix -- -A clippy::all -W clippy::uninlined_format_args
```

180 files changed:
crates/base-db/src/fixture.rs
crates/base-db/src/input.rs
crates/base-db/src/lib.rs
crates/cfg/src/cfg_expr.rs
crates/cfg/src/lib.rs
crates/flycheck/src/lib.rs
crates/hir-def/src/attr.rs
crates/hir-def/src/body/pretty.rs
crates/hir-def/src/find_path.rs
crates/hir-def/src/import_map.rs
crates/hir-def/src/item_tree.rs
crates/hir-def/src/macro_expansion_tests.rs
crates/hir-def/src/nameres.rs
crates/hir-def/src/nameres/collector.rs
crates/hir-def/src/nameres/mod_resolution.rs
crates/hir-def/src/nameres/path_resolution.rs
crates/hir-def/src/nameres/tests/incremental.rs
crates/hir-def/src/pretty.rs
crates/hir-expand/src/db.rs
crates/hir-expand/src/eager.rs
crates/hir-expand/src/fixup.rs
crates/hir-expand/src/quote.rs
crates/hir-ty/src/builder.rs
crates/hir-ty/src/consteval.rs
crates/hir-ty/src/consteval/tests.rs
crates/hir-ty/src/diagnostics/match_check.rs
crates/hir-ty/src/diagnostics/match_check/deconstruct_pat.rs
crates/hir-ty/src/display.rs
crates/hir-ty/src/interner.rs
crates/hir-ty/src/lib.rs
crates/hir-ty/src/tests.rs
crates/hir-ty/src/tests/incremental.rs
crates/hir-ty/src/tests/macros.rs
crates/hir-ty/src/tls.rs
crates/hir-ty/src/traits.rs
crates/hir/src/attrs.rs
crates/hir/src/display.rs
crates/hir/src/lib.rs
crates/hir/src/semantics.rs
crates/ide-assists/src/handlers/generate_delegate_methods.rs
crates/ide-assists/src/handlers/generate_enum_projection_method.rs
crates/ide-assists/src/handlers/generate_getter.rs
crates/ide-assists/src/tests.rs
crates/ide-assists/src/tests/sourcegen.rs
crates/ide-completion/src/completions.rs
crates/ide-completion/src/completions/attribute/cfg.rs
crates/ide-completion/src/completions/attribute/lint.rs
crates/ide-completion/src/completions/env_vars.rs
crates/ide-completion/src/completions/fn_param.rs
crates/ide-completion/src/completions/item_list/trait_impl.rs
crates/ide-completion/src/completions/postfix.rs
crates/ide-completion/src/completions/postfix/format_like.rs
crates/ide-completion/src/completions/snippet.rs
crates/ide-completion/src/context/tests.rs
crates/ide-completion/src/item.rs
crates/ide-completion/src/render.rs
crates/ide-completion/src/render/function.rs
crates/ide-completion/src/render/macro_.rs
crates/ide-completion/src/render/variant.rs
crates/ide-completion/src/snippet.rs
crates/ide-completion/src/tests.rs
crates/ide-completion/src/tests/expression.rs
crates/ide-completion/src/tests/item.rs
crates/ide-completion/src/tests/item_list.rs
crates/ide-completion/src/tests/pattern.rs
crates/ide-completion/src/tests/predicate.rs
crates/ide-completion/src/tests/type_pos.rs
crates/ide-db/src/assists.rs
crates/ide-db/src/imports/import_assets.rs
crates/ide-db/src/imports/insert_use/tests.rs
crates/ide-db/src/rename.rs
crates/ide-db/src/symbol_index.rs
crates/ide-db/src/syntax_helpers/format_string_exprs.rs
crates/ide-db/src/tests/sourcegen_lints.rs
crates/ide-diagnostics/src/handlers/mismatched_arg_count.rs
crates/ide-diagnostics/src/handlers/no_such_field.rs
crates/ide-diagnostics/src/handlers/type_mismatch.rs
crates/ide-diagnostics/src/handlers/unlinked_file.rs
crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs
crates/ide-diagnostics/src/handlers/unresolved_module.rs
crates/ide-diagnostics/src/handlers/unresolved_proc_macro.rs
crates/ide-diagnostics/src/lib.rs
crates/ide-diagnostics/src/tests.rs
crates/ide-diagnostics/src/tests/sourcegen.rs
crates/ide-ssr/src/parsing.rs
crates/ide-ssr/src/tests.rs
crates/ide/src/doc_links.rs
crates/ide/src/doc_links/intra_doc_links.rs
crates/ide/src/doc_links/tests.rs
crates/ide/src/goto_definition.rs
crates/ide/src/hover.rs
crates/ide/src/hover/render.rs
crates/ide/src/hover/tests.rs
crates/ide/src/inlay_hints.rs
crates/ide/src/inlay_hints/bind_pat.rs
crates/ide/src/markup.rs
crates/ide/src/moniker.rs
crates/ide/src/navigation_target.rs
crates/ide/src/rename.rs
crates/ide/src/runnables.rs
crates/ide/src/static_index.rs
crates/ide/src/status.rs
crates/ide/src/syntax_highlighting/html.rs
crates/ide/src/syntax_tree.rs
crates/ide/src/typing.rs
crates/ide/src/typing/on_enter.rs
crates/limit/src/lib.rs
crates/mbe/src/benchmark.rs
crates/mbe/src/syntax_bridge.rs
crates/mbe/src/syntax_bridge/tests.rs
crates/mbe/src/to_parser_input.rs
crates/parser/src/parser.rs
crates/parser/src/tests.rs
crates/parser/src/tests/sourcegen_inline_tests.rs
crates/proc-macro-api/src/lib.rs
crates/proc-macro-api/src/msg/flat.rs
crates/proc-macro-api/src/version.rs
crates/proc-macro-srv/src/abis/abi_1_58/proc_macro/mod.rs
crates/proc-macro-srv/src/abis/abi_1_58/ra_server.rs
crates/proc-macro-srv/src/abis/abi_1_63/ra_server.rs
crates/proc-macro-srv/src/lib.rs
crates/proc-macro-test/build.rs
crates/profile/src/hprof.rs
crates/profile/src/memory_usage.rs
crates/profile/src/stop_watch.rs
crates/project-model/src/build_scripts.rs
crates/project-model/src/cfg_flag.rs
crates/project-model/src/lib.rs
crates/project-model/src/project_json.rs
crates/project-model/src/sysroot.rs
crates/project-model/src/tests.rs
crates/rust-analyzer/src/bin/logger.rs
crates/rust-analyzer/src/bin/main.rs
crates/rust-analyzer/src/cli.rs
crates/rust-analyzer/src/cli/analysis_stats.rs
crates/rust-analyzer/src/cli/diagnostics.rs
crates/rust-analyzer/src/cli/flags.rs
crates/rust-analyzer/src/cli/highlight.rs
crates/rust-analyzer/src/cli/lsif.rs
crates/rust-analyzer/src/cli/progress_report.rs
crates/rust-analyzer/src/cli/scip.rs
crates/rust-analyzer/src/cli/ssr.rs
crates/rust-analyzer/src/cli/symbols.rs
crates/rust-analyzer/src/config.rs
crates/rust-analyzer/src/diagnostics/to_proto.rs
crates/rust-analyzer/src/dispatch.rs
crates/rust-analyzer/src/global_state.rs
crates/rust-analyzer/src/handlers.rs
crates/rust-analyzer/src/integrated_benchmarks.rs
crates/rust-analyzer/src/lib.rs
crates/rust-analyzer/src/lsp_utils.rs
crates/rust-analyzer/src/main_loop.rs
crates/rust-analyzer/src/to_proto.rs
crates/rust-analyzer/tests/slow-tests/main.rs
crates/rust-analyzer/tests/slow-tests/sourcegen.rs
crates/rust-analyzer/tests/slow-tests/support.rs
crates/rust-analyzer/tests/slow-tests/testdir.rs
crates/rust-analyzer/tests/slow-tests/tidy.rs
crates/sourcegen/src/lib.rs
crates/stdx/src/panic_context.rs
crates/syntax/src/algo.rs
crates/syntax/src/ast/edit.rs
crates/syntax/src/ast/edit_in_place.rs
crates/syntax/src/ast/token_ext.rs
crates/syntax/src/fuzz.rs
crates/syntax/src/hacks.rs
crates/syntax/src/ted.rs
crates/syntax/src/tests.rs
crates/syntax/src/tests/sourcegen_ast.rs
crates/test-utils/src/assert_linear.rs
crates/test-utils/src/fixture.rs
crates/test-utils/src/lib.rs
crates/tt/src/lib.rs
crates/vfs/src/vfs_path.rs
lib/lsp-server/examples/goto_def.rs
lib/lsp-server/src/lib.rs
xtask/src/dist.rs
xtask/src/metrics.rs
xtask/src/release.rs
xtask/src/release/changelog.rs

index 83286cf6b777da294c30911bb81bcabc83d06b03..6f83ea40e76f669a784fde7f3d745a7b758a52b6 100644 (file)
@@ -407,9 +407,9 @@ fn parse_crate(crate_str: String) -> (String, CrateOrigin, Option<String>) {
                 Some((version, url)) => {
                     (version, CrateOrigin::CratesIo { repo: Some(url.to_owned()), name: None })
                 }
-                _ => panic!("Bad crates.io parameter: {}", data),
+                _ => panic!("Bad crates.io parameter: {data}"),
             },
-            _ => panic!("Bad string for crate origin: {}", b),
+            _ => panic!("Bad string for crate origin: {b}"),
         };
         (a.to_owned(), origin, Some(version.to_string()))
     } else {
@@ -439,7 +439,7 @@ fn from(f: Fixture) -> FileMeta {
             introduce_new_source_root: f.introduce_new_source_root.map(|kind| match &*kind {
                 "local" => SourceRootKind::Local,
                 "library" => SourceRootKind::Library,
-                invalid => panic!("invalid source root kind '{}'", invalid),
+                invalid => panic!("invalid source root kind '{invalid}'"),
             }),
             target_data_layout: f.target_data_layout,
         }
index 20bf8497cb5822ecc9524d4062f156828f88c652..5fa4a8024950997849e08e2f619a09e675350e44 100644 (file)
@@ -618,8 +618,8 @@ fn to(&self) -> &(CrateId, Option<CrateDisplayName>) {
 impl fmt::Display for CyclicDependenciesError {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         let render = |(id, name): &(CrateId, Option<CrateDisplayName>)| match name {
-            Some(it) => format!("{}({:?})", it, id),
-            None => format!("{:?}", id),
+            Some(it) => format!("{it}({id:?})"),
+            None => format!("{id:?}"),
         };
         let path = self.path.iter().rev().map(render).collect::<Vec<String>>().join(" -> ");
         write!(
index f725064cda9e3a5f15b123227549ca5dd28cea4f..55a51d3bbb2c784d91f14e42f4c7c3e5a0bf967a 100644 (file)
@@ -75,7 +75,7 @@ pub trait SourceDatabase: FileLoader + std::fmt::Debug {
 }
 
 fn parse_query(db: &dyn SourceDatabase, file_id: FileId) -> Parse<ast::SourceFile> {
-    let _p = profile::span("parse_query").detail(|| format!("{:?}", file_id));
+    let _p = profile::span("parse_query").detail(|| format!("{file_id:?}"));
     let text = db.file_text(file_id);
     SourceFile::parse(&text)
 }
index fd9e31ed3b4f52472a47659ca7f159329e87c223..5f4eefa8366199e34130040f520b0dd0fd944266 100644 (file)
@@ -44,7 +44,7 @@ impl fmt::Display for CfgAtom {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             CfgAtom::Flag(name) => name.fmt(f),
-            CfgAtom::KeyValue { key, value } => write!(f, "{} = {:?}", key, value),
+            CfgAtom::KeyValue { key, value } => write!(f, "{key} = {value:?}"),
         }
     }
 }
index d78ef4fb11e7ff2b3f18931032fcc19984dba7ba..30709c968dacfaa1a4d06416471b2f7948bc932d 100644 (file)
@@ -37,7 +37,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
             .iter()
             .map(|atom| match atom {
                 CfgAtom::Flag(it) => it.to_string(),
-                CfgAtom::KeyValue { key, value } => format!("{}={}", key, value),
+                CfgAtom::KeyValue { key, value } => format!("{key}={value}"),
             })
             .collect::<Vec<_>>();
         items.sort();
@@ -175,7 +175,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                 atom.fmt(f)?;
             }
             let is_are = if self.enabled.len() == 1 { "is" } else { "are" };
-            write!(f, " {} enabled", is_are)?;
+            write!(f, " {is_are} enabled")?;
 
             if !self.disabled.is_empty() {
                 f.write_str(" and ")?;
@@ -194,7 +194,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                 atom.fmt(f)?;
             }
             let is_are = if self.disabled.len() == 1 { "is" } else { "are" };
-            write!(f, " {} disabled", is_are)?;
+            write!(f, " {is_are} disabled")?;
         }
 
         Ok(())
index f13088cd90eff5eefdaa3072404aa64d1dc67187..b3e7443d1c1c093b2f67805d7b9fb17baa112771 100644 (file)
@@ -60,9 +60,9 @@ pub enum FlycheckConfig {
 impl fmt::Display for FlycheckConfig {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
-            FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
+            FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {command}"),
             FlycheckConfig::CustomCommand { command, args, .. } => {
-                write!(f, "{} {}", command, args.join(" "))
+                write!(f, "{command} {}", args.join(" "))
             }
         }
     }
@@ -474,7 +474,7 @@ fn run(self) -> io::Result<(bool, String)> {
         );
         match output {
             Ok(_) => Ok((read_at_least_one_message, error)),
-            Err(e) => Err(io::Error::new(e.kind(), format!("{:?}: {}", e, error))),
+            Err(e) => Err(io::Error::new(e.kind(), format!("{e:?}: {error}"))),
         }
     }
 }
index 2b39c6f8da86bee737371f8fd86547d5ed281d11..ab5d180e1bb9ef7df385db25b5ff4876aa60d05d 100644 (file)
@@ -712,7 +712,7 @@ fn source_of_id(&self, id: AttrId) -> InFile<&Either<ast::Attr, ast::Comment>> {
         self.source
             .get(ast_idx)
             .map(|it| InFile::new(file_id, it))
-            .unwrap_or_else(|| panic!("cannot find attr at index {:?}", id))
+            .unwrap_or_else(|| panic!("cannot find attr at index {id:?}"))
     }
 }
 
index 162d173d52404d9adcc05c3eae3dde82c461a855..04279751f0c89fe062e13d32b223adb52f56cb8d 100644 (file)
@@ -32,7 +32,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo
                 Some(name) => name.to_string(),
                 None => "_".to_string(),
             };
-            format!("const {} = ", name)
+            format!("const {name} = ")
         }
         DefWithBodyId::VariantId(it) => {
             needs_semi = false;
@@ -42,7 +42,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo
                 Some(name) => name.to_string(),
                 None => "_".to_string(),
             };
-            format!("{}", name)
+            format!("{name}")
         }
     };
 
index c70e6fdccdcde56c5d6a18ba4fe5c5c235c65cdb..e90dc47cf38d63f068b0c3ed9a2eb057c278fbc4 100644 (file)
@@ -512,7 +512,7 @@ mod tests {
     fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
         let (db, pos) = TestDB::with_position(ra_fixture);
         let module = db.module_at_position(pos);
-        let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
+        let parsed_path_file = syntax::SourceFile::parse(&format!("use {path};"));
         let ast_path =
             parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
         let mod_path = ModPath::from_src(&db, ast_path, &Hygiene::new_unhygienic()).unwrap();
@@ -531,7 +531,7 @@ fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKin
 
         let found_path =
             find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind, false);
-        assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
+        assert_eq!(found_path, Some(mod_path), "{prefix_kind:?}");
     }
 
     fn check_found_path(
index 05e0ceb05a9a307a5dfa037fe71935534d906c37..193c766200885696cf49fdada08341a714bbc336 100644 (file)
@@ -243,7 +243,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                     ItemInNs::Values(_) => "v",
                     ItemInNs::Macros(_) => "m",
                 };
-                format!("- {} ({})", info.path, ns)
+                format!("- {} ({ns})", info.path)
             })
             .collect();
 
@@ -398,7 +398,7 @@ pub fn search_dependencies<'a>(
     krate: CrateId,
     query: Query,
 ) -> FxHashSet<ItemInNs> {
-    let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
+    let _p = profile::span("search_dependencies").detail(|| format!("{query:?}"));
 
     let graph = db.crate_graph();
     let import_maps: Vec<_> =
@@ -549,7 +549,7 @@ fn assoc_item_path(
                         None
                     }
                 })?;
-            return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
+            return Some(format!("{}::{assoc_item_name}", dependency_imports.path_of(trait_)?));
         }
         None
     }
@@ -589,7 +589,7 @@ fn check(ra_fixture: &str, expect: Expect) {
 
                 let map = db.import_map(krate);
 
-                Some(format!("{}:\n{:?}\n", name, map))
+                Some(format!("{name}:\n{map:?}\n"))
             })
             .sorted()
             .collect::<String>();
index 0aa531eff71f6f5e02e12f003c947e25c1dddf5e..80297f8adf16e2a14e43215f7b1c1827e619be86 100644 (file)
@@ -105,7 +105,7 @@ pub struct ItemTree {
 
 impl ItemTree {
     pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
-        let _p = profile::span("file_item_tree_query").detail(|| format!("{:?}", file_id));
+        let _p = profile::span("file_item_tree_query").detail(|| format!("{file_id:?}"));
         let syntax = match db.parse_or_expand(file_id) {
             Some(node) => node,
             None => return Default::default(),
@@ -132,7 +132,7 @@ pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) ->
                     ctx.lower_macro_stmts(stmts)
                 },
                 _ => {
-                    panic!("cannot create item tree from {:?} {}", syntax, syntax);
+                    panic!("cannot create item tree from {syntax:?} {syntax}");
                 },
             }
         };
index 81b9c5c4bfaf98bc3a43eb7cdacd050c38945e00..907cc98f7b59b6d83d138756a3830dc91db34d11 100644 (file)
@@ -179,7 +179,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
             if tree {
                 let tree = format!("{:#?}", parse.syntax_node())
                     .split_inclusive('\n')
-                    .map(|line| format!("// {}", line))
+                    .map(|line| format!("// {line}"))
                     .collect::<String>();
                 format_to!(expn_text, "\n{}", tree)
             }
index 09732d37106c03631b813fa15a6695b371ecc0a4..393747d304b7721a471703e0a7bc1fc241efd619 100644 (file)
@@ -461,7 +461,7 @@ fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
             for (name, child) in
                 map.modules[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
             {
-                let path = format!("{}::{}", path, name);
+                let path = format!("{path}::{name}");
                 buf.push('\n');
                 go(buf, map, &path, *child);
             }
index 1cd42500c080531348807f16397c5650c9e1bbc5..6e1f85bc081cbcf56fd2fcf64ab89f8b838f4f0f 100644 (file)
@@ -1017,7 +1017,7 @@ fn update_recursive(
                         None => true,
                         Some(old_vis) => {
                             let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
-                                panic!("`Tr as _` imports with unrelated visibilities {:?} and {:?} (trait {:?})", old_vis, vis, tr);
+                                panic!("`Tr as _` imports with unrelated visibilities {old_vis:?} and {vis:?} (trait {tr:?})");
                             });
 
                             if max_vis == old_vis {
index ca7bcc814e8f8e41e4ced5c765e48f22af51a505..11d20d3db39a5bc554f3b135fa8686bc886bc5f3 100644 (file)
@@ -74,12 +74,12 @@ pub(super) fn resolve_declaration(
                 candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
             }
             None if file_id.is_include_macro(db.upcast()) => {
-                candidate_files.push(format!("{}.rs", name));
-                candidate_files.push(format!("{}/mod.rs", name));
+                candidate_files.push(format!("{name}.rs"));
+                candidate_files.push(format!("{name}/mod.rs"));
             }
             None => {
-                candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
-                candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
+                candidate_files.push(format!("{}{name}.rs", self.dir_path.0));
+                candidate_files.push(format!("{}{name}/mod.rs", self.dir_path.0));
             }
         };
 
@@ -91,7 +91,7 @@ pub(super) fn resolve_declaration(
                 let (dir_path, root_non_dir_owner) = if is_mod_rs || attr_path.is_some() {
                     (DirPath::empty(), false)
                 } else {
-                    (DirPath::new(format!("{}/", name)), true)
+                    (DirPath::new(format!("{name}/")), true)
                 };
                 if let Some(mod_dir) = self.child(dir_path, root_non_dir_owner) {
                     return Ok((file_id, is_mod_rs, mod_dir));
@@ -156,7 +156,7 @@ fn join_attr(&self, mut attr: &str, relative_to_parent: bool) -> String {
         } else {
             attr
         };
-        let res = format!("{}{}", base, attr);
+        let res = format!("{base}{attr}");
         res
     }
 }
index 20d39ec6cb92e2c86b2a1c48d43de2ca627f73e1..c7c50fa94a0935034b63babb4a60b1a94757c445 100644 (file)
@@ -170,8 +170,8 @@ pub(super) fn resolve_path_fp_with_macro_single(
     ) -> ResolvePathResult {
         let graph = db.crate_graph();
         let _cx = stdx::panic_context::enter(format!(
-            "DefMap {:?} crate_name={:?} block={:?} path={}",
-            self.krate, graph[self.krate].display_name, self.block, path
+            "DefMap {:?} crate_name={:?} block={:?} path={path}",
+            self.krate, graph[self.krate].display_name, self.block
         ));
 
         let mut segments = path.segments().iter().enumerate();
index 2e8cb3621fce663e35bd4a4a3cf93d4fb7b590c7..f5190b76db058e33c0f69c04f159cf26fb6f91ab 100644 (file)
@@ -13,7 +13,7 @@ fn check_def_map_is_not_recomputed(ra_fixture_initial: &str, ra_fixture_change:
         let events = db.log_executed(|| {
             db.crate_def_map(krate);
         });
-        assert!(format!("{:?}", events).contains("crate_def_map"), "{:#?}", events)
+        assert!(format!("{events:?}").contains("crate_def_map"), "{events:#?}")
     }
     db.set_file_text(pos.file_id, Arc::new(ra_fixture_change.to_string()));
 
@@ -21,7 +21,7 @@ fn check_def_map_is_not_recomputed(ra_fixture_initial: &str, ra_fixture_change:
         let events = db.log_executed(|| {
             db.crate_def_map(krate);
         });
-        assert!(!format!("{:?}", events).contains("crate_def_map"), "{:#?}", events)
+        assert!(!format!("{events:?}").contains("crate_def_map"), "{events:#?}")
     }
 }
 
@@ -94,7 +94,7 @@ fn f() {
             let (_, module_data) = crate_def_map.modules.iter().last().unwrap();
             assert_eq!(module_data.scope.resolutions().count(), 1);
         });
-        assert!(format!("{:?}", events).contains("crate_def_map"), "{:#?}", events)
+        assert!(format!("{events:?}").contains("crate_def_map"), "{events:#?}")
     }
     db.set_file_text(pos.file_id, Arc::new("m!(Y);".to_string()));
 
@@ -104,7 +104,7 @@ fn f() {
             let (_, module_data) = crate_def_map.modules.iter().last().unwrap();
             assert_eq!(module_data.scope.resolutions().count(), 1);
         });
-        assert!(!format!("{:?}", events).contains("crate_def_map"), "{:#?}", events)
+        assert!(!format!("{events:?}").contains("crate_def_map"), "{events:#?}")
     }
 }
 
index 933970d10e47282924e6496cbac5a33a2d17d76d..befd0c5ffa0550a9c3188661bbd35dd9380127d0 100644 (file)
@@ -92,7 +92,7 @@ pub(crate) fn print_generic_args(generics: &GenericArgs, buf: &mut dyn Write) ->
 pub(crate) fn print_generic_arg(arg: &GenericArg, buf: &mut dyn Write) -> fmt::Result {
     match arg {
         GenericArg::Type(ty) => print_type_ref(ty, buf),
-        GenericArg::Const(c) => write!(buf, "{}", c),
+        GenericArg::Const(c) => write!(buf, "{c}"),
         GenericArg::Lifetime(lt) => write!(buf, "{}", lt.name),
     }
 }
@@ -118,7 +118,7 @@ pub(crate) fn print_type_ref(type_ref: &TypeRef, buf: &mut dyn Write) -> fmt::Re
                 Mutability::Shared => "*const",
                 Mutability::Mut => "*mut",
             };
-            write!(buf, "{} ", mtbl)?;
+            write!(buf, "{mtbl} ")?;
             print_type_ref(pointee, buf)?;
         }
         TypeRef::Reference(pointee, lt, mtbl) => {
@@ -130,13 +130,13 @@ pub(crate) fn print_type_ref(type_ref: &TypeRef, buf: &mut dyn Write) -> fmt::Re
             if let Some(lt) = lt {
                 write!(buf, "{} ", lt.name)?;
             }
-            write!(buf, "{}", mtbl)?;
+            write!(buf, "{mtbl}")?;
             print_type_ref(pointee, buf)?;
         }
         TypeRef::Array(elem, len) => {
             write!(buf, "[")?;
             print_type_ref(elem, buf)?;
-            write!(buf, "; {}]", len)?;
+            write!(buf, "; {len}]")?;
         }
         TypeRef::Slice(elem) => {
             write!(buf, "[")?;
index 0096649be1460b2dc1b6c6f79d22b6100cbb510e..b28e60187defffb214fd7a0a52b39ae35db4e4c2 100644 (file)
@@ -444,7 +444,7 @@ fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Ar
         // be reported at the definition site (when we construct a def map).
         Err(err) => {
             return ExpandResult::only_err(ExpandError::Other(
-                format!("invalid macro definition: {}", err).into(),
+                format!("invalid macro definition: {err}").into(),
             ))
         }
     };
index 5fd099aea7d64a0b612f2ef98d6e247fbe315514..2f55e78b76343c4feb2d758bd1c28e8455764fc3 100644 (file)
@@ -161,7 +161,7 @@ pub fn expand_eager_macro(
 
         Ok(Ok(db.intern_macro_call(loc)))
     } else {
-        panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
+        panic!("called `expand_eager_macro` on non-eager macro def {def:?}");
     }
 }
 
index a4abe75626e6dcacf24df7e822857e404eecc919..75d364d5f846b2adac1965daf339cb119de99dba 100644 (file)
@@ -366,7 +366,7 @@ fn check(ra_fixture: &str, mut expect: Expect) {
             fixups.append,
         );
 
-        let actual = format!("{}\n", tt);
+        let actual = format!("{tt}\n");
 
         expect.indent(false);
         expect.assert_eq(&actual);
index e839e97bf02d88f86091ca1baeac843bcdd595c7..c0a7bc7ca8815f2d3760bd3848e0ad472f23bb74 100644 (file)
@@ -233,7 +233,7 @@ fn test_quote_hash_token_tree() {
 
         let quoted = quote!(#a);
         assert_eq!(quoted.to_string(), "hello");
-        let t = format!("{:?}", quoted);
+        let t = format!("{quoted:?}");
         assert_eq!(t, "SUBTREE $\n  IDENT   hello 4294967295");
     }
 
index 9ae752556d890df8161c55ea7f937f2fec581aa1..d5ef0c22dec83bcea0438d0e8726df13868dc9f8 100644 (file)
@@ -142,7 +142,7 @@ fn assert_match_kind(&self, a: &chalk_ir::GenericArg<Interner>, e: &ParamKind) {
         match (a.data(Interner), e) {
             (chalk_ir::GenericArgData::Ty(_), ParamKind::Type)
             | (chalk_ir::GenericArgData::Const(_), ParamKind::Const(_)) => (),
-            _ => panic!("Mismatched kinds: {:?}, {:?}, {:?}", a, self.vec, self.param_kinds),
+            _ => panic!("Mismatched kinds: {a:?}, {:?}, {:?}", self.vec, self.param_kinds),
         }
     }
 }
index 340968525701aae7d738543858f32606b1c5275c..345cf63c4fd0071952f9383c4627f33db135fdc4 100644 (file)
@@ -90,14 +90,14 @@ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
             ComputedExpr::Literal(l) => match l {
                 Literal::Int(x, _) => {
                     if *x >= 10 {
-                        write!(f, "{} ({:#X})", x, x)
+                        write!(f, "{x} ({x:#X})")
                     } else {
                         x.fmt(f)
                     }
                 }
                 Literal::Uint(x, _) => {
                     if *x >= 10 {
-                        write!(f, "{} ({:#X})", x, x)
+                        write!(f, "{x} ({x:#X})")
                     } else {
                         x.fmt(f)
                     }
index b76506f6ebc2c867f3b19dcdfcaf31886f60527e..6ba03737cf8e42f2be297a25abe81062a619c41d 100644 (file)
@@ -14,7 +14,7 @@ fn check_number(ra_fixture: &str, answer: i128) {
     match r {
         ComputedExpr::Literal(Literal::Int(r, _)) => assert_eq!(r, answer),
         ComputedExpr::Literal(Literal::Uint(r, _)) => assert_eq!(r, answer as u128),
-        x => panic!("Expected number but found {:?}", x),
+        x => panic!("Expected number but found {x:?}"),
     }
 }
 
@@ -126,7 +126,7 @@ enum E { A = 1, }
             assert_eq!(name, "E::A");
             assert_eq!(val, 1);
         }
-        x => panic!("Expected enum but found {:?}", x),
+        x => panic!("Expected enum but found {x:?}"),
     }
 }
 
index e0905e01b6a1a49cd92fad87bb519b838230e424..8b0f051b46b629a0ac88eaef87d6dbb35290de09 100644 (file)
@@ -386,7 +386,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                 }
                 subpattern.hir_fmt(f)
             }
-            PatKind::LiteralBool { value } => write!(f, "{}", value),
+            PatKind::LiteralBool { value } => write!(f, "{value}"),
             PatKind::Or { pats } => f.write_joined(pats.iter(), " | "),
         }
     }
index 47d60fc41e700bc2962665e48ab04f6720b3884d..d130827a77e8487cbf6eeb020db7a02f21693ce0 100644 (file)
@@ -372,7 +372,7 @@ fn variant_id_for_adt(&self, adt: hir_def::AdtId) -> VariantId {
                     hir_def::AdtId::UnionId(id) => id.into(),
                 }
             }
-            _ => panic!("bad constructor {:?} for adt {:?}", self, adt),
+            _ => panic!("bad constructor {self:?} for adt {adt:?}"),
         }
     }
 
index 57a15d114f071e2520e9c3de8331b209caa2d723..66e813eed8b4a022b62729c0c2198fd0de5bca74 100644 (file)
@@ -176,13 +176,13 @@ pub fn write_joined<T: HirDisplay>(
         let mut first = true;
         for e in iter {
             if !first {
-                write!(self, "{}", sep)?;
+                write!(self, "{sep}")?;
             }
             first = false;
 
             // Abbreviate multiple omitted types with a single ellipsis.
             if self.should_truncate() {
-                return write!(self, "{}", TYPE_HINT_TRUNCATION);
+                return write!(self, "{TYPE_HINT_TRUNCATION}");
             }
 
             e.hir_fmt(self)?;
@@ -320,7 +320,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
 impl HirDisplay for ProjectionTy {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         if f.should_truncate() {
-            return write!(f, "{}", TYPE_HINT_TRUNCATION);
+            return write!(f, "{TYPE_HINT_TRUNCATION}");
         }
 
         let trait_ref = self.trait_ref(f.db);
@@ -342,7 +342,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
 impl HirDisplay for OpaqueTy {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         if f.should_truncate() {
-            return write!(f, "{}", TYPE_HINT_TRUNCATION);
+            return write!(f, "{TYPE_HINT_TRUNCATION}");
         }
 
         self.substitution.at(Interner, 0).hir_fmt(f)
@@ -385,7 +385,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
 impl HirDisplay for Ty {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         if f.should_truncate() {
-            return write!(f, "{}", TYPE_HINT_TRUNCATION);
+            return write!(f, "{TYPE_HINT_TRUNCATION}");
         }
 
         match self.kind(Interner) {
@@ -572,7 +572,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                             hir_def::AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
                             hir_def::AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
                         };
-                        write!(f, "{}", name)?;
+                        write!(f, "{name}")?;
                     }
                     DisplayTarget::SourceCode { module_id } => {
                         if let Some(path) = find_path::find_path(
@@ -581,7 +581,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                             module_id,
                             false,
                         ) {
-                            write!(f, "{}", path)?;
+                            write!(f, "{path}")?;
                         } else {
                             return Err(HirDisplayError::DisplaySourceCodeError(
                                 DisplaySourceCodeError::PathNotFound,
@@ -737,7 +737,7 @@ fn should_show(
                     if sig.params().is_empty() {
                         write!(f, "||")?;
                     } else if f.should_truncate() {
-                        write!(f, "|{}|", TYPE_HINT_TRUNCATION)?;
+                        write!(f, "|{TYPE_HINT_TRUNCATION}|")?;
                     } else {
                         write!(f, "|")?;
                         f.write_joined(sig.params(), ", ")?;
@@ -928,7 +928,7 @@ pub fn write_bounds_like_dyn_trait_with_prefix(
     default_sized: SizedByDefault,
     f: &mut HirFormatter<'_>,
 ) -> Result<(), HirDisplayError> {
-    write!(f, "{}", prefix)?;
+    write!(f, "{prefix}")?;
     if !predicates.is_empty()
         || predicates.is_empty() && matches!(default_sized, SizedByDefault::Sized { .. })
     {
@@ -1056,7 +1056,7 @@ fn fmt_trait_ref(
     use_as: bool,
 ) -> Result<(), HirDisplayError> {
     if f.should_truncate() {
-        return write!(f, "{}", TYPE_HINT_TRUNCATION);
+        return write!(f, "{TYPE_HINT_TRUNCATION}");
     }
 
     tr.self_type_parameter(Interner).hir_fmt(f)?;
@@ -1083,7 +1083,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
 impl HirDisplay for WhereClause {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         if f.should_truncate() {
-            return write!(f, "{}", TYPE_HINT_TRUNCATION);
+            return write!(f, "{TYPE_HINT_TRUNCATION}");
         }
 
         match self {
@@ -1197,7 +1197,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                     hir_def::type_ref::Mutability::Shared => "*const ",
                     hir_def::type_ref::Mutability::Mut => "*mut ",
                 };
-                write!(f, "{}", mutability)?;
+                write!(f, "{mutability}")?;
                 inner.hir_fmt(f)?;
             }
             TypeRef::Reference(inner, lifetime, mutability) => {
@@ -1209,13 +1209,13 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                 if let Some(lifetime) = lifetime {
                     write!(f, "{} ", lifetime.name)?;
                 }
-                write!(f, "{}", mutability)?;
+                write!(f, "{mutability}")?;
                 inner.hir_fmt(f)?;
             }
             TypeRef::Array(inner, len) => {
                 write!(f, "[")?;
                 inner.hir_fmt(f)?;
-                write!(f, "; {}]", len)?;
+                write!(f, "; {len}]")?;
             }
             TypeRef::Slice(inner) => {
                 write!(f, "[")?;
@@ -1232,7 +1232,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                     for index in 0..function_parameters.len() {
                         let (param_name, param_type) = &function_parameters[index];
                         if let Some(name) = param_name {
-                            write!(f, "{}: ", name)?;
+                            write!(f, "{name}: ")?;
                         }
 
                         param_type.hir_fmt(f)?;
@@ -1408,7 +1408,7 @@ impl HirDisplay for hir_def::path::GenericArg {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         match self {
             hir_def::path::GenericArg::Type(ty) => ty.hir_fmt(f),
-            hir_def::path::GenericArg::Const(c) => write!(f, "{}", c),
+            hir_def::path::GenericArg::Const(c) => write!(f, "{c}"),
             hir_def::path::GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
         }
     }
index ca76e08fddb915ee1b10597a6149ab3295177c77..01b5719be4c0a90efc7d531bd81a5de32dd1a9d2 100644 (file)
@@ -143,7 +143,7 @@ fn debug_generic_arg(
 
     fn debug_goal(goal: &Goal<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
         let goal_data = goal.data(Interner);
-        Some(write!(fmt, "{:?}", goal_data))
+        Some(write!(fmt, "{goal_data:?}"))
     }
 
     fn debug_goals(
index 48581d4e0a41e3df075510998e95cb1ad709cb17..d3b445c017902a6acf691530bf3cf76ef4e3cad4 100644 (file)
@@ -513,7 +513,7 @@ fn try_fold_free_var_lifetime(
     let mut error_replacer = ErrorReplacer { vars: 0 };
     let value = match t.clone().try_fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
         Ok(t) => t,
-        Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
+        Err(_) => panic!("Encountered unbound or inference vars in {t:?}"),
     };
     let kinds = (0..error_replacer.vars).map(|_| {
         chalk_ir::CanonicalVarKind::new(
index ebbc5410147c6b8d63e8b4df5623fba06db5b4d5..7bcf89ff59c07922c5b0b7204b6601cc03afa7a5 100644 (file)
@@ -105,7 +105,7 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
                         .collect(),
                 );
             } else {
-                panic!("unexpected annotation: {}", expected);
+                panic!("unexpected annotation: {expected}");
             }
             had_annotations = true;
         }
@@ -181,11 +181,11 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
                         expected,
                         adjustments
                             .iter()
-                            .map(|Adjustment { kind, .. }| format!("{:?}", kind))
+                            .map(|Adjustment { kind, .. }| format!("{kind:?}"))
                             .collect::<Vec<_>>()
                     );
                 } else {
-                    panic!("expected {:?} adjustments, found none", expected);
+                    panic!("expected {expected:?} adjustments, found none");
                 }
             }
         }
index 3e08e83e89a3e2b045cd47f1a58996aeddc0f07e..073d6d9be2b9fab2466d5af807e0b9c3b6278409 100644 (file)
@@ -24,7 +24,7 @@ fn foo() -> i32 {
                 db.infer(def);
             });
         });
-        assert!(format!("{:?}", events).contains("infer"))
+        assert!(format!("{events:?}").contains("infer"))
     }
 
     let new_text = "
@@ -46,6 +46,6 @@ fn foo() -> i32 {
                 db.infer(def);
             });
         });
-        assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
+        assert!(!format!("{events:?}").contains("infer"), "{events:#?}")
     }
 }
index b3adafaafd38de8ea411754aa963079da3f3a309..8b75ec842a4f63560cbe26674b3df3854a4304af 100644 (file)
@@ -849,7 +849,7 @@ fn main() {
   //^^^^^^^^^^^^^^^^^ RegisterBlock
 }
     "#;
-    let fixture = format!("{}\n//- /foo.rs\n{}", fixture, data);
+    let fixture = format!("{fixture}\n//- /foo.rs\n{data}");
 
     {
         let _b = bench("include macro");
index 92711a24fe39fdc317328f7c76894c859ef76e64..b7e6ee6740be7c74dfdc134168f1cec746310a6a 100644 (file)
@@ -67,12 +67,12 @@ pub(crate) fn debug_projection_ty(
         let trait_ref = projection_ty.trait_ref(self.0);
         let trait_params = trait_ref.substitution.as_slice(Interner);
         let self_ty = trait_ref.self_type_parameter(Interner);
-        write!(fmt, "<{:?} as {}", self_ty, trait_name)?;
+        write!(fmt, "<{self_ty:?} as {trait_name}")?;
         if trait_params.len() > 1 {
             write!(
                 fmt,
                 "<{}>",
-                trait_params[1..].iter().format_with(", ", |x, f| f(&format_args!("{:?}", x))),
+                trait_params[1..].iter().format_with(", ", |x, f| f(&format_args!("{x:?}"))),
             )?;
         }
         write!(fmt, ">::{}", type_alias_data.name)?;
@@ -83,7 +83,7 @@ pub(crate) fn debug_projection_ty(
             write!(
                 fmt,
                 "<{}>",
-                proj_params.iter().format_with(", ", |x, f| f(&format_args!("{:?}", x))),
+                proj_params.iter().format_with(", ", |x, f| f(&format_args!("{x:?}"))),
             )?;
         }
 
@@ -105,9 +105,9 @@ pub(crate) fn debug_fn_def_id(
             }
         };
         match def {
-            CallableDefId::FunctionId(_) => write!(fmt, "{{fn {}}}", name),
+            CallableDefId::FunctionId(_) => write!(fmt, "{{fn {name}}}"),
             CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {
-                write!(fmt, "{{ctor {}}}", name)
+                write!(fmt, "{{ctor {name}}}")
             }
         }
     }
index da454eeb42eaedec5d4368593bb38cf9e25abbf8..615fd9d94db69accd6a991d5685d2374eb075b89 100644 (file)
@@ -130,7 +130,7 @@ fn solve(
 
     let mut solve = || {
         let _ctx = if is_chalk_debug() || is_chalk_print() {
-            Some(panic_context::enter(format!("solving {:?}", goal)))
+            Some(panic_context::enter(format!("solving {goal:?}")))
         } else {
             None
         };
index 0bd37934001094d901dd75cc11eedd48ac69dd32..54425d69b6b7f789d62f723b54c27703d61e7782 100644 (file)
@@ -148,7 +148,7 @@ fn resolve_doc_path(
 
     let modpath = {
         // FIXME: this is not how we should get a mod path here
-        let ast_path = ast::SourceFile::parse(&format!("type T = {};", link))
+        let ast_path = ast::SourceFile::parse(&format!("type T = {link};"))
             .syntax_node()
             .descendants()
             .find_map(ast::Path::cast)?;
index 27b2f445d73cabfb415cf8d7b5625569e6355767..5a4b2f3344968dcd83bf00074077dad1ceae2c12 100644 (file)
@@ -79,7 +79,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
                 }
             }
             match name {
-                Some(name) => write!(f, "{}: ", name)?,
+                Some(name) => write!(f, "{name}: ")?,
                 None => f.write_str("_: ")?,
             }
             // FIXME: Use resolved `param.ty` or raw `type_ref`?
@@ -327,7 +327,7 @@ fn write_generic_params(
                         continue;
                     }
                     delim(f)?;
-                    write!(f, "{}", name)?;
+                    write!(f, "{name}")?;
                     if let Some(default) = &ty.default {
                         f.write_str(" = ")?;
                         default.hir_fmt(f)?;
@@ -335,7 +335,7 @@ fn write_generic_params(
                 }
                 TypeOrConstParamData::ConstParamData(c) => {
                     delim(f)?;
-                    write!(f, "const {}: ", name)?;
+                    write!(f, "const {name}: ")?;
                     c.ty.hir_fmt(f)?;
                 }
             }
@@ -372,7 +372,7 @@ fn write_where_clause(def: GenericDefId, f: &mut HirFormatter<'_>) -> Result<(),
         WherePredicateTypeTarget::TypeRef(ty) => ty.hir_fmt(f),
         WherePredicateTypeTarget::TypeOrConstParam(id) => {
             match &params.type_or_consts[*id].name() {
-                Some(name) => write!(f, "{}", name),
+                Some(name) => write!(f, "{name}"),
                 None => f.write_str("{unnamed}"),
             }
         }
@@ -424,7 +424,7 @@ fn write_where_clause(def: GenericDefId, f: &mut HirFormatter<'_>) -> Result<(),
                         if idx != 0 {
                             f.write_str(", ")?;
                         }
-                        write!(f, "{}", lifetime)?;
+                        write!(f, "{lifetime}")?;
                     }
                     f.write_str("> ")?;
                     write_target(target, f)?;
@@ -447,7 +447,7 @@ fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         let data = f.db.const_data(self.id);
         f.write_str("const ")?;
         match &data.name {
-            Some(name) => write!(f, "{}: ", name)?,
+            Some(name) => write!(f, "{name}: ")?,
             None => f.write_str("_: ")?,
         }
         data.type_ref.hir_fmt(f)?;
@@ -511,9 +511,9 @@ impl HirDisplay for Module {
     fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
         // FIXME: Module doesn't have visibility saved in data.
         match self.name(f.db) {
-            Some(name) => write!(f, "mod {}", name),
+            Some(name) => write!(f, "mod {name}"),
             None if self.is_crate_root(f.db) => match self.krate(f.db).display_name(f.db) {
-                Some(name) => write!(f, "extern crate {}", name),
+                Some(name) => write!(f, "extern crate {name}"),
                 None => f.write_str("extern crate {unknown}"),
             },
             None => f.write_str("mod {unnamed}"),
index aabfd170487ecefed7bbe98e50e900fd9871208f..3f8acdfd2ff952eab398fbdadd6faac35dd3dca3 100644 (file)
@@ -813,7 +813,7 @@ fn precise_macro_call_location(
                 .doc_comments_and_attrs()
                 .nth((*invoc_attr_index) as usize)
                 .and_then(Either::left)
-                .unwrap_or_else(|| panic!("cannot find attribute #{}", invoc_attr_index));
+                .unwrap_or_else(|| panic!("cannot find attribute #{invoc_attr_index}"));
 
             (
                 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
index 55950da9d54f34ed019f711fe8b99b17591eb6f6..a255dc1972ceba4e3c25713c41c4d8dc994f9893 100644 (file)
@@ -1378,7 +1378,7 @@ fn find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode>
                 self.cache
                     .borrow()
                     .keys()
-                    .map(|it| format!("{:?}", it))
+                    .map(|it| format!("{it:?}"))
                     .collect::<Vec<_>>()
                     .join(", ")
             )
index ceae80755037c00b56f401edb70c5a6264cb176e..c2c5bf3aabb19c616401ee75b9275cc9b8648896 100644 (file)
@@ -81,7 +81,7 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
         acc.add_group(
             &GroupLabel("Generate delegate methods…".to_owned()),
             AssistId("generate_delegate_methods", AssistKind::Generate),
-            format!("Generate delegate for `{}.{}()`", field_name, method.name(ctx.db())),
+            format!("Generate delegate for `{field_name}.{}()`", method.name(ctx.db())),
             target,
             |builder| {
                 // Create the function
index c9aa41c845ad5c0b0a964cb6d0d059167dd1d416..ee643ce9a4ac306c4bc76de73a715eaad8794d5b 100644 (file)
@@ -157,7 +157,7 @@ fn generate_enum_projection_method(
         assist_description,
         target,
         |builder| {
-            let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{} ", v));
+            let vis = parent_enum.visibility().map_or(String::new(), |v| format!("{v} "));
 
             let field_type_syntax = field_type.syntax();
 
index 5e71914283495e7a44afd3310bb015406285a38c..a82dde2333776b64f0f43538d14aae9d41bbb690 100644 (file)
@@ -235,7 +235,7 @@ fn generate_getter_from_info(
 ) -> String {
     let mut buf = String::with_capacity(512);
 
-    let vis = info.strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
+    let vis = info.strukt.visibility().map_or(String::new(), |v| format!("{v} "));
     let (ty, body) = if info.mutable {
         (
             format!("&mut {}", record_field_info.field_ty),
index 92ced27c78aedf801b3c5eee80a066aea043be72..fca268a1f0b2d57e3806803cddb930f0c12d7786 100644 (file)
@@ -171,7 +171,7 @@ fn check(handler: Handler, before: &str, expected: ExpectedResult<'_>, assist_la
                     }
                     FileSystemEdit::MoveDir { src, src_id, dst } => {
                         // temporary placeholder for MoveDir since we are not using MoveDir in ide assists yet.
-                        (dst, format!("{:?}\n{:?}", src_id, src))
+                        (dst, format!("{src_id:?}\n{src:?}"))
                     }
                 };
                 let sr = db.file_source_root(dst.anchor);
index 070b83d3c16b17f36aad45ddd055fefb0bc49927..c574d6bc631aacdbd95093aa3e31b652fa5177b2 100644 (file)
@@ -18,7 +18,7 @@ fn sourcegen_assists_docs() {
         for assist in assists.iter() {
             for (idx, section) in assist.sections.iter().enumerate() {
                 let test_id =
-                    if idx == 0 { assist.id.clone() } else { format!("{}_{}", &assist.id, idx) };
+                    if idx == 0 { assist.id.clone() } else { format!("{}_{idx}", &assist.id) };
                 let test = format!(
                     r######"
 #[test]
@@ -175,7 +175,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 fn hide_hash_comments(text: &str) -> String {
     text.split('\n') // want final newline
         .filter(|&it| !(it.starts_with("# ") || it == "#"))
-        .map(|it| format!("{}\n", it))
+        .map(|it| format!("{it}\n"))
         .collect()
 }
 
@@ -190,6 +190,6 @@ fn reveal_hash_comments(text: &str) -> String {
                 it
             }
         })
-        .map(|it| format!("{}\n", it))
+        .map(|it| format!("{it}\n"))
         .collect()
 }
index ba5afde19bcf75ec4a798e1894886aab94be5f26..eb87d6c58262d43078e6098261a3ccf588f6f982 100644 (file)
@@ -133,7 +133,7 @@ pub(crate) fn add_keyword_snippet_expr(
                 if incomplete_let && snippet.ends_with('}') {
                     // complete block expression snippets with a trailing semicolon, if inside an incomplete let
                     cov_mark::hit!(let_semi);
-                    item.insert_snippet(cap, format!("{};", snippet));
+                    item.insert_snippet(cap, format!("{snippet};"));
                 } else {
                     item.insert_snippet(cap, snippet);
                 }
index 311060143b06a19c8d08ea437f6791827b41e09b..7ef4ff30b56c7c1b82cbbb21a81b4fdc34887dd7 100644 (file)
@@ -11,7 +11,7 @@
 pub(crate) fn complete_cfg(acc: &mut Completions, ctx: &CompletionContext<'_>) {
     let add_completion = |item: &str| {
         let mut completion = CompletionItem::new(SymbolKind::BuiltinAttr, ctx.source_range(), item);
-        completion.insert_text(format!(r#""{}""#, item));
+        completion.insert_text(format!(r#""{item}""#));
         acc.add(completion.build());
     };
 
@@ -29,7 +29,7 @@ pub(crate) fn complete_cfg(acc: &mut Completions, ctx: &CompletionContext<'_>) {
         Some("target_vendor") => KNOWN_VENDOR.iter().copied().for_each(add_completion),
         Some("target_endian") => ["little", "big"].into_iter().for_each(add_completion),
         Some(name) => ctx.krate.potential_cfg(ctx.db).get_cfg_values(name).cloned().for_each(|s| {
-            let insert_text = format!(r#""{}""#, s);
+            let insert_text = format!(r#""{s}""#);
             let mut item = CompletionItem::new(SymbolKind::BuiltinAttr, ctx.source_range(), s);
             item.insert_text(insert_text);
 
index 967f6ddd9a83b3b2196fa29e0979549954304bed..818c3cfd5fe7f1c2701b5994f5b68291e708c9c6 100644 (file)
@@ -51,7 +51,7 @@ pub(super) fn complete_lint(
             continue;
         }
         let label = match qual {
-            Some(qual) if !is_qualified => format!("{}::{}", qual, name),
+            Some(qual) if !is_qualified => format!("{qual}::{name}"),
             _ => name.to_owned(),
         };
         let mut item = CompletionItem::new(SymbolKind::Attribute, ctx.source_range(), label);
index 09e95e53de63ce42f31791d8c092a2772b4e9501..a094e857bbad7a5ceebf35a22b644f6375bde7d2 100644 (file)
@@ -112,7 +112,7 @@ fn main() {
         "#;
 
         let completions = completion_list(fixture);
-        assert!(completions.is_empty(), "Completions weren't empty: {}", completions);
+        assert!(completions.is_empty(), "Completions weren't empty: {completions}");
     }
 
     #[test]
@@ -129,7 +129,7 @@ fn main() {
         "#;
 
         let completions = completion_list(fixture);
-        assert!(completions.is_empty(), "Completions weren't empty: {}", completions);
+        assert!(completions.is_empty(), "Completions weren't empty: {completions}");
     }
 
     #[test]
@@ -145,6 +145,6 @@ fn main() {
         "#;
 
         let completions = completion_list(fixture);
-        assert!(completions.is_empty(), "Completions weren't empty: {}", completions)
+        assert!(completions.is_empty(), "Completions weren't empty: {completions}")
     }
 }
index f0ecc595af33eaf22838510b6ff35fcc44ec9b48..d8b8a190eb840fc11cf40d2416ed0be79f98a10e 100644 (file)
@@ -192,5 +192,5 @@ fn comma_wrapper(ctx: &CompletionContext<'_>) -> Option<(impl Fn(&str) -> String
         matches!(prev_token_kind, SyntaxKind::COMMA | SyntaxKind::L_PAREN | SyntaxKind::PIPE);
     let leading = if has_leading_comma { "" } else { ", " };
 
-    Some((move |label: &_| (format!("{}{}{}", leading, label, trailing)), param.text_range()))
+    Some((move |label: &_| (format!("{leading}{label}{trailing}")), param.text_range()))
 }
index 4a1bacfa9d9e131660bcccdbf66500a45fd50412..21ec13bba015c7a098406d63a4b75e82cb2a57ef 100644 (file)
@@ -190,7 +190,7 @@ fn add_function_impl(
     };
 
     let mut item = CompletionItem::new(completion_kind, replacement_range, label);
-    item.lookup_by(format!("fn {}", fn_name))
+    item.lookup_by(format!("fn {fn_name}"))
         .set_documentation(func.docs(ctx.db))
         .set_relevance(CompletionRelevance { is_item_from_trait: true, ..Default::default() });
 
@@ -205,11 +205,11 @@ fn add_function_impl(
             let function_decl = function_declaration(&transformed_fn, source.file_id.is_macro());
             match ctx.config.snippet_cap {
                 Some(cap) => {
-                    let snippet = format!("{} {{\n    $0\n}}", function_decl);
+                    let snippet = format!("{function_decl} {{\n    $0\n}}");
                     item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet));
                 }
                 None => {
-                    let header = format!("{} {{", function_decl);
+                    let header = format!("{function_decl} {{");
                     item.text_edit(TextEdit::replace(replacement_range, header));
                 }
             };
@@ -249,10 +249,10 @@ fn add_type_alias_impl(
 ) {
     let alias_name = type_alias.name(ctx.db).unescaped().to_smol_str();
 
-    let label = format!("type {} =", alias_name);
+    let label = format!("type {alias_name} =");
 
     let mut item = CompletionItem::new(SymbolKind::TypeAlias, replacement_range, label);
-    item.lookup_by(format!("type {}", alias_name))
+    item.lookup_by(format!("type {alias_name}"))
         .set_documentation(type_alias.docs(ctx.db))
         .set_relevance(CompletionRelevance { is_item_from_trait: true, ..Default::default() });
 
@@ -290,7 +290,7 @@ fn add_type_alias_impl(
 
             match ctx.config.snippet_cap {
                 Some(cap) => {
-                    let snippet = format!("{}$0;", decl);
+                    let snippet = format!("{decl}$0;");
                     item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet));
                 }
                 None => {
@@ -321,10 +321,10 @@ fn add_const_impl(
                 };
 
                 let label = make_const_compl_syntax(&transformed_const, source.file_id.is_macro());
-                let replacement = format!("{} ", label);
+                let replacement = format!("{label} ");
 
                 let mut item = CompletionItem::new(SymbolKind::Const, replacement_range, label);
-                item.lookup_by(format!("const {}", const_name))
+                item.lookup_by(format!("const {const_name}"))
                     .set_documentation(const_.docs(ctx.db))
                     .set_relevance(CompletionRelevance {
                         is_item_from_trait: true,
@@ -333,7 +333,7 @@ fn add_const_impl(
                 match ctx.config.snippet_cap {
                     Some(cap) => item.snippet_edit(
                         cap,
-                        TextEdit::replace(replacement_range, format!("{}$0;", replacement)),
+                        TextEdit::replace(replacement_range, format!("{replacement}$0;")),
                     ),
                     None => item.text_edit(TextEdit::replace(replacement_range, replacement)),
                 };
index 31ec9d9f6396b63d6ac0d0990fc365b3385710a8..2404491c1f09e0ad3056f20be2a9d92f81edea23 100644 (file)
@@ -61,7 +61,7 @@ pub(crate) fn complete_postfix(
                 let mut item = postfix_snippet(
                     "drop",
                     "fn drop(&mut self)",
-                    &format!("drop($0{})", receiver_text),
+                    &format!("drop($0{receiver_text})"),
                 );
                 item.set_documentation(drop_fn.docs(ctx.db));
                 item.add_to(acc);
@@ -76,14 +76,14 @@ pub(crate) fn complete_postfix(
                 postfix_snippet(
                     "ifl",
                     "if let Ok {}",
-                    &format!("if let Ok($1) = {} {{\n    $0\n}}", receiver_text),
+                    &format!("if let Ok($1) = {receiver_text} {{\n    $0\n}}"),
                 )
                 .add_to(acc);
 
                 postfix_snippet(
                     "while",
                     "while let Ok {}",
-                    &format!("while let Ok($1) = {} {{\n    $0\n}}", receiver_text),
+                    &format!("while let Ok($1) = {receiver_text} {{\n    $0\n}}"),
                 )
                 .add_to(acc);
             }
@@ -91,41 +91,37 @@ pub(crate) fn complete_postfix(
                 postfix_snippet(
                     "ifl",
                     "if let Some {}",
-                    &format!("if let Some($1) = {} {{\n    $0\n}}", receiver_text),
+                    &format!("if let Some($1) = {receiver_text} {{\n    $0\n}}"),
                 )
                 .add_to(acc);
 
                 postfix_snippet(
                     "while",
                     "while let Some {}",
-                    &format!("while let Some($1) = {} {{\n    $0\n}}", receiver_text),
+                    &format!("while let Some($1) = {receiver_text} {{\n    $0\n}}"),
                 )
                 .add_to(acc);
             }
         }
     } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
-        postfix_snippet("if", "if expr {}", &format!("if {} {{\n    $0\n}}", receiver_text))
+        postfix_snippet("if", "if expr {}", &format!("if {receiver_text} {{\n    $0\n}}"))
             .add_to(acc);
-        postfix_snippet(
-            "while",
-            "while expr {}",
-            &format!("while {} {{\n    $0\n}}", receiver_text),
-        )
-        .add_to(acc);
-        postfix_snippet("not", "!expr", &format!("!{}", receiver_text)).add_to(acc);
+        postfix_snippet("while", "while expr {}", &format!("while {receiver_text} {{\n    $0\n}}"))
+            .add_to(acc);
+        postfix_snippet("not", "!expr", &format!("!{receiver_text}")).add_to(acc);
     } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() {
         if receiver_ty.impls_trait(ctx.db, trait_, &[]) {
             postfix_snippet(
                 "for",
                 "for ele in expr {}",
-                &format!("for ele in {} {{\n    $0\n}}", receiver_text),
+                &format!("for ele in {receiver_text} {{\n    $0\n}}"),
             )
             .add_to(acc);
         }
     }
 
-    postfix_snippet("ref", "&expr", &format!("&{}", receiver_text)).add_to(acc);
-    postfix_snippet("refm", "&mut expr", &format!("&mut {}", receiver_text)).add_to(acc);
+    postfix_snippet("ref", "&expr", &format!("&{receiver_text}")).add_to(acc);
+    postfix_snippet("refm", "&mut expr", &format!("&mut {receiver_text}")).add_to(acc);
 
     // The rest of the postfix completions create an expression that moves an argument,
     // so it's better to consider references now to avoid breaking the compilation
@@ -148,7 +144,7 @@ pub(crate) fn complete_postfix(
                 postfix_snippet(
                     "match",
                     "match expr {}",
-                    &format!("match {} {{\n    Ok(${{1:_}}) => {{$2}},\n    Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
+                    &format!("match {receiver_text} {{\n    Ok(${{1:_}}) => {{$2}},\n    Err(${{3:_}}) => {{$0}},\n}}"),
                 )
                 .add_to(acc);
             }
@@ -168,21 +164,21 @@ pub(crate) fn complete_postfix(
             postfix_snippet(
                 "match",
                 "match expr {}",
-                &format!("match {} {{\n    ${{1:_}} => {{$0}},\n}}", receiver_text),
+                &format!("match {receiver_text} {{\n    ${{1:_}} => {{$0}},\n}}"),
             )
             .add_to(acc);
         }
     }
 
-    postfix_snippet("box", "Box::new(expr)", &format!("Box::new({})", receiver_text)).add_to(acc);
-    postfix_snippet("dbg", "dbg!(expr)", &format!("dbg!({})", receiver_text)).add_to(acc); // fixme
-    postfix_snippet("dbgr", "dbg!(&expr)", &format!("dbg!(&{})", receiver_text)).add_to(acc);
-    postfix_snippet("call", "function(expr)", &format!("${{1}}({})", receiver_text)).add_to(acc);
+    postfix_snippet("box", "Box::new(expr)", &format!("Box::new({receiver_text})")).add_to(acc);
+    postfix_snippet("dbg", "dbg!(expr)", &format!("dbg!({receiver_text})")).add_to(acc); // fixme
+    postfix_snippet("dbgr", "dbg!(&expr)", &format!("dbg!(&{receiver_text})")).add_to(acc);
+    postfix_snippet("call", "function(expr)", &format!("${{1}}({receiver_text})")).add_to(acc);
 
     if let Some(parent) = dot_receiver.syntax().parent().and_then(|p| p.parent()) {
         if matches!(parent.kind(), STMT_LIST | EXPR_STMT) {
-            postfix_snippet("let", "let", &format!("let $0 = {};", receiver_text)).add_to(acc);
-            postfix_snippet("letm", "let mut", &format!("let mut $0 = {};", receiver_text))
+            postfix_snippet("let", "let", &format!("let $0 = {receiver_text};")).add_to(acc);
+            postfix_snippet("letm", "let mut", &format!("let mut $0 = {receiver_text};"))
                 .add_to(acc);
         }
     }
@@ -300,7 +296,7 @@ fn add_custom_postfix_completions(
             let body = snippet.postfix_snippet(receiver_text);
             let mut builder =
                 postfix_snippet(trigger, snippet.description.as_deref().unwrap_or_default(), &body);
-            builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));
+            builder.documentation(Documentation::new(format!("```rust\n{body}\n```")));
             for import in imports.into_iter() {
                 builder.add_import(import);
             }
index b43bdb9ab9d1a5b861b148195bfdee890c56192e..d64d6379a9cde2de636f4677e08f7bae2157f312 100644 (file)
@@ -54,7 +54,7 @@ pub(crate) fn add_format_like_completions(
     if let Ok((out, exprs)) = parse_format_exprs(receiver_text.text()) {
         let exprs = with_placeholders(exprs);
         for (label, macro_name) in KINDS {
-            let snippet = format!(r#"{}({}, {})"#, macro_name, out, exprs.join(", "));
+            let snippet = format!(r#"{macro_name}({out}, {})"#, exprs.join(", "));
 
             postfix_snippet(label, macro_name, &snippet).add_to(acc);
         }
@@ -81,7 +81,7 @@ fn test_into_suggestion() {
         for (kind, input, output) in test_vector {
             let (parsed_string, exprs) = parse_format_exprs(input).unwrap();
             let exprs = with_placeholders(exprs);
-            let snippet = format!(r#"{}("{}", {})"#, kind, parsed_string, exprs.join(", "));
+            let snippet = format!(r#"{kind}("{parsed_string}", {})"#, exprs.join(", "));
             assert_eq!(&snippet, output);
         }
     }
index 66adb4286373a85deb59413905e85aa48df811bb..da1f0542d286ff25254e0ba77c5978dca0664d5e 100644 (file)
@@ -141,7 +141,7 @@ fn add_custom_completions(
             };
             let body = snip.snippet();
             let mut builder = snippet(ctx, cap, trigger, &body);
-            builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));
+            builder.documentation(Documentation::new(format!("```rust\n{body}\n```")));
             for import in imports.into_iter() {
                 builder.add_import(import);
             }
index 50845b3881f433953014dfa47d3ec00261806bf7..a654a5db57445e78822bcda000f4f5156cfb677a 100644 (file)
@@ -19,7 +19,7 @@ fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
     let name =
         completion_context.expected_name.map_or_else(|| "?".to_owned(), |name| name.to_string());
 
-    expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
+    expect.assert_eq(&format!("ty: {ty}, name: {name}"));
 }
 
 #[test]
index 27c3ccb35a1eaf263eb8610fce1ccfe1fc8bd5ab..657eab5b1b83036270479f3f6d37f1aa1151d327 100644 (file)
@@ -453,10 +453,10 @@ pub(crate) fn build(self) -> CompletionItem {
             // snippets can have multiple imports, but normal completions only have up to one
             if let Some(original_path) = import_edit.original_path.as_ref() {
                 lookup = lookup.or_else(|| Some(label.clone()));
-                label = SmolStr::from(format!("{} (use {})", label, original_path));
+                label = SmolStr::from(format!("{label} (use {original_path})"));
             }
         } else if let Some(trait_name) = self.trait_name {
-            label = SmolStr::from(format!("{} (as {})", label, trait_name));
+            label = SmolStr::from(format!("{label} (as {trait_name})"));
         }
 
         let text_edit = match self.text_edit {
index c3ffc6d50743b8088e46ef83b42a77ca0c246edb..e48d1aecd04fa621cb881a2fbe91c5065fd659a8 100644 (file)
@@ -144,8 +144,7 @@ pub(crate) fn render_field(
 }
 
 fn field_with_receiver(receiver: Option<&hir::Name>, field_name: &str) -> SmolStr {
-    receiver
-        .map_or_else(|| field_name.into(), |receiver| format!("{}.{}", receiver, field_name).into())
+    receiver.map_or_else(|| field_name.into(), |receiver| format!("{receiver}.{field_name}").into())
 }
 
 pub(crate) fn render_tuple_field(
@@ -306,7 +305,7 @@ fn render_resolution_path(
                 item.lookup_by(name.clone())
                     .label(SmolStr::from_iter([&name, "<…>"]))
                     .trigger_call_info()
-                    .insert_snippet(cap, format!("{}<$0>", local_name));
+                    .insert_snippet(cap, format!("{local_name}<$0>"));
             }
         }
     }
@@ -528,13 +527,13 @@ fn check_relevance_(actual: Vec<CompletionItem>, expect: Expect) {
 
                 let tag = it.kind().tag();
                 let relevance = display_relevance(it.relevance());
-                items.push(format!("{} {} {}\n", tag, it.label(), relevance));
+                items.push(format!("{tag} {} {relevance}\n", it.label()));
 
                 if let Some((mutability, _offset, relevance)) = it.ref_match() {
                     let label = format!("&{}{}", mutability.as_keyword_for_ref(), it.label());
                     let relevance = display_relevance(relevance);
 
-                    items.push(format!("{} {} {}\n", tag, label, relevance));
+                    items.push(format!("{tag} {label} {relevance}\n"));
                 }
 
                 items
@@ -563,7 +562,7 @@ fn display_relevance(relevance: CompletionRelevance) -> String {
             .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
             .join("+");
 
-            format!("[{}]", relevance_factors)
+            format!("[{relevance_factors}]")
         }
     }
 
index 37612084604764eee2c66ec568d9dc7fda0c236f..197592e78ce266f7b21fbff15b9f088768bfc039 100644 (file)
@@ -53,7 +53,7 @@ fn render(
     let (call, escaped_call) = match &func_kind {
         FuncKind::Method(_, Some(receiver)) => (
             format!("{}.{}", receiver.unescaped(), name.unescaped()).into(),
-            format!("{}.{}", receiver, name).into(),
+            format!("{receiver}.{name}").into(),
         ),
         _ => (name.unescaped().to_smol_str(), name.to_smol_str()),
     };
@@ -162,7 +162,7 @@ pub(super) fn add_call_parens<'b>(
     cov_mark::hit!(inserts_parens_for_function_calls);
 
     let (snippet, label_suffix) = if self_param.is_none() && params.is_empty() {
-        (format!("{}()$0", escaped_name), "()")
+        (format!("{escaped_name}()$0"), "()")
     } else {
         builder.trigger_call_info();
         let snippet = if let Some(CallableSnippets::FillArguments) = ctx.config.callable {
@@ -174,7 +174,7 @@ pub(super) fn add_call_parens<'b>(
                             let smol_str = n.to_smol_str();
                             let text = smol_str.as_str().trim_start_matches('_');
                             let ref_ = ref_of_param(ctx, text, param.ty());
-                            f(&format_args!("${{{}:{}{}}}", index + offset, ref_, text))
+                            f(&format_args!("${{{}:{ref_}{text}}}", index + offset))
                         }
                         None => {
                             let name = match param.ty().as_adt() {
@@ -185,7 +185,7 @@ pub(super) fn add_call_parens<'b>(
                                     .map(|s| to_lower_snake_case(s.as_str()))
                                     .unwrap_or_else(|| "_".to_string()),
                             };
-                            f(&format_args!("${{{}:{}}}", index + offset, name))
+                            f(&format_args!("${{{}:{name}}}", index + offset))
                         }
                     }
                 });
@@ -200,12 +200,12 @@ pub(super) fn add_call_parens<'b>(
                     )
                 }
                 None => {
-                    format!("{}({})$0", escaped_name, function_params_snippet)
+                    format!("{escaped_name}({function_params_snippet})$0")
                 }
             }
         } else {
             cov_mark::hit!(suppress_arg_snippets);
-            format!("{}($0)", escaped_name)
+            format!("{escaped_name}($0)")
         };
 
         (snippet, "(…)")
index eabd0bd17d65ffe4fc965f82aeb7d17eee43e4df..ffcad1185aa41d98f0aa08bbb178d6338744c2f1 100644 (file)
@@ -66,7 +66,7 @@ fn render(
 
     match ctx.snippet_cap() {
         Some(cap) if needs_bang && !has_call_parens => {
-            let snippet = format!("{}!{}$0{}", escaped_name, bra, ket);
+            let snippet = format!("{escaped_name}!{bra}$0{ket}");
             let lookup = banged_name(&name);
             item.insert_snippet(cap, snippet).lookup_by(lookup);
         }
index d69906a7065735d50b1bf32d6911272f6418d84b..5995da68a1650b40c7372105a4e35ecfddc560f9 100644 (file)
@@ -35,8 +35,8 @@ pub(crate) fn render_record_lit(
     });
 
     RenderedLiteral {
-        literal: format!("{} {{ {} }}", path, completions),
-        detail: format!("{} {{ {} }}", path, types),
+        literal: format!("{path} {{ {completions} }}"),
+        detail: format!("{path} {{ {types} }}"),
     }
 }
 
@@ -49,7 +49,7 @@ pub(crate) fn render_tuple_lit(
     path: &str,
 ) -> RenderedLiteral {
     if snippet_cap.is_none() {
-        return RenderedLiteral { literal: format!("{}", path), detail: format!("{}", path) };
+        return RenderedLiteral { literal: format!("{path}"), detail: format!("{path}") };
     }
     let completions = fields.iter().enumerate().format_with(", ", |(idx, _), f| {
         if snippet_cap.is_some() {
@@ -62,8 +62,8 @@ pub(crate) fn render_tuple_lit(
     let types = fields.iter().format_with(", ", |field, f| f(&field.ty(db).display(db)));
 
     RenderedLiteral {
-        literal: format!("{}({})", path, completions),
-        detail: format!("{}({})", path, types),
+        literal: format!("{path}({completions})"),
+        detail: format!("{path}({types})"),
     }
 }
 
index f3b8eae4fe8cd8c25fff08afa889326e37da642e..343719c53694e50992ecad8019300be2d666ee15 100644 (file)
@@ -199,7 +199,7 @@ fn validate_snippet(
 ) -> Option<(Box<[GreenNode]>, String, Option<Box<str>>)> {
     let mut imports = Vec::with_capacity(requires.len());
     for path in requires.iter() {
-        let use_path = ast::SourceFile::parse(&format!("use {};", path))
+        let use_path = ast::SourceFile::parse(&format!("use {path};"))
             .syntax_node()
             .descendants()
             .find_map(ast::Path::cast)?;
index 5e9011f9e8aa7d431039c527dc3023ede4438672..d206377e177a20dc10e23bc02085e5c8010fc5a0 100644 (file)
@@ -153,7 +153,7 @@ fn monospace_width(s: &str) -> usize {
         .into_iter()
         .map(|it| {
             let tag = it.kind().tag();
-            let var_name = format!("{} {}", tag, it.label());
+            let var_name = format!("{tag} {}", it.label());
             let mut buf = var_name;
             if let Some(detail) = it.detail() {
                 let width = label_width.saturating_sub(monospace_width(it.label()));
@@ -188,7 +188,7 @@ pub(crate) fn check_edit_with_config(
         .iter()
         .filter(|it| it.lookup() == what)
         .collect_tuple()
-        .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
+        .unwrap_or_else(|| panic!("can't find {what:?} completion in {completions:#?}"));
     let mut actual = db.file_text(position.file_id).to_string();
 
     let mut combined_edit = completion.text_edit().to_owned();
index 8e26d889f9b63c8ce28ffe210da9a433aa6c126a..043f552bd8a4c90aae46b08b53017aa3dcb6340c 100644 (file)
@@ -4,7 +4,7 @@
 use crate::tests::{check_edit, completion_list, BASE_ITEMS_FIXTURE};
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index 409413c1dcdb1ec8c35d3cc74826439b700978b2..3ef2a7c942bce4fd3e57bc0e374039943c2743c3 100644 (file)
@@ -7,7 +7,7 @@
 use crate::tests::{completion_list, BASE_ITEMS_FIXTURE};
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index 2b10294cc5b962b268c9df0b1da3fc312768e4b7..b62b988885d08fd9274e53ca28501f941d9218a5 100644 (file)
@@ -4,7 +4,7 @@
 use crate::tests::{check_edit, completion_list, BASE_ITEMS_FIXTURE};
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index db8bef66405efb3e55e564c55385edfe9dc7b823..ad9254e7f2ecfd6ff45f00f989d905cc79b9c061 100644 (file)
@@ -9,7 +9,7 @@ fn check_empty(ra_fixture: &str, expect: Expect) {
 }
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}\n{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}\n{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index a8676e2f247870cf90c8c245f2717f2f6abdc478..2656a4d545e662f8bbc93e9e4a4f1338936106cd 100644 (file)
@@ -4,7 +4,7 @@
 use crate::tests::{completion_list, BASE_ITEMS_FIXTURE};
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}\n{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}\n{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index f0b7726c51d9bb42d5620d813f18ac4932e05403..c3f4fb4d1817fc9f297687f39adafc2b341a7077 100644 (file)
@@ -4,7 +4,7 @@
 use crate::tests::{completion_list, BASE_ITEMS_FIXTURE};
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let actual = completion_list(&format!("{}\n{}", BASE_ITEMS_FIXTURE, ra_fixture));
+    let actual = completion_list(&format!("{BASE_ITEMS_FIXTURE}\n{ra_fixture}"));
     expect.assert_eq(&actual)
 }
 
index da23763dc2924712dc56691dfb3b4e2718ab849f..8c6c1c44aa7063aefcd74c81f1e674098af9a92f 100644 (file)
@@ -88,7 +88,7 @@ fn from_str(s: &str) -> Result<Self, Self::Err> {
             "RefactorExtract" => Ok(AssistKind::RefactorExtract),
             "RefactorInline" => Ok(AssistKind::RefactorInline),
             "RefactorRewrite" => Ok(AssistKind::RefactorRewrite),
-            unknown => Err(format!("Unknown AssistKind: '{}'", unknown)),
+            unknown => Err(format!("Unknown AssistKind: '{unknown}'")),
         }
     }
 }
index 40a6a3e8970fb770428c092b901ad23bc1bf7536..994d48385a0f77366611ab12d44bc22e612875c5 100644 (file)
@@ -367,7 +367,7 @@ fn import_for_item(
     let expected_import_end = if item_as_assoc(db, original_item).is_some() {
         unresolved_qualifier.to_string()
     } else {
-        format!("{}::{}", unresolved_qualifier, item_name(db, original_item)?)
+        format!("{unresolved_qualifier}::{}", item_name(db, original_item)?)
     };
     if !import_path_string.contains(unresolved_first_segment)
         || !import_path_string.ends_with(&expected_import_end)
index 59673af3204e6da5632324f8b26a43a5598dbdfa..b92e367f7e12abfc9834ee86009c122c0fdec8cf 100644 (file)
@@ -1014,7 +1014,7 @@ fn check_with_config(
         .and_then(|it| ImportScope::find_insert_use_container(&it, sema))
         .or_else(|| ImportScope::from(syntax))
         .unwrap();
-    let path = ast::SourceFile::parse(&format!("use {};", path))
+    let path = ast::SourceFile::parse(&format!("use {path};"))
         .tree()
         .syntax()
         .descendants()
index 49b81265ea5be22649f65103a517d583390f27a2..cd4a7e1554cd7bff2dd0c7afdfc2d6f445f1452b 100644 (file)
@@ -197,7 +197,7 @@ fn rename_mod(
 
         // Module exists in a named file
         if !is_mod_rs {
-            let path = format!("{}.rs", new_name);
+            let path = format!("{new_name}.rs");
             let dst = AnchoredPathBuf { anchor, path };
             source_change.push_file_system_edit(FileSystemEdit::MoveFile { src: anchor, dst })
         }
@@ -207,9 +207,7 @@ fn rename_mod(
         //  - Module has submodules defined in separate files
         let dir_paths = match (is_mod_rs, has_detached_child, module.name(sema.db)) {
             // Go up one level since the anchor is inside the dir we're trying to rename
-            (true, _, Some(mod_name)) => {
-                Some((format!("../{}", mod_name), format!("../{}", new_name)))
-            }
+            (true, _, Some(mod_name)) => Some((format!("../{mod_name}"), format!("../{new_name}"))),
             // The anchor is on the same level as target dir
             (false, true, Some(mod_name)) => Some((mod_name.to_string(), new_name.to_string())),
             _ => None,
@@ -356,7 +354,7 @@ fn source_edit_from_name(edit: &mut TextEditBuilder, name: &ast::Name, new_name:
 
             // FIXME: instead of splitting the shorthand, recursively trigger a rename of the
             // other name https://github.com/rust-lang/rust-analyzer/issues/6547
-            edit.insert(ident_pat.syntax().text_range().start(), format!("{}: ", new_name));
+            edit.insert(ident_pat.syntax().text_range().start(), format!("{new_name}: "));
             return true;
         }
     }
@@ -414,7 +412,7 @@ fn source_edit_from_name_ref(
                 // Foo { field } -> Foo { new_name: field }
                 //       ^ insert `new_name: `
                 let offset = name_ref.syntax().text_range().start();
-                edit.insert(offset, format!("{}: ", new_name));
+                edit.insert(offset, format!("{new_name}: "));
                 return true;
             }
             (None, Some(_)) if matches!(def, Definition::Local(_)) => {
@@ -422,7 +420,7 @@ fn source_edit_from_name_ref(
                 // Foo { field } -> Foo { field: new_name }
                 //            ^ insert `: new_name`
                 let offset = name_ref.syntax().text_range().end();
-                edit.insert(offset, format!(": {}", new_name));
+                edit.insert(offset, format!(": {new_name}"));
                 return true;
             }
             _ => (),
index bfb00312771051f6c2dffd871017e3f65369333c..c054cc1597968d7bf9c171efe3b4ce688bf041f5 100644 (file)
@@ -206,7 +206,7 @@ pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol> {
 }
 
 pub fn crate_symbols(db: &RootDatabase, krate: Crate, query: Query) -> Vec<FileSymbol> {
-    let _p = profile::span("crate_symbols").detail(|| format!("{:?}", query));
+    let _p = profile::span("crate_symbols").detail(|| format!("{query:?}"));
 
     let modules = krate.modules(db);
     let indices: Vec<_> = modules
index 313346ee131539b9210714159d0164b5b464e8c2..f5f03d70b0134373d083946c81fa1cdf467ae569 100644 (file)
@@ -205,7 +205,7 @@ mod tests {
     fn check(input: &str, expect: &Expect) {
         let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_string(), vec![]));
         let outcome_repr = if !exprs.is_empty() {
-            format!("{}; {}", output, with_placeholders(exprs).join(", "))
+            format!("{output}; {}", with_placeholders(exprs).join(", "))
         } else {
             output
         };
index 5042f6d815a1ea35357f314e6442276a4318ec58..c7d5f3613d4bcfabef19ec74533575d35aad8fdf 100644 (file)
@@ -241,9 +241,9 @@ fn generate_descriptor_clippy(buf: &mut String, path: &Path) {
 
     buf.push_str(r#"pub const CLIPPY_LINT_GROUPS: &[LintGroup] = &["#);
     for (id, children) in clippy_groups {
-        let children = children.iter().map(|id| format!("clippy::{}", id)).collect::<Vec<_>>();
+        let children = children.iter().map(|id| format!("clippy::{id}")).collect::<Vec<_>>();
         if !children.is_empty() {
-            let lint_ident = format!("clippy::{}", id);
+            let lint_ident = format!("clippy::{id}");
             let description = format!("lint group for: {}", children.iter().join(", "));
             push_lint_group(buf, &lint_ident, &description, &children);
         }
@@ -273,7 +273,7 @@ fn push_lint_group(buf: &mut String, label: &str, description: &str, children: &
 
     push_lint_completion(buf, label, description);
 
-    let children = format!("&[{}]", children.iter().map(|it| format!("\"{}\"", it)).join(", "));
+    let children = format!("&[{}]", children.iter().map(|it| format!("\"{it}\"")).join(", "));
     format_to!(
         buf,
         r###"
index 5f8b3e543b9440edbcb26ea73e321ecb815d2a3e..c5db8c3741b814c3ca252c84440e7b89e80289a8 100644 (file)
@@ -13,7 +13,7 @@ pub(crate) fn mismatched_arg_count(
     d: &hir::MismatchedArgCount,
 ) -> Diagnostic {
     let s = if d.expected == 1 { "" } else { "s" };
-    let message = format!("expected {} argument{}, found {}", d.expected, s, d.found);
+    let message = format!("expected {} argument{s}, found {}", d.expected, d.found);
     Diagnostic::new("mismatched-arg-count", message, invalid_args_range(ctx, d))
 }
 
index d8f2a9de9818fca43f638f6e8e8031abc9887d78..8673524c109da5cabe61bbdee1d52d08a06bda65 100644 (file)
@@ -78,13 +78,13 @@ fn missing_record_expr_field_fixes(
 
     let mut new_field = new_field.to_string();
     if usage_file_id != def_file_id {
-        new_field = format!("pub(crate) {}", new_field);
+        new_field = format!("pub(crate) {new_field}");
     }
-    new_field = format!("\n{}{}", indent, new_field);
+    new_field = format!("\n{indent}{new_field}");
 
     let needs_comma = !last_field_syntax.to_string().ends_with(',');
     if needs_comma {
-        new_field = format!(",{}", new_field);
+        new_field = format!(",{new_field}");
     }
 
     let source_change = SourceChange::from_text_edit(
index 62c69f90baa4f9f55b1b15bcb827f67883c3f1cd..2adae165e4d253dd6b0fdc2cf7d6472e5ffe0b83 100644 (file)
@@ -106,11 +106,11 @@ 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().start(), format!("{variant_name}("));
     builder.insert(expr.syntax().text_range().end(), ")".to_string());
     let source_change =
         SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), builder.finish());
-    let name = format!("Wrap in {}", variant_name);
+    let name = format!("Wrap in {variant_name}");
     acc.push(fix("wrap_in_constructor", &name, source_change, expr_range));
     Some(())
 }
index c626932f196ba7dbd60101fa3c70a55d4b68b819..be70f0ac4f797b8d8751e4c9d916e79a2d2b3003 100644 (file)
@@ -64,7 +64,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, file_id: FileId) -> Option<Vec<Assist>> {
         // `submod/bla.rs` -> `submod.rs`
         let parent_mod = (|| {
             let (name, _) = parent.name_and_extension()?;
-            parent.parent()?.join(&format!("{}.rs", name))
+            parent.parent()?.join(&format!("{name}.rs"))
         })();
         paths.extend(parent_mod);
         paths
@@ -99,8 +99,8 @@ fn is_outline_mod(item: &ast::Item) -> bool {
         matches!(item, ast::Item::Module(m) if m.item_list().is_none())
     }
 
-    let mod_decl = format!("mod {};", new_mod_name);
-    let pub_mod_decl = format!("pub mod {};", new_mod_name);
+    let mod_decl = format!("mod {new_mod_name};");
+    let pub_mod_decl = format!("pub mod {new_mod_name};");
 
     let ast: ast::SourceFile = db.parse(parent_file_id).tree();
 
@@ -125,8 +125,8 @@ fn is_outline_mod(item: &ast::Item) -> bool {
         Some(last) => {
             cov_mark::hit!(unlinked_file_append_to_existing_mods);
             let offset = last.syntax().text_range().end();
-            mod_decl_builder.insert(offset, format!("\n{}", mod_decl));
-            pub_mod_decl_builder.insert(offset, format!("\n{}", pub_mod_decl));
+            mod_decl_builder.insert(offset, format!("\n{mod_decl}"));
+            pub_mod_decl_builder.insert(offset, format!("\n{pub_mod_decl}"));
         }
         None => {
             // Prepend before the first item in the file.
@@ -134,15 +134,15 @@ fn is_outline_mod(item: &ast::Item) -> bool {
                 Some(item) => {
                     cov_mark::hit!(unlinked_file_prepend_before_first_item);
                     let offset = item.syntax().text_range().start();
-                    mod_decl_builder.insert(offset, format!("{}\n\n", mod_decl));
-                    pub_mod_decl_builder.insert(offset, format!("{}\n\n", pub_mod_decl));
+                    mod_decl_builder.insert(offset, format!("{mod_decl}\n\n"));
+                    pub_mod_decl_builder.insert(offset, format!("{pub_mod_decl}\n\n"));
                 }
                 None => {
                     // No items in the file, so just append at the end.
                     cov_mark::hit!(unlinked_file_empty_file);
                     let offset = ast.syntax().text_range().end();
-                    mod_decl_builder.insert(offset, format!("{}\n", mod_decl));
-                    pub_mod_decl_builder.insert(offset, format!("{}\n", pub_mod_decl));
+                    mod_decl_builder.insert(offset, format!("{mod_decl}\n"));
+                    pub_mod_decl_builder.insert(offset, format!("{pub_mod_decl}\n"));
                 }
             }
         }
@@ -152,13 +152,13 @@ fn is_outline_mod(item: &ast::Item) -> bool {
     Some(vec![
         fix(
             "add_mod_declaration",
-            &format!("Insert `{}`", mod_decl),
+            &format!("Insert `{mod_decl}`"),
             SourceChange::from_text_edit(parent_file_id, mod_decl_builder.finish()),
             trigger_range,
         ),
         fix(
             "add_pub_mod_declaration",
-            &format!("Insert `{}`", pub_mod_decl),
+            &format!("Insert `{pub_mod_decl}`"),
             SourceChange::from_text_edit(parent_file_id, pub_mod_decl_builder.finish()),
             trigger_range,
         ),
index 87531f4acfb753b0feb68c58caf76b3518bc6c5d..1a5efff2c0c60ecbfd00cb68d58b179d8f71e1b2 100644 (file)
@@ -13,7 +13,7 @@ pub(crate) fn unresolved_macro_call(
     let bang = if d.is_bang { "!" } else { "" };
     Diagnostic::new(
         "unresolved-macro-call",
-        format!("unresolved macro `{}{}`", d.path, bang),
+        format!("unresolved macro `{}{bang}`", d.path),
         display_range,
     )
     .experimental()
index b8f2a9e94a40eed3565e4b8a8fe1430fefd3e254..91395f1d841adfc9021540283aea6e83b12d1fb5 100644 (file)
@@ -16,7 +16,7 @@ pub(crate) fn unresolved_module(
         "unresolved-module",
         match &*d.candidates {
             [] => "unresolved module".to_string(),
-            [candidate] => format!("unresolved module, can't find module file: {}", candidate),
+            [candidate] => format!("unresolved module, can't find module file: {candidate}"),
             [candidates @ .., last] => {
                 format!(
                     "unresolved module, can't find module file: {}, or {}",
index 23818d883f73181d7c684523d21637cda93b1085..b2ed19104e27854fa1523ad1f0c72ce949621ce2 100644 (file)
@@ -26,7 +26,7 @@ pub(crate) fn unresolved_proc_macro(
     };
 
     let message = match &d.macro_name {
-        Some(name) => format!("proc macro `{}` not expanded", name),
+        Some(name) => format!("proc macro `{name}` not expanded"),
         None => "proc macro not expanded".to_string(),
     };
     let severity = if config_enabled { Severity::Error } else { Severity::WeakWarning };
index d81e36a1f86321428d55f3f99fbb229e7dc0d0a2..b244666d1c0e875cd88a80490f0290826182af78 100644 (file)
@@ -218,7 +218,7 @@ pub fn diagnostics(
     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
     res.extend(
         parse.errors().iter().take(128).map(|err| {
-            Diagnostic::new("syntax-error", format!("Syntax Error: {}", err), err.range())
+            Diagnostic::new("syntax-error", format!("Syntax Error: {err}"), err.range())
         }),
     );
 
index 82967883176f9c6be0286912bcd8708089d9aa0b..afa641c733ebb20147f3d0b535f2dced5fd2a7e9 100644 (file)
@@ -75,7 +75,7 @@ pub(crate) fn check_no_fix(ra_fixture: &str) {
     )
     .pop()
     .unwrap();
-    assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
+    assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {diagnostic:?}");
 }
 
 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
index ec6558a46efb4d67fa316df736d784aa610fa55f..71d27e6d217df0eaf47f820a8c40d395a5499d9a 100644 (file)
@@ -39,7 +39,7 @@ fn collect_file(acc: &mut Vec<Diagnostic>, path: PathBuf) -> io::Result<()> {
             for block in comment_blocks {
                 let id = block.id;
                 if let Err(msg) = is_valid_diagnostic_name(&id) {
-                    panic!("invalid diagnostic name: {:?}:\n  {}", id, msg)
+                    panic!("invalid diagnostic name: {id:?}:\n  {msg}")
                 }
                 let doc = block.contents.join("\n");
                 let location = sourcegen::Location { file: path.clone(), line: block.line };
index f6220b928a4c6d4413159c1de6c769787929495f..d78d009681a6039a49033e3d5b46840f658ba54a 100644 (file)
@@ -352,7 +352,7 @@ fn from(name: &SmolStr) -> Result<NodeKind, SsrError> {
 impl Placeholder {
     fn new(name: SmolStr, constraints: Vec<Constraint>) -> Self {
         Self {
-            stand_in_name: format!("__placeholder_{}", name),
+            stand_in_name: format!("__placeholder_{name}"),
             constraints,
             ident: Var(name.to_string()),
         }
index 1ecb7aa9aa701092821267741bd04bc679899bcb..61698fca80fee7874ecc070d26a7e0093f6947f4 100644 (file)
@@ -121,7 +121,7 @@ fn print_match_debug_info(match_finder: &MatchFinder<'_>, file_id: FileId, snipp
         snippet
     );
     for (index, d) in debug_info.iter().enumerate() {
-        println!("Node #{}\n{:#?}\n", index, d);
+        println!("Node #{index}\n{d:#?}\n");
     }
 }
 
@@ -144,7 +144,7 @@ fn assert_no_match(pattern: &str, code: &str) {
     let matches = match_finder.matches().flattened().matches;
     if !matches.is_empty() {
         print_match_debug_info(&match_finder, position.file_id, &matches[0].matched_text());
-        panic!("Got {} matches when we expected none: {:#?}", matches.len(), matches);
+        panic!("Got {} matches when we expected none: {matches:#?}", matches.len());
     }
 }
 
index d96827326cfd8a322d5234b6f6765a90271d57c5..8569701346d45c54d40e99d6d8fcf2208d859f6e 100644 (file)
@@ -453,7 +453,7 @@ fn get_doc_base_url(db: &RootDatabase, def: Definition) -> Option<Url> {
             })?
         }
     };
-    Url::parse(&base).ok()?.join(&format!("{}/", display_name)).ok()
+    Url::parse(&base).ok()?.join(&format!("{display_name}/")).ok()
 }
 
 /// Get the filename and extension generated for a symbol by rustdoc.
@@ -488,7 +488,7 @@ fn filename_and_frag_for_def(
                 Some(kw) => {
                     format!("keyword.{}.html", kw.trim_matches('"'))
                 }
-                None => format!("{}/index.html", name),
+                None => format!("{name}/index.html"),
             },
             None => String::from("index.html"),
         },
index 1df9aaae281ee6da083e991c9cecbcc976f332d8..13088bdc3b30f71c88875d536d4055b3e29de297 100644 (file)
@@ -63,8 +63,8 @@ mod tests {
 
     fn check(link: &str, expected: Expect) {
         let (l, a) = parse_intra_doc_link(link);
-        let a = a.map_or_else(String::new, |a| format!(" ({:?})", a));
-        expected.assert_eq(&format!("{}{}", l, a));
+        let a = a.map_or_else(String::new, |a| format!(" ({a:?})"));
+        expected.assert_eq(&format!("{l}{a}"));
     }
 
     #[test]
index c6bfb6b9d09756635cbd41e05cf1c6c2154117c2..104181a33e68dea356f6e1248b12ed621c8f4200 100644 (file)
@@ -40,7 +40,7 @@ fn check_doc_links(ra_fixture: &str) {
         .into_iter()
         .map(|(_, link, ns)| {
             let def = resolve_doc_path_for_def(sema.db, cursor_def, &link, ns)
-                .unwrap_or_else(|| panic!("Failed to resolve {}", link));
+                .unwrap_or_else(|| panic!("Failed to resolve {link}"));
             let nav_target = def.try_to_nav(sema.db).unwrap();
             let range =
                 FileRange { file_id: nav_target.file_id, range: nav_target.focus_or_full_range() };
index 43f7a529bc2979168dcef1d96a2daf67aafe1b28..73fd518a9ef08867ef5196cf446f291cd29b9e27 100644 (file)
@@ -187,7 +187,7 @@ fn check_unresolved(ra_fixture: &str) {
         let (analysis, position) = fixture::position(ra_fixture);
         let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info;
 
-        assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {:?}", navs)
+        assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {navs:?}")
     }
 
     #[test]
index 9cbfed4763b092c840c554dbe1c23bdacb3366c0..bfb19a40bdecdb1d9767c596d3f2dbe5bf7f14e7 100644 (file)
@@ -163,7 +163,7 @@ pub(crate) fn hover(
                 .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
                 .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
                     acc.actions.extend(actions);
-                    acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
+                    acc.markup = Markup::from(format!("{}\n---\n{markup}", acc.markup));
                     acc
                 })
         })
index ef434e51c106f7d247136fbcb6eb348ab2646c7a..4015a411c5888ad5f768de22e796e228f74b4dbc 100644 (file)
@@ -417,8 +417,8 @@ pub(super) fn definition(
         Definition::Variant(it) => label_value_and_docs(db, it, |&it| {
             if !it.parent_enum(db).is_data_carrying(db) {
                 match it.eval(db) {
-                    Ok(x) => Some(format!("{}", x)),
-                    Err(_) => it.value(db).map(|x| format!("{:?}", x)),
+                    Ok(x) => Some(format!("{x}")),
+                    Err(_) => it.value(db).map(|x| format!("{x:?}")),
                 }
             } else {
                 None
@@ -427,7 +427,7 @@ pub(super) fn definition(
         Definition::Const(it) => label_value_and_docs(db, it, |it| {
             let body = it.eval(db);
             match body {
-                Ok(x) => Some(format!("{}", x)),
+                Ok(x) => Some(format!("{x}")),
                 Err(_) => {
                     let source = it.source(db)?;
                     let mut body = source.value.body()?.syntax().clone();
@@ -483,7 +483,7 @@ pub(super) fn definition(
 
 fn render_builtin_attr(db: &RootDatabase, attr: hir::BuiltinAttr) -> Option<Markup> {
     let name = attr.name(db);
-    let desc = format!("#[{}]", name);
+    let desc = format!("#[{name}]");
 
     let AttributeTemplate { word, list, name_value_str } = match attr.template(db) {
         Some(template) => template,
@@ -522,7 +522,7 @@ fn label_and_layout_info_and_docs<D, E, V>(
     V: Display,
 {
     let label = if let Some(value) = value_extractor(&def) {
-        format!("{} // {}", def.display(db), value)
+        format!("{} // {value}", def.display(db))
     } else {
         def.display(db).to_string()
     };
@@ -541,7 +541,7 @@ fn label_value_and_docs<D, E, V>(
     V: Display,
 {
     let label = if let Some(value) = value_extractor(&def) {
-        format!("{} = {}", def.display(db), value)
+        format!("{} = {value}", def.display(db))
     } else {
         def.display(db).to_string()
     };
@@ -605,9 +605,9 @@ fn local(db: &RootDatabase, it: hir::Local) -> Option<Markup> {
             } else {
                 ""
             };
-            format!("{}{}{}: {}", let_kw, is_mut, name, ty)
+            format!("{let_kw}{is_mut}{name}: {ty}")
         }
-        Either::Right(_) => format!("{}self: {}", is_mut, ty),
+        Either::Right(_) => format!("{is_mut}self: {ty}"),
     };
     markup(None, desc, None)
 }
index 3580c457026321d21c40e164809d095e6da5e036..c7f241f2fea6446a3872a86965b4975c347785e4 100644 (file)
@@ -37,7 +37,7 @@ fn check(ra_fixture: &str, expect: Expect) {
     let content = analysis.db.file_text(position.file_id);
     let hovered_element = &content[hover.range];
 
-    let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
+    let actual = format!("*{hovered_element}*\n{}\n", hover.info.markup);
     expect.assert_eq(&actual)
 }
 
@@ -58,7 +58,7 @@ fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
     let content = analysis.db.file_text(position.file_id);
     let hovered_element = &content[hover.range];
 
-    let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
+    let actual = format!("*{hovered_element}*\n{}\n", hover.info.markup);
     expect.assert_eq(&actual)
 }
 
@@ -79,7 +79,7 @@ fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
     let content = analysis.db.file_text(position.file_id);
     let hovered_element = &content[hover.range];
 
-    let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
+    let actual = format!("*{hovered_element}*\n{}\n", hover.info.markup);
     expect.assert_eq(&actual)
 }
 
index 6b3c15fba7fe493c64d8e508f0ae675e4ee66261..9fabc6bc4f95784a3e32bfdc1a5011b6b3bfc9d3 100644 (file)
@@ -468,7 +468,7 @@ pub(super) fn check_with_config(config: InlayHintsConfig, ra_fixture: &str) {
             .collect::<Vec<_>>();
         expected.sort_by_key(|(range, _)| range.start());
 
-        assert_eq!(expected, actual, "\nExpected:\n{:#?}\n\nActual:\n{:#?}", expected, actual);
+        assert_eq!(expected, actual, "\nExpected:\n{expected:#?}\n\nActual:\n{actual:#?}");
     }
 
     #[track_caller]
index 4e63740098b729a4fdae4e27225236783ab39fb1..7127c433c63d54f7c7bae1d693d1013ddb37bb57 100644 (file)
@@ -160,7 +160,7 @@ fn is_named_constructor(
     let ctor_name = match qual_seg.kind()? {
         ast::PathSegmentKind::Name(name_ref) => {
             match qual_seg.generic_arg_list().map(|it| it.generic_args()) {
-                Some(generics) => format!("{}<{}>", name_ref, generics.format(", ")),
+                Some(generics) => format!("{name_ref}<{}>", generics.format(", ")),
                 None => name_ref.to_string(),
             }
         }
@@ -473,7 +473,7 @@ fn main() {
             .unwrap();
         let actual =
             inlay_hints.into_iter().map(|it| (it.range, it.label.to_string())).collect::<Vec<_>>();
-        assert_eq!(expected, actual, "\nExpected:\n{:#?}\n\nActual:\n{:#?}", expected, actual);
+        assert_eq!(expected, actual, "\nExpected:\n{expected:#?}\n\nActual:\n{actual:#?}");
     }
 
     #[test]
index 60c193c40aba27b81111fcab406a69584de34f6d..de9fef61a78eaca0381307c756777c014e811bdb 100644 (file)
@@ -33,6 +33,6 @@ pub fn as_str(&self) -> &str {
         self.text.as_str()
     }
     pub fn fenced_block(contents: &impl fmt::Display) -> Markup {
-        format!("```rust\n{}\n```", contents).into()
+        format!("```rust\n{contents}\n```").into()
     }
 }
index fcbf6d8e58c4b07fd66cda4e0b3f8f49f696bfda..af5e96d2381acaff2b4d0c83f1153370ac0a9034 100644 (file)
@@ -273,7 +273,7 @@ mod tests {
     fn no_moniker(ra_fixture: &str) {
         let (analysis, position) = fixture::position(ra_fixture);
         if let Some(x) = analysis.moniker(position).unwrap() {
-            assert_eq!(x.info.len(), 0, "Moniker founded but no moniker expected: {:?}", x);
+            assert_eq!(x.info.len(), 0, "Moniker founded but no moniker expected: {x:?}");
         }
     }
 
index 9f049e298ad119573cccfdc09fab0ea5c3524507..3aa799d43a8a3eedd835471b6abff526d733adb7 100644 (file)
@@ -117,10 +117,10 @@ pub(crate) fn debug_render(&self) -> String {
             self.full_range
         );
         if let Some(focus_range) = self.focus_range {
-            buf.push_str(&format!(" {:?}", focus_range))
+            buf.push_str(&format!(" {focus_range:?}"))
         }
         if let Some(container_name) = &self.container_name {
-            buf.push_str(&format!(" {}", container_name))
+            buf.push_str(&format!(" {container_name}"))
         }
         buf
     }
index b4df0437050f4d4de0be9b6886c1b0b4d66e00b4..595a3b8ac4f19691f3f4a9fd6b0a8ccdbf0e6bdd 100644 (file)
@@ -345,7 +345,7 @@ fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
         let (analysis, position) = fixture::position(ra_fixture_before);
         let rename_result = analysis
             .rename(position, new_name)
-            .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
+            .unwrap_or_else(|err| panic!("Rename to '{new_name}' was cancelled: {err}"));
         match rename_result {
             Ok(source_change) => {
                 let mut text_edit_builder = TextEdit::builder();
@@ -371,7 +371,7 @@ fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
                         .collect::<String>();
                     assert_eq!(error_message.trim(), err.to_string());
                 } else {
-                    panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
+                    panic!("Rename to '{new_name}' failed unexpectedly: {err}")
                 }
             }
         };
@@ -397,11 +397,11 @@ fn check_prepare(ra_fixture: &str, expect: Expect) {
         let (analysis, position) = fixture::position(ra_fixture);
         let result = analysis
             .prepare_rename(position)
-            .unwrap_or_else(|err| panic!("PrepareRename was cancelled: {}", err));
+            .unwrap_or_else(|err| panic!("PrepareRename was cancelled: {err}"));
         match result {
             Ok(RangeInfo { range, info: () }) => {
                 let source = analysis.file_text(position.file_id).unwrap();
-                expect.assert_eq(&format!("{:?}: {}", range, &source[range]))
+                expect.assert_eq(&format!("{range:?}: {}", &source[range]))
             }
             Err(RenameError(err)) => expect.assert_eq(&err),
         };
index 0181c6b8e456a1881e723ce139ef105e4f4be92a..5b35262aabe11b9b0c350f074e6ccd1b7607537f 100644 (file)
@@ -66,12 +66,12 @@ impl Runnable {
     // test package::module::testname
     pub fn label(&self, target: Option<String>) -> String {
         match &self.kind {
-            RunnableKind::Test { test_id, .. } => format!("test {}", test_id),
-            RunnableKind::TestMod { path } => format!("test-mod {}", path),
-            RunnableKind::Bench { test_id } => format!("bench {}", test_id),
-            RunnableKind::DocTest { test_id, .. } => format!("doctest {}", test_id),
+            RunnableKind::Test { test_id, .. } => format!("test {test_id}"),
+            RunnableKind::TestMod { path } => format!("test-mod {path}"),
+            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_string(), |t| format!("run {t}"))
             }
         }
     }
@@ -377,7 +377,7 @@ pub(crate) fn runnable_impl(
     } else {
         String::new()
     };
-    let mut test_id = format!("{}{}", adt_name, params);
+    let mut test_id = format!("{adt_name}{params}");
     test_id.retain(|c| c != ' ');
     let test_id = TestId::Path(test_id);
 
index a8ffc387080d1bba849d6e0f18b48384a66dd0f3..b6a58f5ef59bc988ff2d66fc0fe6e2a5f9019067 100644 (file)
@@ -233,13 +233,13 @@ fn check_all_ranges(ra_fixture: &str) {
             for (range, _) in f.tokens {
                 let x = FileRange { file_id: f.file_id, range };
                 if !range_set.contains(&x) {
-                    panic!("additional range {:?}", x);
+                    panic!("additional range {x:?}");
                 }
                 range_set.remove(&x);
             }
         }
         if !range_set.is_empty() {
-            panic!("unfound ranges {:?}", range_set);
+            panic!("unfound ranges {range_set:?}");
         }
     }
 
@@ -254,13 +254,13 @@ fn check_definitions(ra_fixture: &str) {
                     continue;
                 }
                 if !range_set.contains(&x) {
-                    panic!("additional definition {:?}", x);
+                    panic!("additional definition {x:?}");
                 }
                 range_set.remove(&x);
             }
         }
         if !range_set.is_empty() {
-            panic!("unfound definitions {:?}", range_set);
+            panic!("unfound definitions {range_set:?}");
         }
     }
 
index 20810c25b3e81f976ee1b99190d788389165ad80..7ce782f93be14dda6d526c2bf71031536d220e29 100644 (file)
@@ -52,8 +52,8 @@ pub(crate) fn status(db: &RootDatabase, file_id: Option<FileId>) -> String {
         let crate_graph = db.crate_graph();
         for krate in crates {
             let display_crate = |krate: CrateId| match &crate_graph[krate].display_name {
-                Some(it) => format!("{}({:?})", it, krate),
-                None => format!("{:?}", krate),
+                Some(it) => format!("{it}({krate:?})"),
+                None => format!("{krate:?}"),
             };
             format_to!(buf, "Crate: {}\n", display_crate(krate));
             let deps = crate_graph[krate]
index e91fd7f12571649cee96e51e652165cad39bc993..2c7823069b3f8465875d14041238e177db1b6bea 100644 (file)
@@ -52,7 +52,7 @@ fn rainbowify(seed: u64) -> String {
         let class = r.highlight.to_string().replace('.', " ");
         let color = match (rainbow, r.binding_hash) {
             (true, Some(hash)) => {
-                format!(" data-binding-hash=\"{}\" style=\"color: {};\"", hash, rainbowify(hash))
+                format!(" data-binding-hash=\"{hash}\" style=\"color: {};\"", rainbowify(hash))
             }
             _ => "".into(),
         };
index 4256fea0f81e45679ff6567fda769c93c92578eb..bb6827e8a44e4678d78533e2e60ce3e78e8ef580 100644 (file)
@@ -32,7 +32,7 @@ pub(crate) fn syntax_tree(
             }
         };
 
-        format!("{:#?}", node)
+        format!("{node:#?}")
     } else {
         format!("{:#?}", parse.tree().syntax())
     }
index 9118f3c699c0c334e9dcb0c8b42368099942cefd..eba5a485636e27ebacba6f93ff502caf3dd1a113 100644 (file)
@@ -397,7 +397,7 @@ fn do_type_char(char_typed: char, before: &str) -> Option<String> {
 
     fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
         let actual = do_type_char(char_typed, ra_fixture_before)
-            .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
+            .unwrap_or_else(|| panic!("typing `{char_typed}` did nothing"));
 
         assert_eq_text!(ra_fixture_after, &actual);
     }
index 48c1713270b6c5c46c42deb7553ca98ac66384d3..298482f2ab5c4e4793df4a1d94016275a81bf4cd 100644 (file)
@@ -108,7 +108,7 @@ fn on_enter_in_comment(
     }
 
     let indent = node_indent(file, comment.syntax())?;
-    let inserted = format!("\n{}{} $0", indent, prefix);
+    let inserted = format!("\n{indent}{prefix} $0");
     let delete = if remove_trailing_whitespace {
         let trimmed_len = comment.text().trim_end().len() as u32;
         let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
@@ -129,7 +129,7 @@ fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<Te
 
     let indent = IndentLevel::from_node(block.syntax());
     let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
-    edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
+    edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{indent}"))).ok()?;
     Some(edit)
 }
 
@@ -140,11 +140,8 @@ fn on_enter_in_use_tree_list(list: ast::UseTreeList, position: FilePosition) ->
 
     let indent = IndentLevel::from_node(list.syntax());
     let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
-    edit.union(TextEdit::insert(
-        list.r_curly_token()?.text_range().start(),
-        format!("\n{}", indent),
-    ))
-    .ok()?;
+    edit.union(TextEdit::insert(list.r_curly_token()?.text_range().start(), format!("\n{indent}")))
+        .ok()?;
     Some(edit)
 }
 
index d6a706a7cd73a82efc2dad0b97adc7ae4e9623ce..6b2534aa4619df42f3125b622750942094191204 100644 (file)
@@ -59,7 +59,7 @@ pub fn check(&self, other: usize) -> Result<(), ()> {
                     .compare_exchange_weak(old_max, other, Ordering::Relaxed, Ordering::Relaxed)
                     .is_ok()
                 {
-                    eprintln!("new max: {}", other);
+                    eprintln!("new max: {other}");
                 }
             }
 
index 9c92bae6a1962d593219c3d869bb0c454967ec78..1915c0b6611b7273829ce281d9ce2c892428aad0 100644 (file)
@@ -101,7 +101,7 @@ fn invocation_fixtures(rules: &FxHashMap<String, DeclarativeMacro>) -> Vec<(Stri
                     }
                     try_cnt += 1;
                     if try_cnt > 100 {
-                        panic!("invocaton fixture {} cannot be generated.\n", name);
+                        panic!("invocaton fixture {name} cannot be generated.\n");
                     }
                 }
             }
@@ -139,7 +139,7 @@ fn collect_from_op(op: &Op, parent: &mut tt::Subtree, seed: &mut usize) {
                 }
 
                 None => (),
-                Some(kind) => panic!("Unhandled kind {:?}", kind),
+                Some(kind) => panic!("Unhandled kind {kind:?}"),
             },
             Op::Leaf(leaf) => parent.token_trees.push(leaf.clone().into()),
             Op::Repeat { tokens, kind, separator } => {
index cf53c16726bf7fe092c11fe7cf87748f39d2f9b8..4ca3ba74ae34989dff73eab603b894f3516628d6 100644 (file)
@@ -237,7 +237,7 @@ struct StackEntry {
             let char = match token.to_char(conv) {
                 Some(c) => c,
                 None => {
-                    panic!("Token from lexer must be single char: token = {:#?}", token);
+                    panic!("Token from lexer must be single char: token = {token:#?}");
                 }
             };
             tt::Leaf::from(tt::Punct { char, spacing, id: conv.id_alloc().alloc(range, synth_id) })
index 4e04d2bc1c77bcbd972d7d349cb7ed2fe6c32129..606c259e5182dd184e672b4d297f374261cdaa48 100644 (file)
@@ -19,7 +19,7 @@ fn check_punct_spacing(fixture: &str) {
             let spacing = match annotation.as_str() {
                 "Alone" => Spacing::Alone,
                 "Joint" => Spacing::Joint,
-                a => panic!("unknown annotation: {}", a),
+                a => panic!("unknown annotation: {a}"),
             };
             (token, spacing)
         })
@@ -39,7 +39,7 @@ fn check_punct_spacing(fixture: &str) {
         cursor = cursor.bump();
     }
 
-    assert!(annotations.is_empty(), "unchecked annotations: {:?}", annotations);
+    assert!(annotations.is_empty(), "unchecked annotations: {annotations:?}");
 }
 
 #[test]
index 783c3ca4a89f7dd8025e172292ba11c9100564b1..7013aa58b55dc295522d10d71604b9837b39a4a8 100644 (file)
@@ -60,7 +60,7 @@ pub(crate) fn to_parser_input(buffer: &TokenBuffer<'_>) -> parser::Input {
                     },
                     tt::Leaf::Punct(punct) => {
                         let kind = SyntaxKind::from_char(punct.char)
-                            .unwrap_or_else(|| panic!("{:#?} is not a valid punct", punct));
+                            .unwrap_or_else(|| panic!("{punct:#?} is not a valid punct"));
                         res.push(kind);
                         if punct.spacing == tt::Spacing::Joint {
                             res.was_joint();
index b621ebc37c3b2fd6e65be277cf8d01fef11602d3..30bd0b3b169ee925270fd5121f0d4cf9ce0785b6 100644 (file)
@@ -205,7 +205,7 @@ pub(crate) fn expect(&mut self, kind: SyntaxKind) -> bool {
         if self.eat(kind) {
             return true;
         }
-        self.error(format!("expected {:?}", kind));
+        self.error(format!("expected {kind:?}"));
         false
     }
 
index 735c0b3e4020485bc266d8dc4494c1e048ba2588..caf1a3e83cb934075bcd23006934423ae4fc9b0d 100644 (file)
@@ -37,8 +37,8 @@ fn lex(text: &str) -> String {
         let text = lexed.text(i);
         let error = lexed.error(i);
 
-        let error = error.map(|err| format!(" error: {}", err)).unwrap_or_default();
-        writeln!(res, "{:?} {:?}{}", kind, text, error).unwrap();
+        let error = error.map(|err| format!(" error: {err}")).unwrap_or_default();
+        writeln!(res, "{kind:?} {text:?}{error}").unwrap();
     }
     res
 }
@@ -47,7 +47,7 @@ fn lex(text: &str) -> String {
 fn parse_ok() {
     for case in TestCase::list("parser/ok") {
         let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text);
-        assert!(!errors, "errors in an OK file {}:\n{}", case.rs.display(), actual);
+        assert!(!errors, "errors in an OK file {}:\n{actual}", case.rs.display());
         expect_file![case.rast].assert_eq(&actual);
     }
 }
@@ -56,7 +56,7 @@ fn parse_ok() {
 fn parse_inline_ok() {
     for case in TestCase::list("parser/inline/ok") {
         let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text);
-        assert!(!errors, "errors in an OK file {}:\n{}", case.rs.display(), actual);
+        assert!(!errors, "errors in an OK file {}:\n{actual}", case.rs.display());
         expect_file![case.rast].assert_eq(&actual);
     }
 }
@@ -65,7 +65,7 @@ fn parse_inline_ok() {
 fn parse_err() {
     for case in TestCase::list("parser/err") {
         let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text);
-        assert!(errors, "no errors in an ERR file {}:\n{}", case.rs.display(), actual);
+        assert!(errors, "no errors in an ERR file {}:\n{actual}", case.rs.display());
         expect_file![case.rast].assert_eq(&actual)
     }
 }
@@ -74,7 +74,7 @@ fn parse_err() {
 fn parse_inline_err() {
     for case in TestCase::list("parser/inline/err") {
         let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text);
-        assert!(errors, "no errors in an ERR file {}:\n{}", case.rs.display(), actual);
+        assert!(errors, "no errors in an ERR file {}:\n{actual}", case.rs.display());
         expect_file![case.rast].assert_eq(&actual)
     }
 }
@@ -93,14 +93,14 @@ fn parse(entry: TopEntryPoint, text: &str) -> (String, bool) {
         crate::StrStep::Token { kind, text } => {
             assert!(depth > 0);
             len += text.len();
-            write!(buf, "{}", indent).unwrap();
-            write!(buf, "{:?} {:?}\n", kind, text).unwrap();
+            write!(buf, "{indent}").unwrap();
+            write!(buf, "{kind:?} {text:?}\n").unwrap();
         }
         crate::StrStep::Enter { kind } => {
             assert!(depth > 0 || len == 0);
             depth += 1;
-            write!(buf, "{}", indent).unwrap();
-            write!(buf, "{:?}\n", kind).unwrap();
+            write!(buf, "{indent}").unwrap();
+            write!(buf, "{kind:?}\n").unwrap();
             indent.push_str("  ");
         }
         crate::StrStep::Exit => {
@@ -111,7 +111,7 @@ fn parse(entry: TopEntryPoint, text: &str) -> (String, bool) {
         }
         crate::StrStep::Error { msg, pos } => {
             assert!(depth > 0);
-            errors.push(format!("error {}: {}\n", pos, msg))
+            errors.push(format!("error {pos}: {msg}\n"))
         }
     });
     assert_eq!(
@@ -124,7 +124,7 @@ fn parse(entry: TopEntryPoint, text: &str) -> (String, bool) {
 
     for (token, msg) in lexed.errors() {
         let pos = lexed.text_start(token);
-        errors.push(format!("error {}: {}\n", pos, msg));
+        errors.push(format!("error {pos}: {msg}\n"));
     }
 
     let has_errors = !errors.is_empty();
@@ -149,7 +149,7 @@ fn list(path: &'static str) -> Vec<TestCase> {
 
         let mut res = Vec::new();
         let read_dir = fs::read_dir(&dir)
-            .unwrap_or_else(|err| panic!("can't `read_dir` {}: {}", dir.display(), err));
+            .unwrap_or_else(|err| panic!("can't `read_dir` {}: {err}", dir.display()));
         for file in read_dir {
             let file = file.unwrap();
             let path = file.path();
index 7b2b703deb699407f1ce09e576e3ad9d00c38b51..54e85c07344b21a944336c376a8e3c1833341498 100644 (file)
@@ -23,7 +23,7 @@ fn install_tests(tests: &HashMap<String, Test>, into: &str) {
         // ok is never actually read, but it needs to be specified to create a Test in existing_tests
         let existing = existing_tests(&tests_dir, true);
         for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
-            panic!("Test is deleted: {}", t);
+            panic!("Test is deleted: {t}");
         }
 
         let mut new_idx = existing.len() + 1;
@@ -31,7 +31,7 @@ fn install_tests(tests: &HashMap<String, Test>, into: &str) {
             let path = match existing.get(name) {
                 Some((path, _test)) => path.clone(),
                 None => {
-                    let file_name = format!("{:04}_{}.rs", new_idx, name);
+                    let file_name = format!("{new_idx:04}_{name}.rs");
                     new_idx += 1;
                     tests_dir.join(file_name)
                 }
@@ -116,7 +116,7 @@ fn existing_tests(dir: &Path, ok: bool) -> HashMap<String, (PathBuf, Test)> {
         let text = fs::read_to_string(&path).unwrap();
         let test = Test { name: name.clone(), text, ok };
         if let Some(old) = res.insert(name, (path, test)) {
-            println!("Duplicate test: {:?}", old);
+            println!("Duplicate test: {old:?}");
         }
     }
     res
index a3ea05f4aff8e9ca60cc2ca53e4858e0f5e1fe9c..7921fda331eed345c56d6dc03f23c5b9f82165d7 100644 (file)
@@ -60,7 +60,7 @@ pub fn new(path: AbsPathBuf) -> io::Result<MacroDylib> {
 
         let info = version::read_dylib_info(&path)?;
         if info.version.0 < 1 || info.version.1 < 47 {
-            let msg = format!("proc-macro {} built by {:#?} is not supported by rust-analyzer, please update your Rust version.", path.display(), info);
+            let msg = format!("proc-macro {} built by {info:#?} is not supported by rust-analyzer, please update your Rust version.", path.display());
             return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
         }
 
index 268a03bb5359b607343d9cecd8daaa60291f8db1..f50ecccf1e2b01442da2d70174ee60b6bfdaa94e 100644 (file)
@@ -137,7 +137,7 @@ impl SubtreeRepr {
             1 => Some(tt::DelimiterKind::Parenthesis),
             2 => Some(tt::DelimiterKind::Brace),
             3 => Some(tt::DelimiterKind::Bracket),
-            other => panic!("bad kind {}", other),
+            other => panic!("bad kind {other}"),
         };
         SubtreeRepr { id: TokenId(id), kind, tt: [lo, len] }
     }
@@ -164,7 +164,7 @@ impl PunctRepr {
         let spacing = match spacing {
             0 => tt::Spacing::Alone,
             1 => tt::Spacing::Joint,
-            other => panic!("bad spacing {}", other),
+            other => panic!("bad spacing {other}"),
         };
         PunctRepr { id: TokenId(id), char: char.try_into().unwrap(), spacing }
     }
@@ -312,7 +312,7 @@ pub(crate) fn read(self) -> tt::Subtree {
                                 })
                                 .into()
                             }
-                            other => panic!("bad tag: {}", other),
+                            other => panic!("bad tag: {other}"),
                         }
                     })
                     .collect(),
index 030531b80d7bb0d7b511a6e1ba00016561a846c9..40125c2a512ad28ac20e278675800a197b654b59 100644 (file)
@@ -125,7 +125,7 @@ pub fn read_version(dylib_path: &AbsPath) -> io::Result<String> {
         _ => {
             return Err(io::Error::new(
                 io::ErrorKind::InvalidData,
-                format!("unsupported metadata version {}", version),
+                format!("unsupported metadata version {version}"),
             ));
         }
     }
index a405497f3c9b7858da927d1b5d1be5eedff0c261..c5145d00e329e6c22fb75baa2336b5ea0b2091e5 100644 (file)
@@ -877,7 +877,7 @@ impl Literal {
     /// example if it is infinity or NaN this function will panic.
     pub fn f32_unsuffixed(n: f32) -> Literal {
         if !n.is_finite() {
-            panic!("Invalid float literal {}", n);
+            panic!("Invalid float literal {n}");
         }
         let mut repr = n.to_string();
         if !repr.contains('.') {
@@ -901,7 +901,7 @@ pub fn f32_unsuffixed(n: f32) -> Literal {
     /// example if it is infinity or NaN this function will panic.
     pub fn f32_suffixed(n: f32) -> Literal {
         if !n.is_finite() {
-            panic!("Invalid float literal {}", n);
+            panic!("Invalid float literal {n}");
         }
         Literal(bridge::client::Literal::f32(&n.to_string()))
     }
@@ -920,7 +920,7 @@ pub fn f32_suffixed(n: f32) -> Literal {
     /// example if it is infinity or NaN this function will panic.
     pub fn f64_unsuffixed(n: f64) -> Literal {
         if !n.is_finite() {
-            panic!("Invalid float literal {}", n);
+            panic!("Invalid float literal {n}");
         }
         let mut repr = n.to_string();
         if !repr.contains('.') {
@@ -944,7 +944,7 @@ pub fn f64_unsuffixed(n: f64) -> Literal {
     /// example if it is infinity or NaN this function will panic.
     pub fn f64_suffixed(n: f64) -> Literal {
         if !n.is_finite() {
-            panic!("Invalid float literal {}", n);
+            panic!("Invalid float literal {n}");
         }
         Literal(bridge::client::Literal::f64(&n.to_string()))
     }
index c19684850fcb53dcaccab56643504076c1fc72df..22d4ad94f770e8e59329d98562bf53a579f34d16 100644 (file)
@@ -548,13 +548,13 @@ fn float(&mut self, n: &str) -> Self::Literal {
 
     fn f32(&mut self, n: &str) -> Self::Literal {
         let n: f32 = n.parse().unwrap();
-        let text = format!("{}f32", n);
+        let text = format!("{n}f32");
         Literal { text: text.into(), id: tt::TokenId::unspecified() }
     }
 
     fn f64(&mut self, n: &str) -> Self::Literal {
         let n: f64 = n.parse().unwrap();
-        let text = format!("{}f64", n);
+        let text = format!("{n}f64");
         Literal { text: text.into(), id: tt::TokenId::unspecified() }
     }
 
@@ -563,11 +563,11 @@ fn string(&mut self, string: &str) -> Self::Literal {
         for ch in string.chars() {
             escaped.extend(ch.escape_debug());
         }
-        Literal { text: format!("\"{}\"", escaped).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("\"{escaped}\"").into(), id: tt::TokenId::unspecified() }
     }
 
     fn character(&mut self, ch: char) -> Self::Literal {
-        Literal { text: format!("'{}'", ch).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("'{ch}'").into(), id: tt::TokenId::unspecified() }
     }
 
     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
@@ -578,7 +578,7 @@ fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
             .map(Into::<char>::into)
             .collect::<String>();
 
-        Literal { text: format!("b\"{}\"", string).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("b\"{string}\"").into(), id: tt::TokenId::unspecified() }
     }
 
     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
index eb9d7a94b5dc9c4f18345ec160408a07d769b34f..f82f20c37bc3d323b117452ce38d1b694e3ba9f6 100644 (file)
@@ -563,13 +563,13 @@ fn float(&mut self, n: &str) -> Self::Literal {
 
     fn f32(&mut self, n: &str) -> Self::Literal {
         let n: f32 = n.parse().unwrap();
-        let text = format!("{}f32", n);
+        let text = format!("{n}f32");
         Literal { text: text.into(), id: tt::TokenId::unspecified() }
     }
 
     fn f64(&mut self, n: &str) -> Self::Literal {
         let n: f64 = n.parse().unwrap();
-        let text = format!("{}f64", n);
+        let text = format!("{n}f64");
         Literal { text: text.into(), id: tt::TokenId::unspecified() }
     }
 
@@ -578,11 +578,11 @@ fn string(&mut self, string: &str) -> Self::Literal {
         for ch in string.chars() {
             escaped.extend(ch.escape_debug());
         }
-        Literal { text: format!("\"{}\"", escaped).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("\"{escaped}\"").into(), id: tt::TokenId::unspecified() }
     }
 
     fn character(&mut self, ch: char) -> Self::Literal {
-        Literal { text: format!("'{}'", ch).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("'{ch}'").into(), id: tt::TokenId::unspecified() }
     }
 
     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
@@ -593,7 +593,7 @@ fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
             .map(Into::<char>::into)
             .collect::<String>();
 
-        Literal { text: format!("b\"{}\"", string).into(), id: tt::TokenId::unspecified() }
+        Literal { text: format!("b\"{string}\"").into(), id: tt::TokenId::unspecified() }
     }
 
     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
index b4f5ebd157f33d04c1a94a21b76cef917c4ba667..2eb939a7ce581ef219f8917c1a9ec38d265dbab7 100644 (file)
@@ -48,7 +48,7 @@ impl ProcMacroSrv {
     pub fn expand(&mut self, task: ExpandMacro) -> Result<FlatTree, PanicMessage> {
         let expander = self.expander(task.lib.as_ref()).map_err(|err| {
             debug_assert!(false, "should list macros before asking to expand");
-            PanicMessage(format!("failed to load macro: {}", err))
+            PanicMessage(format!("failed to load macro: {err}"))
         })?;
 
         let prev_env = EnvSnapshot::new();
@@ -59,7 +59,7 @@ pub fn expand(&mut self, task: ExpandMacro) -> Result<FlatTree, PanicMessage> {
             Some(dir) => {
                 let prev_working_dir = std::env::current_dir().ok();
                 if let Err(err) = std::env::set_current_dir(&dir) {
-                    eprintln!("Failed to set the current working dir to {}. Error: {:?}", dir, err)
+                    eprintln!("Failed to set the current working dir to {dir}. Error: {err:?}")
                 }
                 prev_working_dir
             }
@@ -112,14 +112,16 @@ pub(crate) fn list_macros(
     }
 
     fn expander(&mut self, path: &Path) -> Result<&dylib::Expander, String> {
-        let time = fs::metadata(path).and_then(|it| it.modified()).map_err(|err| {
-            format!("Failed to get file metadata for {}: {}", path.display(), err)
-        })?;
+        let time = fs::metadata(path)
+            .and_then(|it| it.modified())
+            .map_err(|err| format!("Failed to get file metadata for {}: {err}", path.display()))?;
 
         Ok(match self.expanders.entry((path.to_path_buf(), time)) {
-            Entry::Vacant(v) => v.insert(dylib::Expander::new(path).map_err(|err| {
-                format!("Cannot create expander for {}: {}", path.display(), err)
-            })?),
+            Entry::Vacant(v) => {
+                v.insert(dylib::Expander::new(path).map_err(|err| {
+                    format!("Cannot create expander for {}: {err}", path.display())
+                })?)
+            }
             Entry::Occupied(e) => e.into_mut(),
         })
     }
index dd6203e2eeb997f9558f16299f0ba03e2bbd55ff..340e9f93ed6c26d8eaa09bc9e944b7b199124597 100644 (file)
@@ -71,7 +71,7 @@ fn main() {
         .arg("--target-dir")
         .arg(&target_dir);
 
-    println!("Running {:?}", cmd);
+    println!("Running {cmd:?}");
 
     let output = cmd.output().unwrap();
     if !output.status.success() {
@@ -87,7 +87,7 @@ fn main() {
     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()) {
-                let repr = format!("{} {}", name, version);
+                let repr = format!("{name} {version}");
                 if artifact.package_id.repr.starts_with(&repr) {
                     artifact_path = Some(PathBuf::from(&artifact.filenames[0]));
                 }
index deea0b0dd8f131557c4be9f46c07d36704aaef40..ea89a89c5c5ca89da3c4dcf89607f1e18d16507d 100644 (file)
@@ -238,7 +238,7 @@ fn pop(&mut self, label: Label, detail: Option<String>) {
             self.heartbeat(frame.heartbeats);
             let avg_span = duration / (frame.heartbeats + 1);
             if avg_span > self.filter.heartbeat_longer_than {
-                eprintln!("Too few heartbeats {} ({}/{:?})?", label, frame.heartbeats, duration);
+                eprintln!("Too few heartbeats {label} ({}/{duration:?})?", frame.heartbeats);
             }
         }
 
@@ -275,7 +275,7 @@ fn print(
     out: &mut impl Write,
 ) {
     let current_indent = "    ".repeat(level as usize);
-    let detail = tree[curr].detail.as_ref().map(|it| format!(" @ {}", it)).unwrap_or_default();
+    let detail = tree[curr].detail.as_ref().map(|it| format!(" @ {it}")).unwrap_or_default();
     writeln!(
         out,
         "{}{} - {}{}",
@@ -302,13 +302,13 @@ fn print(
     }
 
     for (child_msg, (duration, count)) in &short_children {
-        writeln!(out, "    {}{} - {} ({} calls)", current_indent, ms(*duration), child_msg, count)
+        writeln!(out, "    {current_indent}{} - {child_msg} ({count} calls)", ms(*duration))
             .expect("printing profiling info");
     }
 
     let unaccounted = tree[curr].duration - accounted_for;
     if tree.children(curr).next().is_some() && unaccounted > longer_than {
-        writeln!(out, "    {}{} - ???", current_indent, ms(unaccounted))
+        writeln!(out, "    {current_indent}{} - ???", ms(unaccounted))
             .expect("printing profiling info");
     }
 }
@@ -320,7 +320,7 @@ impl fmt::Display for ms {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.0.as_millis() {
             0 => f.write_str("    0  "),
-            n => write!(f, "{:5}ms", n),
+            n => write!(f, "{n:5}ms"),
         }
     }
 }
index ee882b4cb4c68fa9174cf9bdd56e4c346670b482..8017f865792b36e451f6b35c7b54ebd4cca6472b 100644 (file)
@@ -109,7 +109,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                 suffix = "mb";
             }
         }
-        f.pad(&format!("{}{}", value, suffix))
+        f.pad(&format!("{value}{suffix}"))
     }
 }
 
index 6258328482962d622b0c6d91ee1641d7cf35940c..71303d5a631621119abbc2a1a7deb4c62e8d269f 100644 (file)
@@ -33,11 +33,11 @@ pub fn start() -> StopWatch {
             if *PERF_ENABLED {
                 let mut counter = perf_event::Builder::new()
                     .build()
-                    .map_err(|err| eprintln!("Failed to create perf counter: {}", err))
+                    .map_err(|err| eprintln!("Failed to create perf counter: {err}"))
                     .ok();
                 if let Some(counter) = &mut counter {
                     if let Err(err) = counter.enable() {
-                        eprintln!("Failed to start perf counter: {}", err)
+                        eprintln!("Failed to start perf counter: {err}")
                     }
                 }
                 counter
@@ -64,7 +64,7 @@ pub fn elapsed(&mut self) -> StopWatchSpan {
 
         #[cfg(target_os = "linux")]
         let instructions = self.counter.as_mut().and_then(|it| {
-            it.read().map_err(|err| eprintln!("Failed to read perf counter: {}", err)).ok()
+            it.read().map_err(|err| eprintln!("Failed to read perf counter: {err}")).ok()
         });
         #[cfg(not(target_os = "linux"))]
         let instructions = None;
@@ -91,10 +91,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                 instructions /= 1000;
                 prefix = "g";
             }
-            write!(f, ", {}{}instr", instructions, prefix)?;
+            write!(f, ", {instructions}{prefix}instr")?;
         }
         if let Some(memory) = self.memory {
-            write!(f, ", {}", memory)?;
+            write!(f, ", {memory}")?;
         }
         Ok(())
     }
index ae2b41f27d58efe226a66e667683cca74788cb47..ae9cba52ded2c447b0a05a88537e860a7091f479 100644 (file)
@@ -295,7 +295,7 @@ fn run_command(
                 match message {
                     Message::BuildScriptExecuted(mut message) => {
                         with_output_for(&message.package_id.repr, &mut |name, data| {
-                            progress(format!("running build-script: {}", name));
+                            progress(format!("running build-script: {name}"));
                             let cfgs = {
                                 let mut acc = Vec::new();
                                 for cfg in &message.cfgs {
@@ -334,7 +334,7 @@ fn run_command(
                     }
                     Message::CompilerArtifact(message) => {
                         with_output_for(&message.package_id.repr, &mut |name, data| {
-                            progress(format!("building proc-macros: {}", name));
+                            progress(format!("building proc-macros: {name}"));
                             if message.target.kind.iter().any(|k| k == "proc-macro") {
                                 // Skip rmeta file
                                 if let Some(filename) =
index f3dd8f51333be447b350e4baf402c0272c7e15b7..c134b78ab3a2e09e5e18f654f8ab8c55a9c6b233 100644 (file)
@@ -17,7 +17,7 @@ fn from_str(s: &str) -> Result<Self, Self::Err> {
         let res = match s.split_once('=') {
             Some((key, value)) => {
                 if !(value.starts_with('"') && value.ends_with('"')) {
-                    return Err(format!("Invalid cfg ({:?}), value should be in quotes", s));
+                    return Err(format!("Invalid cfg ({s:?}), value should be in quotes"));
                 }
                 let key = key.to_string();
                 let value = value[1..value.len() - 1].to_string();
index 835f2b3dd031caf9986ea0be35cbb27961903c8b..e2f09bad2ded5eaa420457fba09942e03b94173a 100644 (file)
@@ -146,7 +146,7 @@ pub fn discover_all(paths: &[AbsPathBuf]) -> Vec<ProjectManifest> {
 }
 
 fn utf8_stdout(mut cmd: Command) -> Result<String> {
-    let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
+    let output = cmd.output().with_context(|| format!("{cmd:?} failed"))?;
     if !output.status.success() {
         match String::from_utf8(output.stderr) {
             Ok(stderr) if !stderr.is_empty() => {
index 5133a14d532bb2467934d058678a5dae6bb5bfaf..9af0eafe9fddbe30b1818d4d08da72d7f7b8d7f3 100644 (file)
@@ -197,5 +197,5 @@ fn deserialize_crate_name<'de, D>(de: D) -> Result<CrateName, D::Error>
     D: de::Deserializer<'de>,
 {
     let name = String::deserialize(de)?;
-    CrateName::new(&name).map_err(|err| de::Error::custom(format!("invalid crate name: {:?}", err)))
+    CrateName::new(&name).map_err(|err| de::Error::custom(format!("invalid crate name: {err:?}")))
 }
index f6c09a27c9d7ea1a03727550603237348454feab..b62b2026b64b8e4e493b80683dce18b2296f0ca6 100644 (file)
@@ -104,7 +104,7 @@ pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result<Sysr
 
         for path in SYSROOT_CRATES.trim().lines() {
             let name = path.split('/').last().unwrap();
-            let root = [format!("{}/src/lib.rs", path), format!("lib{}/lib.rs", path)]
+            let root = [format!("{path}/src/lib.rs"), format!("lib{path}/lib.rs")]
                 .into_iter()
                 .map(|it| sysroot.src_root.join(it))
                 .filter_map(|it| ManifestPath::try_from(it).ok())
index adb106e97931464c3762ce9ca4a73ef004bb9246..2bb9ebf998bdb40903a71d4835187cd373e052df 100644 (file)
@@ -107,7 +107,7 @@ fn to_crate_graph(project_workspace: ProjectWorkspace) -> CrateGraph {
 }
 
 fn check_crate_graph(crate_graph: CrateGraph, expect: Expect) {
-    let mut crate_graph = format!("{:#?}", crate_graph);
+    let mut crate_graph = format!("{crate_graph:#?}");
     replace_root(&mut crate_graph, false);
     expect.assert_eq(&crate_graph);
 }
index ac10721d95514049baa41f351b7a2a4c0a989811..8caadecd850b39de59764966c7076f876d50acea 100644 (file)
@@ -81,9 +81,9 @@ pub(crate) fn install(self) -> Result<()> {
                 Registry::default()
                     .with(
                         self.filter
-                            .add_directive(format!("chalk_solve={}", val).parse()?)
-                            .add_directive(format!("chalk_ir={}", val).parse()?)
-                            .add_directive(format!("chalk_recursive={}", val).parse()?),
+                            .add_directive(format!("chalk_solve={val}").parse()?)
+                            .add_directive(format!("chalk_ir={val}").parse()?)
+                            .add_directive(format!("chalk_recursive={val}").parse()?),
                     )
                     .with(ra_fmt_layer)
                     .with(chalk_layer)
@@ -124,7 +124,7 @@ fn format_event(
             Some(log) => log.target(),
             None => event.metadata().target(),
         };
-        write!(writer, "[{} {}] ", level, target)?;
+        write!(writer, "[{level} {target}] ")?;
 
         // Write spans and fields of each span
         ctx.visit_spans(|span| {
@@ -140,7 +140,7 @@ fn format_event(
             let fields = &ext.get::<FormattedFields<N>>().expect("will never be `None`");
 
             if !fields.is_empty() {
-                write!(writer, "{{{}}}", fields)?;
+                write!(writer, "{{{fields}}}")?;
             }
             write!(writer, ": ")?;
 
index ec5053e991d3d56b84dffb1d8d16eb9648bc1734..53710749de3d400f6d67d85e0e2645a0644b845c 100644 (file)
@@ -30,7 +30,7 @@ fn main() {
         let code = match rustc_wrapper::run_rustc_skipping_cargo_checking(rustc, args.collect()) {
             Ok(rustc_wrapper::ExitCode(code)) => code.unwrap_or(102),
             Err(err) => {
-                eprintln!("{}", err);
+                eprintln!("{err}");
                 101
             }
         };
@@ -40,7 +40,7 @@ fn main() {
     let flags = flags::RustAnalyzer::from_env_or_exit();
     if let Err(err) = try_main(flags) {
         tracing::error!("Unexpected error: {}", err);
-        eprintln!("{}", err);
+        eprintln!("{err}");
         process::exit(101);
     }
 }
index 60ba67e25f93bc08679072f4a25de7bf10bdaf7c..d5d877680a09a513a8392a2a0f3f50eee6da5b50 100644 (file)
@@ -46,7 +46,7 @@ fn report_metric(metric: &str, value: u64, unit: &str) {
     if std::env::var("RA_METRICS").is_err() {
         return;
     }
-    println!("METRIC:{}:{}:{}", metric, value, unit)
+    println!("METRIC:{metric}:{value}:{unit}")
 }
 
 fn print_memory_usage(mut host: AnalysisHost, vfs: Vfs) {
@@ -65,6 +65,6 @@ fn print_memory_usage(mut host: AnalysisHost, vfs: Vfs) {
 
     for (name, bytes) in mem {
         // NOTE: Not a debug print, so avoid going through the `eprintln` defined above.
-        eprintln!("{:>8} {}", bytes, name);
+        eprintln!("{bytes:>8} {name}");
     }
 }
index 01fccc83e8227be05109dd1ada0528c24ed92a28..053db5fc5331dc94a39abef5e595fbb02db44578 100644 (file)
@@ -87,9 +87,9 @@ pub fn run(self, verbosity: Verbosity) -> Result<()> {
             load_workspace(workspace, &cargo_config.extra_env, &load_cargo_config)?;
         let db = host.raw_database();
         eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
-        eprint!(" (metadata {}", metadata_time);
+        eprint!(" (metadata {metadata_time}");
         if let Some(build_scripts_time) = build_scripts_time {
-            eprint!("; build {}", build_scripts_time);
+            eprint!("; build {build_scripts_time}");
         }
         eprintln!(")");
 
@@ -118,7 +118,7 @@ pub fn run(self, verbosity: Verbosity) -> Result<()> {
             shuffle(&mut rng, &mut visit_queue);
         }
 
-        eprint!("  crates: {}", num_crates);
+        eprint!("  crates: {num_crates}");
         let mut num_decls = 0;
         let mut funcs = Vec::new();
         while let Some(module) = visit_queue.pop() {
@@ -142,7 +142,7 @@ pub fn run(self, verbosity: Verbosity) -> Result<()> {
                 }
             }
         }
-        eprintln!(", mods: {}, decls: {}, fns: {}", visited_modules.len(), num_decls, funcs.len());
+        eprintln!(", mods: {}, decls: {num_decls}, fns: {}", visited_modules.len(), funcs.len());
         eprintln!("{:<20} {}", "Item Collection:", analysis_sw.elapsed());
 
         if self.randomize {
@@ -154,7 +154,7 @@ pub fn run(self, verbosity: Verbosity) -> Result<()> {
         }
 
         let total_span = analysis_sw.elapsed();
-        eprintln!("{:<20} {}", "Total:", total_span);
+        eprintln!("{:<20} {total_span}", "Total:");
         report_metric("total time", total_span.time.as_millis() as u64, "ms");
         if let Some(instructions) = total_span.instructions {
             report_metric("total instructions", instructions, "#instr");
@@ -179,7 +179,7 @@ pub fn run(self, verbosity: Verbosity) -> Result<()> {
                     total_macro_file_size += syntax_len(val.syntax_node())
                 }
             }
-            eprintln!("source files: {}, macro files: {}", total_file_size, total_macro_file_size);
+            eprintln!("source files: {total_file_size}, macro files: {total_macro_file_size}");
         }
 
         if self.memory_usage && verbosity.is_verbose() {
@@ -239,7 +239,7 @@ fn run_inference(
                     continue;
                 }
             }
-            let mut msg = format!("processing: {}", full_name);
+            let mut msg = format!("processing: {full_name}");
             if verbosity.is_verbose() {
                 if let Some(src) = f.source(db) {
                     let original_file = src.file_id.original_file(db);
@@ -275,7 +275,7 @@ fn run_inference(
                                 end.col,
                             ));
                         } else {
-                            bar.println(format!("{}: Unknown type", name,));
+                            bar.println(format!("{name}: Unknown type",));
                         }
                     }
                     true
@@ -402,7 +402,7 @@ fn location_csv(
     let text_range = original_range.range;
     let (start, end) =
         (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
-    format!("{},{}:{},{}:{}", path, start.line + 1, start.col, end.line + 1, end.col)
+    format!("{path},{}:{},{}:{}", start.line + 1, start.col, end.line + 1, end.col)
 }
 
 fn expr_syntax_range(
index 247007db0a7883474caaf5b90e031abbd70f3a09..fd5b3ce61f78d3c687ef2086483917d2f9a246f1 100644 (file)
@@ -40,7 +40,7 @@ pub fn run(self) -> anyhow::Result<()> {
             if !visited_files.contains(&file_id) {
                 let crate_name =
                     module.krate().display_name(db).as_deref().unwrap_or("unknown").to_string();
-                println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id));
+                println!("processing crate: {crate_name}, module: {}", _vfs.file_path(file_id));
                 for diagnostic in analysis
                     .diagnostics(
                         &DiagnosticsConfig::test_sample(),
@@ -53,7 +53,7 @@ pub fn run(self) -> anyhow::Result<()> {
                         found_error = true;
                     }
 
-                    println!("{:?}", diagnostic);
+                    println!("{diagnostic:?}");
                 }
 
                 visited_files.insert(file_id);
index 5bcc97e22612257f8e025d2dbd24ff16e0f64bf8..770612cc9478d86b8824c5fe16f36b15907b9510 100644 (file)
@@ -255,7 +255,7 @@ impl FromStr for OutputFormat {
     fn from_str(s: &str) -> Result<Self, Self::Err> {
         match s {
             "csv" => Ok(Self::Csv),
-            _ => Err(format!("unknown output format `{}`", s)),
+            _ => Err(format!("unknown output format `{s}`")),
         }
     }
 }
index 4f9b362f1bec47b430f4781a83a7b545ef0df86d..84607b9fd5d52817f0d7c38add00da5734fa08a0 100644 (file)
@@ -8,7 +8,7 @@ impl flags::Highlight {
     pub fn run(self) -> anyhow::Result<()> {
         let (analysis, file_id) = Analysis::from_single_file(read_stdin()?);
         let html = analysis.highlight_as_html(file_id, self.rainbow).unwrap();
-        println!("{}", html);
+        println!("{html}");
         Ok(())
     }
 }
index 4316177841326ce4fb8f4c6df7522cc189ade485..af8356d041f83608b365d1ed5cce40b9acd73515 100644 (file)
@@ -83,7 +83,7 @@ fn add_edge(&mut self, edge: lsif::Edge) -> Id {
 
     // FIXME: support file in addition to stdout here
     fn emit(&self, data: &str) {
-        println!("{}", data);
+        println!("{data}");
     }
 
     fn get_token_id(&mut self, id: TokenId) -> Id {
index 5a2dc39d52b399c125651c10b3e88c779f93b89f..d459dd115cebe92de194942c5959a348b9524365 100644 (file)
@@ -67,7 +67,7 @@ pub(crate) fn tick(&mut self) {
             return;
         }
         let percent = (self.curr * 100.0) as u32;
-        let text = format!("{}/{} {:3>}% {}", self.pos, self.len, percent, self.msg);
+        let text = format!("{}/{} {percent:3>}% {}", self.pos, self.len, self.msg);
         self.update_text(&text);
     }
 
@@ -114,7 +114,7 @@ fn clear(&mut self) {
         // Fill all last text to space and return the cursor
         let spaces = " ".repeat(self.text.len());
         let backspaces = "\x08".repeat(self.text.len());
-        print!("{}{}{}", backspaces, spaces, backspaces);
+        print!("{backspaces}{spaces}{backspaces}");
         let _ = io::stdout().flush();
 
         self.text = String::new();
index 9edd045ab0716510309e3248ea8c15ce40d55f7f..b1a803d28c6b2513ba238a8bb2b79a048129ac1e 100644 (file)
@@ -28,7 +28,7 @@ pub fn run(self) -> Result<()> {
         let now = Instant::now();
         let cargo_config = CargoConfig::default();
 
-        let no_progress = &|s| (eprintln!("rust-analyzer: Loading {}", s));
+        let no_progress = &|s| (eprintln!("rust-analyzer: Loading {s}"));
         let load_cargo_config = LoadCargoConfig {
             load_out_dirs_from_check: true,
             with_proc_macro: true,
@@ -209,7 +209,7 @@ fn new_descriptor_str(
 fn new_descriptor(name: Name, suffix: scip_types::descriptor::Suffix) -> scip_types::Descriptor {
     let mut name = name.to_string();
     if name.contains("'") {
-        name = format!("`{}`", name);
+        name = format!("`{name}`");
     }
 
     new_descriptor_str(name.as_str(), suffix)
@@ -303,11 +303,11 @@ fn check_symbol(ra_fixture: &str, expected: &str) {
         }
 
         if expected == "" {
-            assert!(found_symbol.is_none(), "must have no symbols {:?}", found_symbol);
+            assert!(found_symbol.is_none(), "must have no symbols {found_symbol:?}");
             return;
         }
 
-        assert!(found_symbol.is_some(), "must have one symbol {:?}", found_symbol);
+        assert!(found_symbol.is_some(), "must have one symbol {found_symbol:?}");
         let res = found_symbol.unwrap();
         let formatted = format_symbol(res);
         assert_eq!(formatted, expected);
index e8291782b7ac15499ed60d7655e73e59a324954d..84c48917167b6778ac8be328011a3cef7c5b5448 100644 (file)
@@ -70,7 +70,7 @@ pub fn run(self) -> Result<()> {
                 let sr = db.source_root(root);
                 for file_id in sr.iter() {
                     for debug_info in match_finder.debug_where_text_equal(file_id, debug_snippet) {
-                        println!("{:#?}", debug_info);
+                        println!("{debug_info:#?}");
                     }
                 }
             }
index 84659b5ea9cd5a471bbc99ba67ece3ccdd7cad8a..9fad6723afcd9025aed3f3876337d3bef02b7537 100644 (file)
@@ -9,7 +9,7 @@ pub fn run(self) -> anyhow::Result<()> {
         let (analysis, file_id) = Analysis::from_single_file(text);
         let structure = analysis.file_structure(file_id).unwrap();
         for s in structure {
-            println!("{:?}", s);
+            println!("{s:?}");
         }
         Ok(())
     }
index 76ff2d5859e9fb83bd5a88b279a356a96a7fe07e..ac496a7a9f9a901a432a62afd98ab1f9547abaa6 100644 (file)
@@ -1869,14 +1869,14 @@ fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json:
         fn key(f: &str) -> &str {
             f.splitn(2, '_').next().unwrap()
         }
-        assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
+        assert!(key(f1) <= key(f2), "wrong field order: {f1:?} {f2:?}");
     }
 
     let map = fields
         .iter()
         .map(|(field, ty, doc, default)| {
             let name = field.replace('_', ".");
-            let name = format!("rust-analyzer.{}", name);
+            let name = format!("rust-analyzer.{name}");
             let props = field_props(field, ty, doc, default);
             (name, props)
         })
@@ -2166,7 +2166,7 @@ macro_rules! set {
                 },
             ],
         },
-        _ => panic!("missing entry for {}: {}", ty, default),
+        _ => panic!("missing entry for {ty}: {default}"),
     }
 
     map.into()
@@ -2194,14 +2194,14 @@ fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
                     name, name, default, doc
                 )
             } else {
-                format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
+                format!("[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n")
             }
         })
         .collect::<String>()
 }
 
 fn doc_comment_to_string(doc: &[&str]) -> String {
-    doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
+    doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{it}\n")).collect()
 }
 
 #[cfg(test)]
@@ -2215,7 +2215,7 @@ mod tests {
     #[test]
     fn generate_package_json_config() {
         let s = Config::json_schema();
-        let schema = format!("{:#}", s);
+        let schema = format!("{s:#}");
         let mut schema = schema
             .trim_start_matches('{')
             .trim_end_matches('}')
index beb23c54c9f0fc7361bd7199073499798dc41ec3..d1ee99af3ec6e5f4a8fa06dd124c9a202b170aed 100644 (file)
@@ -161,7 +161,7 @@ fn resolve_path(
         .iter()
         .find_map(|(from, to)| file_name.strip_prefix(from).map(|file_name| (to, file_name)))
     {
-        Some((to, file_name)) => workspace_root.join(format!("{}{}", to, file_name)),
+        Some((to, file_name)) => workspace_root.join(format!("{to}{file_name}")),
         None => workspace_root.join(file_name),
     }
 }
@@ -218,7 +218,7 @@ fn map_rust_child_diagnostic(
     if !suggested_replacements.is_empty() {
         message.push_str(": ");
         let suggestions =
-            suggested_replacements.iter().map(|suggestion| format!("`{}`", suggestion)).join(", ");
+            suggested_replacements.iter().map(|suggestion| format!("`{suggestion}`")).join(", ");
         message.push_str(&suggestions);
     }
 
@@ -493,7 +493,7 @@ fn rustc_code_description(code: Option<&str>) -> Option<lsp_types::CodeDescripti
             && chars.next().is_none()
     })
     .and_then(|code| {
-        lsp_types::Url::parse(&format!("https://doc.rust-lang.org/error-index.html#{}", code))
+        lsp_types::Url::parse(&format!("https://doc.rust-lang.org/error-index.html#{code}"))
             .ok()
             .map(|href| lsp_types::CodeDescription { href })
     })
index 57899b599146693e176c6135107b05dcff363fe1..715804449a0450e4b58237cfa5cc89d7a754f2bf 100644 (file)
@@ -145,7 +145,7 @@ fn parse<R>(&mut self) -> Option<(lsp_server::Request, R::Params, String)>
         match res {
             Ok(params) => {
                 let panic_context =
-                    format!("\nversion: {}\nrequest: {} {:#?}", version(), R::METHOD, params);
+                    format!("\nversion: {}\nrequest: {} {params:#?}", version(), R::METHOD);
                 Some((req, params, panic_context))
             }
             Err(err) => {
index 4e8bc8d6462ce58362d04a5a625eccb3ac565d59..7f6ced26ce9ae991b4a0af43b24c232337074192 100644 (file)
@@ -429,6 +429,6 @@ pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
 
 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
     let path = from_proto::vfs_path(url)?;
-    let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;
+    let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {path}"))?;
     Ok(res)
 }
index 7a4d372a285b81826769f1e21671f1f9d41a87d2..33f5b8a4efb265fb949afa616a6a5adfbea37936 100644 (file)
@@ -730,7 +730,7 @@ pub(crate) fn handle_runnables(
         Some(spec) => {
             for cmd in ["check", "test"] {
                 res.push(lsp_ext::Runnable {
-                    label: format!("cargo {} -p {} --all-targets", cmd, spec.package),
+                    label: format!("cargo {cmd} -p {} --all-targets", spec.package),
                     location: None,
                     kind: lsp_ext::RunnableKind::Cargo,
                     args: lsp_ext::CargoRunnable {
@@ -1146,8 +1146,8 @@ pub(crate) fn handle_code_action_resolve(
         Ok(parsed_data) => parsed_data,
         Err(e) => {
             return Err(invalid_params_error(format!(
-                "Failed to parse action id string '{}': {}",
-                params.id, e
+                "Failed to parse action id string '{}': {e}",
+                params.id
             ))
             .into())
         }
@@ -1191,7 +1191,7 @@ fn parse_action_id(action_id: &str) -> Result<(usize, SingleResolve), String> {
             let assist_kind: AssistKind = assist_kind_string.parse()?;
             let index: usize = match index_string.parse() {
                 Ok(index) => index,
-                Err(e) => return Err(format!("Incorrect index string: {}", e)),
+                Err(e) => return Err(format!("Incorrect index string: {e}")),
             };
             Ok((index, SingleResolve { assist_id: assist_id_string.to_string(), assist_kind }))
         }
@@ -1870,7 +1870,7 @@ fn run_rustfmt(
         .stdout(Stdio::piped())
         .stderr(Stdio::piped())
         .spawn()
-        .context(format!("Failed to spawn {:?}", command))?;
+        .context(format!("Failed to spawn {command:?}"))?;
 
     rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
 
@@ -1903,9 +1903,9 @@ fn run_rustfmt(
                     format!(
                         r#"rustfmt exited with:
                            Status: {}
-                           stdout: {}
-                           stderr: {}"#,
-                        output.status, captured_stdout, captured_stderr,
+                           stdout: {captured_stdout}
+                           stderr: {captured_stderr}"#,
+                        output.status,
                     ),
                 )
                 .into())
index 96b1cb6b12713d5f0c666d8791cdb890a1d20e43..405d261db6fb407f244ce9073f2bf30a553b2069 100644 (file)
@@ -48,7 +48,7 @@ fn integrated_highlighting_benchmark() {
     let file_id = {
         let file = workspace_to_load.join(file);
         let path = VfsPath::from(AbsPathBuf::assert(file));
-        vfs.file_id(&path).unwrap_or_else(|| panic!("can't find virtual file for {}", path))
+        vfs.file_id(&path).unwrap_or_else(|| panic!("can't find virtual file for {path}"))
     };
 
     {
@@ -102,7 +102,7 @@ fn integrated_completion_benchmark() {
     let file_id = {
         let file = workspace_to_load.join(file);
         let path = VfsPath::from(AbsPathBuf::assert(file));
-        vfs.file_id(&path).unwrap_or_else(|| panic!("can't find virtual file for {}", path))
+        vfs.file_id(&path).unwrap_or_else(|| panic!("can't find virtual file for {path}"))
     };
 
     {
index 552379752fa64e46f65e32a4978ce5e379325539..32dc3750fdf6bfa36e71818f352d19d78952fab2 100644 (file)
@@ -55,7 +55,7 @@ macro_rules! eprintln {
 
 pub fn from_json<T: DeserializeOwned>(what: &'static str, json: &serde_json::Value) -> Result<T> {
     let res = serde_json::from_value(json.clone())
-        .map_err(|e| format!("Failed to deserialize {}: {}; {}", what, e, json))?;
+        .map_err(|e| format!("Failed to deserialize {what}: {e}; {json}"))?;
     Ok(res)
 }
 
index 0971dc36f3a5c84ef1f1ab34ae0da88c4ce70edc..dcaee92857abd3a6d99b7da0aed4e03af391d626 100644 (file)
@@ -98,7 +98,7 @@ pub(crate) fn report_progress(
         });
         let cancellable = Some(cancel_token.is_some());
         let token = lsp_types::ProgressToken::String(
-            cancel_token.unwrap_or_else(|| format!("rustAnalyzer/{}", title)),
+            cancel_token.unwrap_or_else(|| format!("rustAnalyzer/{title}")),
         );
         let work_done_progress = match state {
             Progress::Begin => {
index 2d443231b4ed301b4f5413c6ef7b5612e88110c3..9cedcf1bec1d63c39862a1fe7999ad24adad25d4 100644 (file)
@@ -229,8 +229,8 @@ fn handle_event(&mut self, event: Event) -> Result<()> {
 
                             message = match &report.crates_currently_indexing[..] {
                                 [crate_name] => Some(format!(
-                                    "{}/{} ({})",
-                                    report.crates_done, report.crates_total, crate_name
+                                    "{}/{} ({crate_name})",
+                                    report.crates_done, report.crates_total
                                 )),
                                 [crate_name, rest @ ..] => Some(format!(
                                     "{}/{} ({} + {} more)",
@@ -516,7 +516,7 @@ fn handle_vfs_msg(&mut self, message: vfs::loader::Message) {
                 self.report_progress(
                     "Roots Scanned",
                     state,
-                    Some(format!("{}/{}", n_done, n_total)),
+                    Some(format!("{n_done}/{n_total}")),
                     Some(Progress::fraction(n_done, n_total)),
                     None,
                 )
@@ -587,7 +587,7 @@ fn handle_flycheck_msg(&mut self, message: flycheck::Message) {
                     state,
                     message,
                     None,
-                    Some(format!("rust-analyzer/flycheck/{}", id)),
+                    Some(format!("rust-analyzer/flycheck/{id}")),
                 );
             }
         }
index a7106acc78b157016088c8fda3f86210201748ed..35ced15de549dc0c1394310a318b6268e23af2ff 100644 (file)
@@ -342,7 +342,7 @@ fn set_score(
         // by the client. Hex format is used because it is easier to
         // visually compare very large values, which the sort text
         // tends to be since it is the opposite of the score.
-        res.sort_text = Some(format!("{:08x}", sort_score));
+        res.sort_text = Some(format!("{sort_score:08x}"));
     }
 }
 
@@ -1113,7 +1113,7 @@ pub(crate) fn code_action(
         (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
         (None, Some((index, code_action_params))) => {
             res.data = Some(lsp_ext::CodeActionData {
-                id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
+                id: format!("{}:{}:{index}", assist.id.0, assist.id.1.name()),
                 code_action_params,
             });
         }
@@ -1352,7 +1352,7 @@ pub(crate) fn implementation_title(count: usize) -> String {
     if count == 1 {
         "1 implementation".into()
     } else {
-        format!("{} implementations", count)
+        format!("{count} implementations")
     }
 }
 
@@ -1360,7 +1360,7 @@ pub(crate) fn reference_title(count: usize) -> String {
     if count == 1 {
         "1 reference".into()
     } else {
-        format!("{} references", count)
+        format!("{count} references")
     }
 }
 
index fa55f7d90c49db01e7a0d8019615599a43dafdd3..76eb60ac7cb237d171ee520a847247d23ddd210d 100644 (file)
@@ -263,7 +263,7 @@ fn devdependency() {}
     for runnable in ["consumer", "dependency", "devdependency"] {
         server.request::<Runnables>(
             RunnablesParams {
-                text_document: server.doc_id(&format!("{}/src/lib.rs", runnable)),
+                text_document: server.doc_id(&format!("{runnable}/src/lib.rs")),
                 position: None,
             },
             json!([
@@ -595,8 +595,8 @@ fn diagnostics_dont_block_typing() {
         return;
     }
 
-    let librs: String = (0..10).map(|i| format!("mod m{};", i)).collect();
-    let libs: String = (0..10).map(|i| format!("//- /src/m{}.rs\nfn foo() {{}}\n\n", i)).collect();
+    let librs: String = (0..10).map(|i| format!("mod m{i};")).collect();
+    let libs: String = (0..10).map(|i| format!("//- /src/m{i}.rs\nfn foo() {{}}\n\n")).collect();
     let server = Project::with_fixture(&format!(
         r#"
 //- /Cargo.toml
@@ -622,7 +622,7 @@ fn main() {{}}
     for i in 0..10 {
         server.notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
             text_document: TextDocumentItem {
-                uri: server.doc_id(&format!("src/m{}.rs", i)).uri,
+                uri: server.doc_id(&format!("src/m{i}.rs")).uri,
                 language_id: "rust".to_string(),
                 version: 0,
                 text: "/// Docs\nfn foo() {}".to_string(),
@@ -645,7 +645,7 @@ fn main() {{}}
         }]),
     );
     let elapsed = start.elapsed();
-    assert!(elapsed.as_millis() < 2000, "typing enter took {:?}", elapsed);
+    assert!(elapsed.as_millis() < 2000, "typing enter took {elapsed:?}");
 }
 
 #[test]
@@ -942,7 +942,7 @@ fn test_will_rename_files_same_level() {
     let tmp_dir = TestDir::new();
     let tmp_dir_path = tmp_dir.path().to_owned();
     let tmp_dir_str = tmp_dir_path.to_str().unwrap();
-    let base_path = PathBuf::from(format!("file://{}", tmp_dir_str));
+    let base_path = PathBuf::from(format!("file://{tmp_dir_str}"));
 
     let code = r#"
 //- /Cargo.toml
index e6ac018a05feaf07173992fff3602c3b25f37996..7465ca9ab5773234afca8dac102f1839eafef6fe 100644 (file)
@@ -42,7 +42,7 @@ fn collect_file(acc: &mut Vec<Feature>, path: PathBuf) -> io::Result<()> {
             for block in comment_blocks {
                 let id = block.id;
                 if let Err(msg) = is_valid_feature_name(&id) {
-                    panic!("invalid feature name: {:?}:\n  {}", id, msg)
+                    panic!("invalid feature name: {id:?}:\n  {msg}")
                 }
                 let doc = block.contents.join("\n");
                 let location = sourcegen::Location { file: path.clone(), line: block.line };
@@ -63,11 +63,11 @@ fn is_valid_feature_name(feature: &str) -> Result<(), String> {
         }
         for short in ["To", "And"] {
             if word == short {
-                return Err(format!("Don't capitalize {:?}", word));
+                return Err(format!("Don't capitalize {word:?}"));
             }
         }
         if !word.starts_with(char::is_uppercase) {
-            return Err(format!("Capitalize {:?}", word));
+            return Err(format!("Capitalize {word:?}"));
         }
     }
     Ok(())
index 7257445dabe05f108da9bebcb6c61162bc72137b..269212ebb99c1b2d337216400a1a341aa03e8657 100644 (file)
@@ -216,7 +216,7 @@ pub(crate) fn send_request<R>(&self, params: R::Params) -> Value
     fn send_request_(&self, r: Request) -> Value {
         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)) {
+        while let Some(msg) = self.recv().unwrap_or_else(|Timeout| panic!("timeout: {r:?}")) {
             match msg {
                 Message::Request(req) => {
                     if req.method == "client/registerCapability" {
@@ -228,19 +228,19 @@ fn send_request_(&self, r: Request) -> Value {
                             continue;
                         }
                     }
-                    panic!("unexpected request: {:?}", req)
+                    panic!("unexpected request: {req:?}")
                 }
                 Message::Notification(_) => (),
                 Message::Response(res) => {
                     assert_eq!(res.id, id);
                     if let Some(err) = res.error {
-                        panic!("error response: {:#?}", err);
+                        panic!("error response: {err:#?}");
                     }
                     return res.result.unwrap();
                 }
             }
         }
-        panic!("no response for {:?}", r);
+        panic!("no response for {r:?}");
     }
     pub(crate) fn wait_until_workspace_is_loaded(self) -> Server {
         self.wait_for_message_cond(1, &|msg: &Message| match msg {
index 3bec23a911750fdf703eb246e7a538775367a133..f7fceb588869634363418b5664105d5392536420 100644 (file)
@@ -28,7 +28,7 @@ pub(crate) fn new() -> TestDir {
         static CNT: AtomicUsize = AtomicUsize::new(0);
         for _ in 0..100 {
             let cnt = CNT.fetch_add(1, Ordering::Relaxed);
-            let path = base.join(format!("{}_{}", pid, cnt));
+            let path = base.join(format!("{pid}_{cnt}"));
             if path.is_dir() {
                 continue;
             }
@@ -53,7 +53,7 @@ fn drop(&mut self) {
             return;
         }
         remove_dir_all(&self.path).unwrap_or_else(|err| {
-            panic!("failed to remove temporary directory {}: {}", self.path.display(), err)
+            panic!("failed to remove temporary directory {}: {err}", self.path.display())
         })
     }
 }
index 24e68eca676d7419ece4bb0125f479f652a617ef..745faf424916d01519563fe40c8ac07a22e402f5 100644 (file)
@@ -216,18 +216,18 @@ fn check_licenses() {
         diff.push_str("New Licenses:\n");
         for &l in licenses.iter() {
             if !expected.contains(&l) {
-                diff += &format!("  {}\n", l)
+                diff += &format!("  {l}\n")
             }
         }
 
         diff.push_str("\nMissing Licenses:\n");
         for &l in expected.iter() {
             if !licenses.contains(&l) {
-                diff += &format!("  {}\n", l)
+                diff += &format!("  {l}\n")
             }
         }
 
-        panic!("different set of licenses!\n{}", diff);
+        panic!("different set of licenses!\n{diff}");
     }
     assert_eq!(licenses, expected);
 }
@@ -316,7 +316,7 @@ fn check_test_attrs(path: &Path, text: &str) {
         "ide-assists/src/tests/generated.rs",
     ];
     if text.contains("#[ignore") && !need_ignore.iter().any(|p| path.ends_with(p)) {
-        panic!("\ndon't `#[ignore]` tests, see:\n\n    {}\n\n   {}\n", ignore_rule, path.display(),)
+        panic!("\ndon't `#[ignore]` tests, see:\n\n    {ignore_rule}\n\n   {}\n", path.display(),)
     }
 
     let panic_rule =
@@ -438,7 +438,7 @@ fn finish(self) {
             self.hits.symmetric_difference(&self.checks).map(|it| it.as_str()).collect();
 
         if !diff.is_empty() {
-            panic!("unpaired marks: {:?}", diff)
+            panic!("unpaired marks: {diff:?}")
         }
     }
 }
index 4e0ee63f32f26a2e7ce56b832325e223bb0233b7..9d7a0c480bde535319dd4b863448c8c1fd1d66ec 100644 (file)
@@ -57,7 +57,7 @@ impl CommentBlock {
     pub fn extract(tag: &str, text: &str) -> Vec<CommentBlock> {
         assert!(tag.starts_with(char::is_uppercase));
 
-        let tag = format!("{}:", tag);
+        let tag = format!("{tag}:");
         // Would be nice if we had `.retain_mut` here!
         CommentBlock::extract_untagged(text)
             .into_iter()
@@ -163,7 +163,7 @@ pub fn reformat(text: String) -> String {
 }
 
 pub fn add_preamble(generator: &'static str, mut text: String) -> String {
-    let preamble = format!("//! Generated by `{}`, do not edit by hand.\n\n", generator);
+    let preamble = format!("//! Generated by `{generator}`, do not edit by hand.\n\n");
     text.insert_str(0, &preamble);
     text
 }
index a64f9a6f3faacba7563f1b048a6ee95b28abb87c..c3e8813b0e813356aa209f94fa4c83e1ee930a8b 100644 (file)
@@ -25,7 +25,7 @@ fn init() {
                 if !ctx.is_empty() {
                     eprintln!("Panic context:");
                     for frame in ctx.iter() {
-                        eprintln!("> {}\n", frame);
+                        eprintln!("> {frame}\n");
                     }
                 }
                 default_hook(panic_info);
index 8b14789dd917da224e63250d6373942076d68b25..bcfece4503c8dd38f2796de7dd8a74d3630925f9 100644 (file)
@@ -616,7 +616,7 @@ fn check_diff(from: &str, to: &str, expected_diff: Expect) {
 
         let fmt_syntax = |syn: &SyntaxElement| match syn.kind() {
             SyntaxKind::WHITESPACE => format!("{:?}", syn.to_string()),
-            _ => format!("{}", syn),
+            _ => format!("{syn}"),
         };
 
         let insertions =
@@ -637,7 +637,7 @@ fn check_diff(from: &str, to: &str, expected_diff: Expect) {
             .iter()
             .sorted_by_key(|(syntax, _)| syntax.text_range().start())
             .format_with("\n", |(k, v), f| {
-                f(&format!("Line {}: {:?} -> {}", line_number(k), k, fmt_syntax(v)))
+                f(&format!("Line {}: {k:?} -> {}", line_number(k), fmt_syntax(v)))
             });
 
         let deletions = diff
index 15805dfc8608feba4429576eee1bb3e3db28fc2c..5bc6b780e47fa3ae74b50bb3080e3b1ebeac4d8b 100644 (file)
@@ -87,7 +87,7 @@ pub(super) fn increase_indent(self, node: &SyntaxNode) {
         for token in tokens {
             if let Some(ws) = ast::Whitespace::cast(token) {
                 if ws.text().contains('\n') {
-                    let new_ws = make::tokens::whitespace(&format!("{}{}", ws.syntax(), self));
+                    let new_ws = make::tokens::whitespace(&format!("{}{self}", ws.syntax()));
                     ted::replace(ws.syntax(), &new_ws);
                 }
             }
@@ -103,7 +103,7 @@ pub(super) fn decrease_indent(self, node: &SyntaxNode) {
             if let Some(ws) = ast::Whitespace::cast(token) {
                 if ws.text().contains('\n') {
                     let new_ws = make::tokens::whitespace(
-                        &ws.syntax().text().replace(&format!("\n{}", self), "\n"),
+                        &ws.syntax().text().replace(&format!("\n{self}"), "\n"),
                     );
                     ted::replace(ws.syntax(), &new_ws);
                 }
index 660c057e99c5671636e8cd0d5d3a75b2545fe08e..d7ad4f332f36be2f91225266621d29ecb9be9ea3 100644 (file)
@@ -481,7 +481,7 @@ pub fn add_item(&self, item: ast::AssocItem) {
             },
         };
         let elements: Vec<SyntaxElement<_>> = vec![
-            make::tokens::whitespace(&format!("{}{}", whitespace, indent)).into(),
+            make::tokens::whitespace(&format!("{whitespace}{indent}")).into(),
             item.syntax().clone().into(),
         ];
         ted::insert_all(position, elements);
@@ -537,7 +537,7 @@ pub fn add_arm(&self, arm: ast::MatchArm) {
             },
         };
         let indent = IndentLevel::from_node(self.syntax()) + 1;
-        elements.push(make::tokens::whitespace(&format!("\n{}", indent)).into());
+        elements.push(make::tokens::whitespace(&format!("\n{indent}")).into());
         elements.push(arm.syntax().clone().into());
         if needs_comma(&arm) {
             ted::append_child(arm.syntax(), make::token(SyntaxKind::COMMA));
@@ -555,7 +555,7 @@ pub fn add_field(&self, field: ast::RecordExprField) {
         let is_multiline = self.syntax().text().contains_char('\n');
         let whitespace = if is_multiline {
             let indent = IndentLevel::from_node(self.syntax()) + 1;
-            make::tokens::whitespace(&format!("\n{}", indent))
+            make::tokens::whitespace(&format!("\n{indent}"))
         } else {
             make::tokens::single_space()
         };
@@ -616,7 +616,7 @@ pub fn add_field(&self, field: ast::RecordPatField) {
         let is_multiline = self.syntax().text().contains_char('\n');
         let whitespace = if is_multiline {
             let indent = IndentLevel::from_node(self.syntax()) + 1;
-            make::tokens::whitespace(&format!("\n{}", indent))
+            make::tokens::whitespace(&format!("\n{indent}"))
         } else {
             make::tokens::single_space()
         };
@@ -681,7 +681,7 @@ pub fn add_variant(&self, variant: ast::Variant) {
             },
         };
         let elements: Vec<SyntaxElement<_>> = vec![
-            make::tokens::whitespace(&format!("{}{}", "\n", indent)).into(),
+            make::tokens::whitespace(&format!("{}{indent}", "\n")).into(),
             variant.syntax().clone().into(),
             ast::make::token(T![,]).into(),
         ];
@@ -704,11 +704,11 @@ fn normalize_ws_between_braces(node: &SyntaxNode) -> Option<()> {
     match l.next_sibling_or_token() {
         Some(ws) if ws.kind() == SyntaxKind::WHITESPACE => {
             if ws.next_sibling_or_token()?.into_token()? == r {
-                ted::replace(ws, make::tokens::whitespace(&format!("\n{}", indent)));
+                ted::replace(ws, make::tokens::whitespace(&format!("\n{indent}")));
             }
         }
         Some(ws) if ws.kind() == T!['}'] => {
-            ted::insert(Position::after(l), make::tokens::whitespace(&format!("\n{}", indent)));
+            ted::insert(Position::after(l), make::tokens::whitespace(&format!("\n{indent}")));
         }
         _ => (),
     }
index 8990f7a7d4e8ec4b85d5906667216f5835e8cb80..ca18196300df614a787ff551fde5efd30f6bd543 100644 (file)
@@ -436,9 +436,7 @@ fn test_int_number_suffix() {
 
     fn check_string_value<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
         assert_eq!(
-            ast::String { syntax: make::tokens::literal(&format!("\"{}\"", lit)) }
-                .value()
-                .as_deref(),
+            ast::String { syntax: make::tokens::literal(&format!("\"{lit}\"")) }.value().as_deref(),
             expected.into()
         );
     }
@@ -461,7 +459,7 @@ fn check_byte_string_value<'a, const N: usize>(
         expected: impl Into<Option<&'a [u8; N]>>,
     ) {
         assert_eq!(
-            ast::ByteString { syntax: make::tokens::literal(&format!("b\"{}\"", lit)) }
+            ast::ByteString { syntax: make::tokens::literal(&format!("b\"{lit}\"")) }
                 .value()
                 .as_deref(),
             expected.into().map(|value| &value[..])
index 7c7a60d62994eeca97712716beef99b45146a6e2..239a89f9b2d5200b6a671a44bc88b24fb0d2c53b 100644 (file)
@@ -36,7 +36,7 @@ pub fn from_data(data: &[u8]) -> Option<Self> {
         let delete_len = usize::from_str(lines.next()?).ok()?;
         let insert = lines.next()?.to_string();
         let text = lines.collect::<Vec<_>>().join("\n");
-        let text = format!("{}{}{}", PREFIX, text, SUFFIX);
+        let text = format!("{PREFIX}{text}{SUFFIX}");
         text.get(delete_start..delete_start.checked_add(delete_len)?)?; // make sure delete is a valid range
         let delete =
             TextRange::at(delete_start.try_into().unwrap(), delete_len.try_into().unwrap());
@@ -60,8 +60,8 @@ pub fn run(&self) {
                 eprint!("reparsed:\n{:#?}", new_parse.tree().syntax());
                 eprint!("full reparse:\n{:#?}", full_reparse.tree().syntax());
                 assert_eq!(
-                    format!("{:?}", a),
-                    format!("{:?}", b),
+                    format!("{a:?}"),
+                    format!("{b:?}"),
                     "different syntax tree produced by the full reparse"
                 );
             }
index ec3d3d444c365822f5c9d7efea9e8268f1bb36b1..a3023c3195f3f0793d2f94453c55b8cff94a388b 100644 (file)
@@ -6,7 +6,7 @@
 
 pub fn parse_expr_from_str(s: &str) -> Option<ast::Expr> {
     let s = s.trim();
-    let file = ast::SourceFile::parse(&format!("const _: () = {};", s));
+    let file = ast::SourceFile::parse(&format!("const _: () = {s};"));
     let expr = file.syntax_node().descendants().find_map(ast::Expr::cast)?;
     if expr.syntax().text() != s {
         return None;
index a47b4b11c0ae6e5e22f288e7fc4288726c5f034d..29788d05e845fbdca757dbb187d0f7574946289e 100644 (file)
@@ -157,7 +157,7 @@ fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {
         if let Some(item_list) = prev.parent().and_then(ast::ItemList::cast) {
             let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into());
             indent.0 += 1;
-            return Some(make::tokens::whitespace(&format!("\n{}", indent)));
+            return Some(make::tokens::whitespace(&format!("\n{indent}")));
         }
     }
 
@@ -165,7 +165,7 @@ fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {
         if let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast) {
             let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into());
             indent.0 += 1;
-            return Some(make::tokens::whitespace(&format!("\n{}", indent)));
+            return Some(make::tokens::whitespace(&format!("\n{indent}")));
         }
     }
 
@@ -200,7 +200,7 @@ fn ws_between(left: &SyntaxElement, right: &SyntaxElement) -> Option<SyntaxToken
         if left.kind() == SyntaxKind::USE {
             indent.0 = IndentLevel::from_element(right).0.max(indent.0);
         }
-        return Some(make::tokens::whitespace(&format!("\n{}", indent)));
+        return Some(make::tokens::whitespace(&format!("\n{indent}")));
     }
     Some(make::tokens::single_space())
 }
index 58fba8cfa8f05ccda4c4e063cdcda733806b4848..9148c08b4af3f4ca5bd56a5e1c20f8dd3071d509 100644 (file)
@@ -108,7 +108,7 @@ fn self_hosting_parsing() {
             .into_iter()
             .map(|(path, err)| format!("{}: {:?}\n", path.display(), err[0]))
             .collect::<String>();
-        panic!("Parsing errors:\n{}\n", errors);
+        panic!("Parsing errors:\n{errors}\n");
     }
 }
 
@@ -181,6 +181,6 @@ fn rust_files_in_dir(dir: &Path) -> Vec<PathBuf> {
 /// so this should always be correct.
 fn read_text(path: &Path) -> String {
     fs::read_to_string(path)
-        .unwrap_or_else(|_| panic!("File at {:?} should be valid", path))
+        .unwrap_or_else(|_| panic!("File at {path:?} should be valid"))
         .replace("\r\n", "\n")
 }
index 712ef5f63b651e9e3db63378dff73210a7622a12..d66ff7365f8e991ce50e96802e9696ccacf22549 100644 (file)
@@ -328,7 +328,7 @@ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 
 fn write_doc_comment(contents: &[String], dest: &mut String) {
     for line in contents {
-        writeln!(dest, "///{}", line).unwrap();
+        writeln!(dest, "///{line}").unwrap();
     }
 }
 
@@ -501,7 +501,7 @@ fn to_pascal_case(s: &str) -> String {
 }
 
 fn pluralize(s: &str) -> String {
-    format!("{}s", s)
+    format!("{s}s")
 }
 
 impl Field {
@@ -637,7 +637,7 @@ fn lower_rule(acc: &mut Vec<Field>, grammar: &Grammar, label: Option<&String>, r
             let mut name = grammar[*token].name.clone();
             if name != "int_number" && name != "string" {
                 if "[]{}()".contains(&name) {
-                    name = format!("'{}'", name);
+                    name = format!("'{name}'");
                 }
                 let field = Field::Token(name);
                 acc.push(field);
@@ -651,7 +651,7 @@ fn lower_rule(acc: &mut Vec<Field>, grammar: &Grammar, label: Option<&String>, r
                 acc.push(field);
                 return;
             }
-            panic!("unhandled rule: {:?}", rule)
+            panic!("unhandled rule: {rule:?}")
         }
         Rule::Labeled { label: l, rule } => {
             assert!(label.is_none());
index 24502ddb41aff489af210866ddbf1f4e93ca2aee..d6acdde383f1fdaeba6d0556d6eb4e708069a5ae 100644 (file)
@@ -83,7 +83,7 @@ fn finish(&mut self) {
 
         let a = mean_y - b * mean_x;
 
-        self.plot = format!("y_pred = {:.3} + {:.3} * x\n\nx     y     y_pred\n", a, b);
+        self.plot = format!("y_pred = {a:.3} + {b:.3} * x\n\nx     y     y_pred\n");
 
         let mut se = 0.0;
         let mut max_error = 0.0f64;
index 73e72c18809b59702f7fdd074f70fca6b278c80f..e7bc64620b2ce3c1539e6c113fcba5d7e00d2df2 100644 (file)
@@ -153,7 +153,7 @@ pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<String>, Vec<Fixture>)
                     && !line.contains('.')
                     && line.chars().all(|it| !it.is_uppercase())
                 {
-                    panic!("looks like invalid metadata line: {:?}", line);
+                    panic!("looks like invalid metadata line: {line:?}");
                 }
 
                 if let Some(entry) = res.last_mut() {
@@ -172,7 +172,7 @@ fn parse_meta_line(meta: &str) -> Fixture {
         let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
 
         let path = components[0].to_string();
-        assert!(path.starts_with('/'), "fixture path does not start with `/`: {:?}", path);
+        assert!(path.starts_with('/'), "fixture path does not start with `/`: {path:?}");
 
         let mut krate = None;
         let mut deps = Vec::new();
@@ -184,9 +184,8 @@ fn parse_meta_line(meta: &str) -> Fixture {
         let mut introduce_new_source_root = None;
         let mut target_data_layout = None;
         for component in components[1..].iter() {
-            let (key, value) = component
-                .split_once(':')
-                .unwrap_or_else(|| panic!("invalid meta line: {:?}", meta));
+            let (key, value) =
+                component.split_once(':').unwrap_or_else(|| panic!("invalid meta line: {meta:?}"));
             match key {
                 "crate" => krate = Some(value.to_string()),
                 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
@@ -216,7 +215,7 @@ fn parse_meta_line(meta: &str) -> Fixture {
                 }
                 "new_source_root" => introduce_new_source_root = Some(value.to_string()),
                 "target_data_layout" => target_data_layout = Some(value.to_string()),
-                _ => panic!("bad component: {:?}", component),
+                _ => panic!("bad component: {component:?}"),
             }
         }
 
@@ -253,7 +252,7 @@ fn has_flag(&self, flag: &str) -> bool {
     #[track_caller]
     fn assert_valid_flag(&self, flag: &str) {
         if !self.valid_flags.iter().any(|it| it == flag) {
-            panic!("invalid flag: {:?}, valid flags: {:?}", flag, self.valid_flags);
+            panic!("invalid flag: {flag:?}, valid flags: {:?}", self.valid_flags);
         }
     }
 
@@ -263,7 +262,7 @@ fn parse(line: &str) -> MiniCore {
         let line = line.strip_prefix("//- minicore:").unwrap().trim();
         for entry in line.split(", ") {
             if res.has_flag(entry) {
-                panic!("duplicate minicore flag: {:?}", entry);
+                panic!("duplicate minicore flag: {entry:?}");
             }
             res.activated_flags.push(entry.to_owned());
         }
@@ -369,7 +368,7 @@ pub fn source_code(mut self) -> String {
 
         for flag in &self.valid_flags {
             if !seen_regions.iter().any(|it| it == flag) {
-                panic!("unused minicore flag: {:?}", flag);
+                panic!("unused minicore flag: {flag:?}");
             }
         }
         buf
index 8a9cfb6c22e45e5dd8af957ea16a4bb1245c64aa..74468ea750d93f8d55885b91e6282853e9082ecf 100644 (file)
@@ -146,8 +146,8 @@ pub fn extract_range_or_offset(text: &str) -> (RangeOrOffset, String) {
 
 /// Extracts ranges, marked with `<tag> </tag>` pairs from the `text`
 pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option<String>)>, String) {
-    let open = format!("<{}", tag);
-    let close = format!("</{}>", tag);
+    let open = format!("<{tag}");
+    let close = format!("</{tag}>");
     let mut ranges = Vec::new();
     let mut res = String::new();
     let mut stack = Vec::new();
@@ -169,8 +169,7 @@ pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option<String
                     stack.push((from, attr));
                 } else if text.starts_with(&close) {
                     text = &text[close.len()..];
-                    let (from, attr) =
-                        stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag));
+                    let (from, attr) = stack.pop().unwrap_or_else(|| panic!("unmatched </{tag}>"));
                     let to = TextSize::of(&res);
                     ranges.push((TextRange::new(from, to), attr));
                 } else {
@@ -180,7 +179,7 @@ pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option<String
             }
         }
     }
-    assert!(stack.is_empty(), "unmatched <{}>", tag);
+    assert!(stack.is_empty(), "unmatched <{tag}>");
     ranges.sort_by_key(|r| (r.0.start(), r.0.end()));
     (ranges, res)
 }
@@ -413,8 +412,8 @@ pub fn format_diff(chunks: Vec<dissimilar::Chunk<'_>>) -> String {
     for chunk in chunks {
         let formatted = match chunk {
             dissimilar::Chunk::Equal(text) => text.into(),
-            dissimilar::Chunk::Delete(text) => format!("\x1b[41m{}\x1b[0m", text),
-            dissimilar::Chunk::Insert(text) => format!("\x1b[42m{}\x1b[0m", text),
+            dissimilar::Chunk::Delete(text) => format!("\x1b[41m{text}\x1b[0m"),
+            dissimilar::Chunk::Insert(text) => format!("\x1b[42m{text}\x1b[0m"),
         };
         buf.push_str(&formatted);
     }
index 85daec262c424646618b4e69d31a3730ccfa802c..353b09fd8c1edcd1261e61be5c792be2a21785ce 100644 (file)
@@ -115,15 +115,15 @@ fn print_debug_subtree(f: &mut fmt::Formatter<'_>, subtree: &Subtree, level: usi
 
     let aux = match subtree.delimiter.map(|it| (it.kind, it.id.0)) {
         None => "$".to_string(),
-        Some((DelimiterKind::Parenthesis, id)) => format!("() {}", id),
-        Some((DelimiterKind::Brace, id)) => format!("{{}} {}", id),
-        Some((DelimiterKind::Bracket, id)) => format!("[] {}", id),
+        Some((DelimiterKind::Parenthesis, id)) => format!("() {id}"),
+        Some((DelimiterKind::Brace, id)) => format!("{{}} {id}"),
+        Some((DelimiterKind::Bracket, id)) => format!("[] {id}"),
     };
 
     if subtree.token_trees.is_empty() {
-        write!(f, "{}SUBTREE {}", align, aux)?;
+        write!(f, "{align}SUBTREE {aux}")?;
     } else {
-        writeln!(f, "{}SUBTREE {}", align, aux)?;
+        writeln!(f, "{align}SUBTREE {aux}")?;
         for (idx, child) in subtree.token_trees.iter().enumerate() {
             print_debug_token(f, child, level + 1)?;
             if idx != subtree.token_trees.len() - 1 {
@@ -140,7 +140,7 @@ fn print_debug_token(f: &mut fmt::Formatter<'_>, tkn: &TokenTree, level: usize)
 
     match tkn {
         TokenTree::Leaf(leaf) => match leaf {
-            Leaf::Literal(lit) => write!(f, "{}LITERAL {} {}", align, lit.text, lit.id.0)?,
+            Leaf::Literal(lit) => write!(f, "{align}LITERAL {} {}", lit.text, lit.id.0)?,
             Leaf::Punct(punct) => write!(
                 f,
                 "{}PUNCH   {} [{}] {}",
@@ -149,7 +149,7 @@ fn print_debug_token(f: &mut fmt::Formatter<'_>, tkn: &TokenTree, level: usize)
                 if punct.spacing == Spacing::Alone { "alone" } else { "joint" },
                 punct.id.0
             )?,
-            Leaf::Ident(ident) => write!(f, "{}IDENT   {} {}", align, ident.text, ident.id.0)?,
+            Leaf::Ident(ident) => write!(f, "{align}IDENT   {} {}", ident.text, ident.id.0)?,
         },
         TokenTree::Subtree(subtree) => {
             print_debug_subtree(f, subtree, level)?;
@@ -312,7 +312,7 @@ fn tokentree_to_text(tkn: &TokenTree) -> String {
                     Some(DelimiterKind::Parenthesis) => ("(", ")"),
                     Some(DelimiterKind::Bracket) => ("[", "]"),
                 };
-                format!("{}{}{}", open, content, close)
+                format!("{open}{content}{close}")
             }
         }
     }
index 668c7320d4ec25baec8285753acde5dac6a2b92c..b23c9f1966d5c5effcda627c04fe6e4bd1770f6d 100644 (file)
@@ -364,7 +364,7 @@ fn join(&self, mut path: &str) -> Option<VirtualPath> {
             path = &path["../".len()..];
         }
         path = path.trim_start_matches("./");
-        res.0 = format!("{}/{}", res.0, path);
+        res.0 = format!("{}/{path}", res.0);
         Some(res)
     }
 
index ca7ad0b53673933ed0be41d9855812276ce2ef56..2f270afbbf1996c85cfb9c9f3b1c67c00439a265 100644 (file)
@@ -80,32 +80,32 @@ fn main_loop(
     let _params: InitializeParams = serde_json::from_value(params).unwrap();
     eprintln!("starting example main loop");
     for msg in &connection.receiver {
-        eprintln!("got msg: {:?}", msg);
+        eprintln!("got msg: {msg:?}");
         match msg {
             Message::Request(req) => {
                 if connection.handle_shutdown(&req)? {
                     return Ok(());
                 }
-                eprintln!("got request: {:?}", req);
+                eprintln!("got request: {req:?}");
                 match cast::<GotoDefinition>(req) {
                     Ok((id, params)) => {
-                        eprintln!("got gotoDefinition request #{}: {:?}", id, params);
+                        eprintln!("got gotoDefinition request #{id}: {params:?}");
                         let result = Some(GotoDefinitionResponse::Array(Vec::new()));
                         let result = serde_json::to_value(&result).unwrap();
                         let resp = Response { id, result: Some(result), error: None };
                         connection.sender.send(Message::Response(resp))?;
                         continue;
                     }
-                    Err(err @ ExtractError::JsonError { .. }) => panic!("{:?}", err),
+                    Err(err @ ExtractError::JsonError { .. }) => panic!("{err:?}"),
                     Err(ExtractError::MethodMismatch(req)) => req,
                 };
                 // ...
             }
             Message::Response(resp) => {
-                eprintln!("got response: {:?}", resp);
+                eprintln!("got response: {resp:?}");
             }
             Message::Notification(not) => {
-                eprintln!("got notification: {:?}", not);
+                eprintln!("got notification: {not:?}");
             }
         }
     }
index d567077d4a4ba3659d7020563bb535308fbc2074..8c3c81feabc1e4482b226417ac5e181bc74b4728 100644 (file)
@@ -123,7 +123,7 @@ pub fn initialize_start(&self) -> Result<(RequestId, serde_json::Value), Protoco
                     let resp = Response::new_err(
                         req.id.clone(),
                         ErrorCode::ServerNotInitialized as i32,
-                        format!("expected initialize request, got {:?}", req),
+                        format!("expected initialize request, got {req:?}"),
                     );
                     self.sender.send(resp.into()).unwrap();
                 }
@@ -221,11 +221,9 @@ pub fn handle_shutdown(&self, req: &Request) -> Result<bool, ProtocolError> {
         match &self.receiver.recv_timeout(std::time::Duration::from_secs(30)) {
             Ok(Message::Notification(n)) if n.is_exit() => (),
             Ok(msg) => {
-                return Err(ProtocolError(format!("unexpected message during shutdown: {:?}", msg)))
-            }
-            Err(e) => {
-                return Err(ProtocolError(format!("unexpected error during shutdown: {}", e)))
+                return Err(ProtocolError(format!("unexpected message during shutdown: {msg:?}")))
             }
+            Err(e) => return Err(ProtocolError(format!("unexpected error during shutdown: {e}"))),
         }
         Ok(true)
     }
index 686aec4ae507420a69b992049bab9f5268cf7174..410276bc45beffc962729741609ff1a37392e2e1 100644 (file)
@@ -26,10 +26,10 @@ pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
 
         if let Some(patch_version) = self.client_patch_version {
             let version = if stable {
-                format!("{}.{}", VERSION_STABLE, patch_version)
+                format!("{VERSION_STABLE}.{patch_version}")
             } else {
                 // A hack to make VS Code prefer nightly over stable.
-                format!("{}.{}", VERSION_NIGHTLY, patch_version)
+                format!("{VERSION_NIGHTLY}.{patch_version}")
             };
             dist_server(sh, &format!("{version}-standalone"), &target)?;
             let release_tag = if stable { date_iso(sh)? } else { "nightly".to_string() };
@@ -59,10 +59,10 @@ fn dist_client(
     let mut patch = Patch::new(sh, "./package.json")?;
     patch
         .replace(
-            &format!(r#""version": "{}.0-dev""#, VERSION_DEV),
-            &format!(r#""version": "{}""#, version),
+            &format!(r#""version": "{VERSION_DEV}.0-dev""#),
+            &format!(r#""version": "{version}""#),
         )
-        .replace(r#""releaseTag": null"#, &format!(r#""releaseTag": "{}""#, release_tag))
+        .replace(r#""releaseTag": null"#, &format!(r#""releaseTag": "{release_tag}""#))
         .replace(r#""$generated-start": {},"#, "")
         .replace(",\n                \"$generated-end\": {}", "")
         .replace(r#""enabledApiProposals": [],"#, r#""#);
@@ -130,8 +130,8 @@ fn get(project_root: &Path) -> Self {
         } else {
             (String::new(), None)
         };
-        let server_path = out_path.join(format!("rust-analyzer{}", exe_suffix));
-        let artifact_name = format!("rust-analyzer-{}{}", name, exe_suffix);
+        let server_path = out_path.join(format!("rust-analyzer{exe_suffix}"));
+        let artifact_name = format!("rust-analyzer-{name}{exe_suffix}");
         Self { name, server_path, symbols_path, artifact_name }
     }
 }
index ebeb873463ea18aeed509abc877ee1081f00e17c..b6f730dbf126276d1dda377b663ef5a34bb6e016 100644 (file)
@@ -87,7 +87,7 @@ fn measure_analysis_stats(&mut self, sh: &Shell, bench: &str) -> anyhow::Result<
         self.measure_analysis_stats_path(
             sh,
             bench,
-            &format!("./target/rustc-perf/collector/benchmarks/{}", bench),
+            &format!("./target/rustc-perf/collector/benchmarks/{bench}"),
         )
     }
     fn measure_analysis_stats_path(
index eda8fceef05ba2aa78da842a18f53be5987037bf..bfbe95569641360285a66b193a89ee04eb27e226 100644 (file)
@@ -64,7 +64,7 @@ pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
         let prev_tag = tags.lines().filter(|line| is_release_tag(line)).last().unwrap();
 
         let contents = changelog::get_changelog(sh, changelog_n, &commit, prev_tag, &today)?;
-        let path = changelog_dir.join(format!("{}-changelog-{}.adoc", today, changelog_n));
+        let path = changelog_dir.join(format!("{today}-changelog-{changelog_n}.adoc"));
         sh.write_file(&path, &contents)?;
 
         Ok(())
index 7df8f89dbe22a441176467180acf800dbc69c422..4a06bb9ac081d4b0769a3032f3e9cb024e54f06c 100644 (file)
@@ -25,7 +25,7 @@ pub(crate) fn get_changelog(
         let line = line.trim_start();
         if let Some(pr_num) = parse_pr_number(&line) {
             let accept = "Accept: application/vnd.github.v3+json";
-            let authorization = format!("Authorization: token {}", token);
+            let authorization = format!("Authorization: token {token}");
             let pr_url = "https://api.github.com/repos/rust-lang/rust-analyzer/issues";
 
             // we don't use an HTTPS client or JSON parser to keep the build times low
@@ -57,7 +57,7 @@ pub(crate) fn get_changelog(
                 PrKind::Other => &mut others,
                 PrKind::Skip => continue,
             };
-            writeln!(s, "* pr:{}[] {}", pr_num, l.message.as_deref().unwrap_or(&pr_title)).unwrap();
+            writeln!(s, "* pr:{pr_num}[] {}", l.message.as_deref().unwrap_or(&pr_title)).unwrap();
         }
     }