Skip to content

Commit

Permalink
Auto merge of #17315 - hamirmahal:style/simplify-string-interpolation…
Browse files Browse the repository at this point in the history
…, r=Veykril

style: simplify string interpolation
  • Loading branch information
bors committed Jun 3, 2024
2 parents 9edc30a + 7fa555f commit cb6b808
Show file tree
Hide file tree
Showing 43 changed files with 71 additions and 79 deletions.
7 changes: 3 additions & 4 deletions crates/flycheck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ impl FlycheckActor {
Some(c) => c,
None => continue,
};
let formatted_command = format!("{:?}", command);
let formatted_command = format!("{command:?}");

tracing::debug!(?command, "will restart flycheck");
let (sender, receiver) = unbounded();
Expand All @@ -318,8 +318,7 @@ impl FlycheckActor {
}
Err(error) => {
self.report_progress(Progress::DidFailToRestart(format!(
"Failed to run the following command: {} error={}",
formatted_command, error
"Failed to run the following command: {formatted_command} error={error}"
)));
self.status = FlycheckStatus::Finished;
}
Expand All @@ -331,7 +330,7 @@ impl FlycheckActor {
// Watcher finished
let command_handle = self.command_handle.take().unwrap();
self.command_receiver.take();
let formatted_handle = format!("{:?}", command_handle);
let formatted_handle = format!("{command_handle:?}");

let res = command_handle.join();
if let Err(error) = &res {
Expand Down
6 changes: 3 additions & 3 deletions crates/hir-ty/src/consteval/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,23 @@ fn check_answer(ra_fixture: &str, check: impl FnOnce(&[u8], &MemoryMap)) {
Ok(t) => t,
Err(e) => {
let err = pretty_print_err(e, db);
panic!("Error in evaluating goal: {}", err);
panic!("Error in evaluating goal: {err}");
}
};
match &r.data(Interner).value {
chalk_ir::ConstValue::Concrete(c) => match &c.interned {
ConstScalar::Bytes(b, mm) => {
check(b, mm);
}
x => panic!("Expected number but found {:?}", x),
x => panic!("Expected number but found {x:?}"),
},
_ => panic!("result of const eval wasn't a concrete const"),
}
}

fn pretty_print_err(e: ConstEvalError, db: TestDB) -> String {
let mut err = String::new();
let span_formatter = |file, range| format!("{:?} {:?}", file, range);
let span_formatter = |file, range| format!("{file:?} {range:?}");
match e {
ConstEvalError::MirLowerError(e) => e.pretty_print(&mut err, &db, span_formatter),
ConstEvalError::MirEvalError(e) => e.pretty_print(&mut err, &db, span_formatter),
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-ty/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,7 @@ fn render_const_scalar(
TyKind::FnDef(..) => ty.hir_fmt(f),
TyKind::Function(_) | TyKind::Raw(_, _) => {
let it = u128::from_le_bytes(pad16(b, false));
write!(f, "{:#X} as ", it)?;
write!(f, "{it:#X} as ")?;
ty.hir_fmt(f)
}
TyKind::Array(ty, len) => {
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-ty/src/mir/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ impl MirEvalError {
)?;
}
Either::Right(closure) => {
writeln!(f, "In {:?}", closure)?;
writeln!(f, "In {closure:?}")?;
}
}
let source_map = db.body_with_source_map(*def).1;
Expand Down Expand Up @@ -424,7 +424,7 @@ impl MirEvalError {
| MirEvalError::StackOverflow
| MirEvalError::CoerceUnsizedError(_)
| MirEvalError::InternalError(_)
| MirEvalError::InvalidVTableId(_) => writeln!(f, "{:?}", err)?,
| MirEvalError::InvalidVTableId(_) => writeln!(f, "{err:?}")?,
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-ty/src/mir/eval/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ fn check_panic(ra_fixture: &str, expected_panic: &str) {
let (db, file_ids) = TestDB::with_many_files(ra_fixture);
let file_id = *file_ids.last().unwrap();
let e = eval_main(&db, file_id).unwrap_err();
assert_eq!(e.is_panic().unwrap_or_else(|| panic!("unexpected error: {:?}", e)), expected_panic);
assert_eq!(e.is_panic().unwrap_or_else(|| panic!("unexpected error: {e:?}")), expected_panic);
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-ty/src/mir/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl MirLowerError {
| MirLowerError::LangItemNotFound(_)
| MirLowerError::MutatingRvalue
| MirLowerError::UnresolvedLabel
| MirLowerError::UnresolvedUpvar(_) => writeln!(f, "{:?}", self)?,
| MirLowerError::UnresolvedUpvar(_) => writeln!(f, "{self:?}")?,
}
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions crates/hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2422,9 +2422,9 @@ impl Const {
let value_signed =
i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_))));
if value >= 10 {
return Ok(format!("{} ({:#X})", value_signed, value));
return Ok(format!("{value_signed} ({value:#X})"));
} else {
return Ok(format!("{}", value_signed));
return Ok(format!("{value_signed}"));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/auto_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
acc.add_group(
&group_label,
assist_id,
format!("Import `{}`", import_name),
format!("Import `{import_name}`"),
range,
|builder| {
let scope = match scope.clone() {
Expand All @@ -165,7 +165,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
acc.add_group(
&group_label,
assist_id,
format!("Import `{} as _`", import_name),
format!("Import `{import_name} as _`"),
range,
|builder| {
let scope = match scope.clone() {
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/bool_to_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ fn replace_usages(

edit.replace(
prefix_expr.syntax().text_range(),
format!("{} == Bool::False", inner_expr),
format!("{inner_expr} == Bool::False"),
);
} else if let Some((record_field, initializer)) = name
.as_name_ref()
Expand Down Expand Up @@ -275,7 +275,7 @@ fn replace_usages(
} else if let Some(receiver) = find_method_call_expr_usage(&name) {
edit.replace(
receiver.syntax().text_range(),
format!("({} == Bool::True)", receiver),
format!("({receiver} == Bool::True)"),
);
} else if name.syntax().ancestors().find_map(ast::UseTree::cast).is_none() {
// for any other usage in an expression, replace it with a check that it is the true variant
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ fn generate_field_names(ctx: &AssistContext<'_>, data: &StructEditData) -> Vec<(
.iter()
.enumerate()
.map(|(index, _)| {
let new_name = new_field_name((format!("_{}", index)).into(), &data.names_in_scope);
let new_name = new_field_name((format!("_{index}")).into(), &data.names_in_scope);
(index.to_string().into(), new_name)
})
.collect(),
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/generate_delegate_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ fn ty_assoc_item(item: syntax::ast::TypeAlias, qual_path_ty: Path) -> Option<Ass
}

fn qualified_path(qual_path_ty: ast::Path, path_expr_seg: ast::Path) -> ast::Path {
make::path_from_text(&format!("{}::{}", qual_path_ty, path_expr_seg))
make::path_from_text(&format!("{qual_path_ty}::{path_expr_seg}"))
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub(crate) fn generate_setter(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opt
}

// Prepend set_ to fn names.
fn_names.iter_mut().for_each(|name| *name = format!("set_{}", name));
fn_names.iter_mut().for_each(|name| *name = format!("set_{name}"));

// Return early if we've found an existing fn
let impl_def = find_struct_impl(ctx, &ast::Adt::Struct(strukt.clone()), &fn_names)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/generate_mut_trait_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub(crate) fn generate_mut_trait_impl(acc: &mut Assists, ctx: &AssistContext<'_>
"Generate `IndexMut` impl from this `Index` trait",
target,
|edit| {
edit.insert(target.start(), format!("$0{}\n\n", impl_def));
edit.insert(target.start(), format!("$0{impl_def}\n\n"));
},
)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/into_to_qualified_from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ pub(crate) fn into_to_qualified_from(acc: &mut Assists, ctx: &AssistContext<'_>)
edit.replace(
method_call.syntax().text_range(),
if sc.chars().all(|c| c.is_alphanumeric() || c == ':') {
format!("{}::from({})", sc, receiver)
format!("{sc}::from({receiver})")
} else {
format!("<{}>::from({})", sc, receiver)
format!("<{sc}>::from({receiver})")
},
);
},
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/merge_nested_if.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub(crate) fn merge_nested_if(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opt
nested_if_cond.syntax().text().to_string()
};

let replace_cond = format!("{} && {}", cond_text, nested_if_cond_text);
let replace_cond = format!("{cond_text} && {nested_if_cond_text}");

edit.replace(cond_range, replace_cond);
edit.replace(then_branch_range, nested_if_then_branch.syntax().text());
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/remove_parentheses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub(crate) fn remove_parentheses(acc: &mut Assists, ctx: &AssistContext<'_>) ->
}
None => false,
};
let expr = if need_to_add_ws { format!(" {}", expr) } else { expr.to_string() };
let expr = if need_to_add_ws { format!(" {expr}") } else { expr.to_string() };

builder.replace(parens.syntax().text_range(), expr)
},
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-completion/src/completions/postfix/format_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub(crate) fn add_format_like_completions(
let exprs = with_placeholders(exprs);
for (label, macro_name) in KINDS {
let snippet = if exprs.is_empty() {
format!(r#"{}({})"#, macro_name, out)
format!(r#"{macro_name}({out})"#)
} else {
format!(r#"{}({}, {})"#, macro_name, out, exprs.join(", "))
};
Expand Down Expand Up @@ -108,7 +108,7 @@ mod tests {

for (kind, input, output) in test_vector {
let (parsed_string, _exprs) = parse_format_exprs(input).unwrap();
let snippet = format!(r#"{}("{}")"#, kind, parsed_string);
let snippet = format!(r#"{kind}("{parsed_string}")"#);
assert_eq!(&snippet, output);
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl State {
self.names.insert(name.clone(), 1);
1
};
make::name(&format!("{}{}", name, count))
make::name(&format!("{name}{count}"))
}

fn serde_derive(&self) -> String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub(crate) fn trait_impl_redundant_assoc_item(
hir::AssocItem::Function(id) => {
let function = id;
(
format!("`fn {}`", redundant_assoc_item_name),
format!("`fn {redundant_assoc_item_name}`"),
function
.source(db)
.map(|it| it.syntax().value.text_range())
Expand All @@ -38,7 +38,7 @@ pub(crate) fn trait_impl_redundant_assoc_item(
hir::AssocItem::Const(id) => {
let constant = id;
(
format!("`const {}`", redundant_assoc_item_name),
format!("`const {redundant_assoc_item_name}`"),
constant
.source(db)
.map(|it| it.syntax().value.text_range())
Expand All @@ -49,7 +49,7 @@ pub(crate) fn trait_impl_redundant_assoc_item(
hir::AssocItem::TypeAlias(id) => {
let type_alias = id;
(
format!("`type {}`", redundant_assoc_item_name),
format!("`type {redundant_assoc_item_name}`"),
type_alias
.source(db)
.map(|it| it.syntax().value.text_range())
Expand Down
8 changes: 3 additions & 5 deletions crates/ide-diagnostics/src/handlers/unresolved_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,11 @@ fn assoc_func_fix(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedMethodCall) -
// we could omit generic parameters cause compiler can deduce it automatically
if !need_to_take_receiver_as_first_arg && !generic_parameters.is_empty() {
let generic_parameters = generic_parameters.join(", ");
receiver_type_adt_name =
format!("{}::<{}>", receiver_type_adt_name, generic_parameters);
receiver_type_adt_name = format!("{receiver_type_adt_name}::<{generic_parameters}>");
}

let method_name = call.name_ref()?;
let assoc_func_call = format!("{}::{}()", receiver_type_adt_name, method_name);
let assoc_func_call = format!("{receiver_type_adt_name}::{method_name}()");

let assoc_func_call = make::expr_path(make::path_from_text(&assoc_func_call));

Expand All @@ -184,8 +183,7 @@ fn assoc_func_fix(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedMethodCall) -
Some(Assist {
id: AssistId("method_call_to_assoc_func_call_fix", AssistKind::QuickFix),
label: Label::new(format!(
"Use associated func call instead: `{}`",
assoc_func_call_expr_string
"Use associated func call instead: `{assoc_func_call_expr_string}`"
)),
group: None,
target: range,
Expand Down
2 changes: 1 addition & 1 deletion crates/ide/src/interpret_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn find_and_interpret(db: &RootDatabase, position: FilePosition) -> Option<Strin
let path = path.as_deref().unwrap_or("<unknown file>");
match db.line_index(file_id).try_line_col(text_range.start()) {
Some(line_col) => format!("file://{path}#{}:{}", line_col.line + 1, line_col.col),
None => format!("file://{path} range {:?}", text_range),
None => format!("file://{path} range {text_range:?}"),
}
};
Some(def.eval(db, span_formatter))
Expand Down
2 changes: 1 addition & 1 deletion crates/ide/src/view_memory_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl fmt::Display for RecursiveMemoryLayout {
"{}: {} (size: {}, align: {}, field offset: {})\n",
node.item_name, node.typename, node.size, node.alignment, node.offset
);
write!(fmt, "{}", out)?;
write!(fmt, "{out}")?;
if node.children_start != -1 {
for j in nodes[idx].children_start
..(nodes[idx].children_start + nodes[idx].children_len as i64)
Expand Down
2 changes: 1 addition & 1 deletion crates/parser/src/grammar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ fn delimited(
}
if !p.eat(delim) {
if p.at_ts(first_set) {
p.error(format!("expected {:?}", delim));
p.error(format!("expected {delim:?}"));
} else {
break;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/paths/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl AbsPathBuf {
/// Panics if `path` is not absolute.
pub fn assert(path: Utf8PathBuf) -> AbsPathBuf {
AbsPathBuf::try_from(path)
.unwrap_or_else(|path| panic!("expected absolute path, got {}", path))
.unwrap_or_else(|path| panic!("expected absolute path, got {path}"))
}

/// Wrap the given absolute path in `AbsPathBuf`
Expand Down
3 changes: 1 addition & 2 deletions crates/proc-macro-api/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ impl ProcMacroProcessSrv {
Ok(v) if v > CURRENT_API_VERSION => Err(io::Error::new(
io::ErrorKind::Other,
format!(
"proc-macro server's api version ({}) is newer than rust-analyzer's ({})",
v, CURRENT_API_VERSION
"proc-macro server's api version ({v}) is newer than rust-analyzer's ({CURRENT_API_VERSION})"
),
)),
Ok(v) => {
Expand Down
3 changes: 1 addition & 2 deletions crates/project-model/src/sysroot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ impl Sysroot {
", try running `rustup component add rust-src` to possibly fix this"
};
sysroot.error = Some(format!(
"sysroot at `{}` is missing a `core` library{var_note}",
src_root,
"sysroot at `{src_root}` is missing a `core` library{var_note}",
));
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/project-model/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ fn replace_fake_sys_root(s: &mut String) {
let fake_sysroot_path = get_test_path("fake-sysroot");
let fake_sysroot_path = if cfg!(windows) {
let normalized_path = fake_sysroot_path.as_str().replace('\\', r#"\\"#);
format!(r#"{}\\"#, normalized_path)
format!(r#"{normalized_path}\\"#)
} else {
format!("{}/", fake_sysroot_path.as_str())
};
Expand Down
2 changes: 1 addition & 1 deletion crates/rust-analyzer/src/cli/analysis_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ impl flags::AnalysisStats {
.or_insert(1);
} else {
acc.syntax_errors += 1;
bar.println(format!("Syntax error: \n{}", err));
bar.println(format!("Syntax error: \n{err}"));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/rust-analyzer/src/cli/run_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl flags::RunTests {
let mut sw_all = StopWatch::start();
for test in tests {
let full_name = full_name_of_item(db, test.module(db), test.name(db));
println!("test {}", full_name);
println!("test {full_name}");
if test.is_ignore(db) {
println!("ignored");
ignore_count += 1;
Expand All @@ -62,7 +62,7 @@ impl flags::RunTests {
} else {
fail_count += 1;
}
println!("{}", result);
println!("{result}");
eprintln!("{:<20} {}", format!("test {}", full_name), sw_one.elapsed());
}
println!("{pass_count} passed, {fail_count} failed, {ignore_count} ignored");
Expand Down
4 changes: 2 additions & 2 deletions crates/rust-analyzer/src/cli/rustc_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ impl Tester {
self.pass_count += 1;
} else {
println!("{p:?} FAIL");
println!("actual (r-a) = {:?}", actual);
println!("expected (rustc) = {:?}", expected);
println!("actual (r-a) = {actual:?}");
println!("expected (rustc) = {expected:?}");
self.fail_count += 1;
}
}
Expand Down
Loading

0 comments on commit cb6b808

Please sign in to comment.