Inline all format arguments where possible

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
```
This commit is contained in:
Yuri Astrakhan 2022-12-23 13:42:58 -05:00
parent 1927c2e1d8
commit e16c76e3c3
180 changed files with 487 additions and 501 deletions

View 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 @@ impl From<Fixture> for 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,
}

View file

@ -618,8 +618,8 @@ impl CyclicDependenciesError {
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!(

View 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)
}

View 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:?}"),
}
}
}

View file

@ -37,7 +37,7 @@ impl fmt::Debug for CfgOptions {
.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 @@ impl fmt::Display for InactiveReason {
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 @@ impl fmt::Display for InactiveReason {
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(())

View 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 @@ impl CargoActor {
);
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}"))),
}
}
}

View file

@ -712,7 +712,7 @@ impl AttrSourceMap {
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:?}"))
}
}

View 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}")
}
};

View 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 @@ mod tests {
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(

View file

@ -243,7 +243,7 @@ impl fmt::Debug for ImportMap {
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 @@ mod tests {
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 @@ mod tests {
let map = db.import_map(krate);
Some(format!("{}:\n{:?}\n", name, map))
Some(format!("{name}:\n{map:?}\n"))
})
.sorted()
.collect::<String>();

View 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 @@ impl ItemTree {
ctx.lower_macro_stmts(stmts)
},
_ => {
panic!("cannot create item tree from {:?} {}", syntax, syntax);
panic!("cannot create item tree from {syntax:?} {syntax}");
},
}
};

View 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)
}

View file

@ -461,7 +461,7 @@ impl DefMap {
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);
}

View file

@ -1017,7 +1017,7 @@ impl DefCollector<'_> {
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 {

View file

@ -74,12 +74,12 @@ impl ModDir {
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 @@ impl ModDir {
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 @@ impl DirPath {
} else {
attr
};
let res = format!("{}{}", base, attr);
let res = format!("{base}{attr}");
res
}
}

View file

@ -170,8 +170,8 @@ impl DefMap {
) -> 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();

View 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 typing_inside_a_macro_should_not_invalidate_def_map() {
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 typing_inside_a_macro_should_not_invalidate_def_map() {
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:#?}")
}
}

View 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, "[")?;

View 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(),
))
}
};

View 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:?}");
}
}

View file

@ -366,7 +366,7 @@ mod tests {
fixups.append,
);
let actual = format!("{}\n", tt);
let actual = format!("{tt}\n");
expect.indent(false);
expect.assert_eq(&actual);

View file

@ -233,7 +233,7 @@ mod tests {
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");
}

View file

@ -142,7 +142,7 @@ impl<D> TyBuilder<D> {
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),
}
}
}

View file

@ -90,14 +90,14 @@ impl Display for ComputedExpr {
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)
}

View 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 @@ fn enums() {
assert_eq!(name, "E::A");
assert_eq!(val, 1);
}
x => panic!("Expected enum but found {:?}", x),
x => panic!("Expected enum but found {x:?}"),
}
}

View file

@ -386,7 +386,7 @@ impl HirDisplay for Pat {
}
subpattern.hir_fmt(f)
}
PatKind::LiteralBool { value } => write!(f, "{}", value),
PatKind::LiteralBool { value } => write!(f, "{value}"),
PatKind::Or { pats } => f.write_joined(pats.iter(), " | "),
}
}

View file

@ -372,7 +372,7 @@ impl Constructor {
hir_def::AdtId::UnionId(id) => id.into(),
}
}
_ => panic!("bad constructor {:?} for adt {:?}", self, adt),
_ => panic!("bad constructor {self:?} for adt {adt:?}"),
}
}

View file

@ -176,13 +176,13 @@ impl<'a> HirFormatter<'a> {
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 @@ impl<T: HirDisplay + Internable> HirDisplay for Interned<T> {
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 @@ impl HirDisplay for ProjectionTy {
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 @@ impl HirDisplay for BoundVar {
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 @@ impl HirDisplay for Ty {
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 @@ impl HirDisplay for Ty {
module_id,
false,
) {
write!(f, "{}", path)?;
write!(f, "{path}")?;
} else {
return Err(HirDisplayError::DisplaySourceCodeError(
DisplaySourceCodeError::PathNotFound,
@ -737,7 +737,7 @@ impl HirDisplay for Ty {
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 @@ impl HirDisplay for TraitRef {
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 @@ impl HirDisplay for TypeRef {
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 @@ impl HirDisplay for TypeRef {
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 @@ impl HirDisplay for TypeRef {
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),
}
}

View file

@ -143,7 +143,7 @@ impl chalk_ir::interner::Interner for Interner {
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(

View file

@ -513,7 +513,7 @@ where
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(

View 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");
}
}
}

View file

@ -24,7 +24,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
db.infer(def);
});
});
assert!(format!("{:?}", events).contains("infer"))
assert!(format!("{events:?}").contains("infer"))
}
let new_text = "
@ -46,6 +46,6 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
db.infer(def);
});
});
assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
assert!(!format!("{events:?}").contains("infer"), "{events:#?}")
}
}

View 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");

View file

@ -67,12 +67,12 @@ impl DebugContext<'_> {
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 @@ impl DebugContext<'_> {
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 @@ impl DebugContext<'_> {
}
};
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}}}")
}
}
}

View 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
};

View 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)?;

View file

@ -79,7 +79,7 @@ impl HirDisplay for Function {
}
}
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 @@ impl HirDisplay for Const {
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}"),

View 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))),

View file

@ -1378,7 +1378,7 @@ impl<'db> SemanticsImpl<'db> {
self.cache
.borrow()
.keys()
.map(|it| format!("{:?}", it))
.map(|it| format!("{it:?}"))
.collect::<Vec<_>>()
.join(", ")
)

View 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

View 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();

View 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),

View 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);

View file

@ -18,7 +18,7 @@ use super::check_doc_test;
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 @@ impl fmt::Display for Assist {
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()
}

View file

@ -133,7 +133,7 @@ impl Completions {
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);
}

View file

@ -11,7 +11,7 @@ use crate::{completions::Completions, context::CompletionContext, CompletionItem
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);

View 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);

View file

@ -112,7 +112,7 @@ mod tests {
"#;
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 @@ mod tests {
"#;
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 @@ mod tests {
"#;
let completions = completion_list(fixture);
assert!(completions.is_empty(), "Completions weren't empty: {}", completions)
assert!(completions.is_empty(), "Completions weren't empty: {completions}")
}
}

View 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()))
}

View 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)),
};

View 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);
}

View 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 @@ mod tests {
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);
}
}

View 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);
}

View 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]

View file

@ -453,10 +453,10 @@ impl Builder {
// 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 {

View 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 @@ mod tests {
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 @@ mod tests {
.filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
.join("+");
format!("[{}]", relevance_factors)
format!("[{relevance_factors}]")
}
}

View 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, "(…)")

View 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);
}

View 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})"),
}
}

View 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)?;

View file

@ -153,7 +153,7 @@ fn render_completion_list(completions: Vec<CompletionItem>) -> String {
.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();

View file

@ -4,7 +4,7 @@ use expect_test::{expect, Expect};
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)
}

View file

@ -7,7 +7,7 @@ use expect_test::{expect, Expect};
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)
}

View file

@ -4,7 +4,7 @@ use expect_test::{expect, Expect};
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)
}

View 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)
}

View file

@ -4,7 +4,7 @@ use expect_test::{expect, Expect};
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)
}

View file

@ -4,7 +4,7 @@ use expect_test::{expect, Expect};
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)
}

View file

@ -88,7 +88,7 @@ impl FromStr for AssistKind {
"RefactorExtract" => Ok(AssistKind::RefactorExtract),
"RefactorInline" => Ok(AssistKind::RefactorInline),
"RefactorRewrite" => Ok(AssistKind::RefactorRewrite),
unknown => Err(format!("Unknown AssistKind: '{}'", unknown)),
unknown => Err(format!("Unknown AssistKind: '{unknown}'")),
}
}
}

View 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)

View 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()

View 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;
}
_ => (),

View 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

View 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
};

View 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###"

View 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))
}

View 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(

View 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(())
}

View 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 make_fixes(
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 make_fixes(
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 make_fixes(
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 make_fixes(
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,
),

View 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()

View 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 {}",

View 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 };

View 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())
}),
);

View 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) {

View file

@ -39,7 +39,7 @@ impl Diagnostic {
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 };

View file

@ -352,7 +352,7 @@ impl NodeKind {
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()),
}

View 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());
}
}

View 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"),
},

View 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]

View 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() };

View file

@ -187,7 +187,7 @@ mod tests {
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]

View 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
})
})

View 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 @@ where
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 @@ where
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)
}

View 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)
}

View file

@ -468,7 +468,7 @@ mod tests {
.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]

View 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]

View file

@ -33,6 +33,6 @@ impl Markup {
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()
}
}

View 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:?}");
}
}

View file

@ -117,10 +117,10 @@ impl NavigationTarget {
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
}

View file

@ -345,7 +345,7 @@ mod tests {
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 @@ mod tests {
.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 @@ mod tests {
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),
};

View 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);

Some files were not shown because too many files have changed in this diff Show more