Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions crates/ide-assists/src/handlers/generate_constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub(crate) fn generate_constant(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
target_data_for_generate_constant(ctx, current_module, constant_module).unwrap_or_else(
|| {
let indent = IndentLevel::from_node(statement.syntax());
(statement.syntax().text_range().start(), indent, None, format!("\n{}", indent))
(statement.syntax().text_range().start(), indent, None, format!("\n{indent}"))
},
);

Expand All @@ -90,7 +90,7 @@ pub(crate) fn generate_constant(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
if let Some(file_id) = file_id {
builder.edit_file(file_id);
}
builder.insert(offset, format!("{}{}", text, post_string));
builder.insert(offset, format!("{text}{post_string}"));
},
)
}
Expand All @@ -103,13 +103,13 @@ fn get_text_for_generate_constant(
) -> Option<String> {
let constant_token = not_exist_name_ref.pop()?;
let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " };
let mut text = format!("{}const {}: {} = $0;", vis, constant_token, type_name);
let mut text = format!("{vis}const {constant_token}: {type_name} = $0;");
while let Some(name_ref) = not_exist_name_ref.pop() {
let vis = if not_exist_name_ref.len() == 0 && !outer_exists { "" } else { "\npub " };
text = text.replace("\n", "\n ");
text = format!("{}mod {} {{{}\n}}", vis, name_ref.to_string(), text);
text = format!("{vis}mod {name_ref} {{{text}\n}}");
}
Some(text.replace("\n", &format!("\n{}", indent)))
Some(text.replace("\n", &format!("\n{indent}")))
}

fn target_data_for_generate_constant(
Expand All @@ -134,7 +134,7 @@ fn target_data_for_generate_constant(
.find(|it| it.kind() == SyntaxKind::WHITESPACE && it.to_string().contains("\n"))
.is_some();
let post_string =
if siblings_has_newline { format!("{}", indent) } else { format!("\n{}", indent) };
if siblings_has_newline { format!("{indent}") } else { format!("\n{indent}") };
Some((offset, indent + 1, Some(file_id), post_string))
}
_ => Some((TextSize::from(0), 0.into(), Some(file_id), "\n".into())),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ pub(crate) fn generate_default_from_enum_variant(
let buf = format!(
r#"

impl Default for {0} {{
impl Default for {enum_name} {{
fn default() -> Self {{
Self::{1}
Self::{variant_name}
}}
}}"#,
enum_name, variant_name
);
edit.insert(start_offset, buf);
},
Expand Down
61 changes: 31 additions & 30 deletions crates/ide-assists/src/handlers/generate_default_from_new.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use ide_db::famous_defs::FamousDefs;
use itertools::Itertools;
use stdx::format_to;
use syntax::{
ast::{self, HasGenericParams, HasName, HasTypeBounds, Impl},
ast::{self, make, HasGenericParams, HasName, Impl},
AstNode,
};

Expand Down Expand Up @@ -77,45 +76,47 @@ pub(crate) fn generate_default_from_new(acc: &mut Assists, ctx: &AssistContext<'
)
}

// FIXME: based on from utils::generate_impl_text_inner
fn generate_trait_impl_text_from_impl(impl_: &ast::Impl, trait_text: &str, code: &str) -> String {
let generic_params = impl_.generic_param_list();
let mut buf = String::with_capacity(code.len());
buf.push_str("\n\n");
buf.push_str("impl");

if let Some(generic_params) = &generic_params {
let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax()));
let toc_params = generic_params.type_or_const_params().map(|toc_param| match toc_param {
ast::TypeOrConstParam::Type(type_param) => {
let mut buf = String::new();
if let Some(it) = type_param.name() {
format_to!(buf, "{}", it.syntax());
}
if let Some(it) = type_param.colon_token() {
format_to!(buf, "{} ", it);
let impl_ty = impl_.self_ty().unwrap();
let generic_params = impl_.generic_param_list().map(|generic_params| {
let lifetime_params =
generic_params.lifetime_params().map(ast::GenericParam::LifetimeParam);
let ty_or_const_params = generic_params.type_or_const_params().filter_map(|param| {
// remove defaults since they can't be specified in impls
match param {
ast::TypeOrConstParam::Type(param) => {
let param = param.clone_for_update();
param.remove_default();
Some(ast::GenericParam::TypeParam(param))
}
if let Some(it) = type_param.type_bound_list() {
format_to!(buf, "{}", it.syntax());
ast::TypeOrConstParam::Const(param) => {
let param = param.clone_for_update();
param.remove_default();
Some(ast::GenericParam::ConstParam(param))
}
buf
}
ast::TypeOrConstParam::Const(const_param) => const_param.syntax().to_string(),
});
let generics = lifetimes.chain(toc_params).format(", ");
format_to!(buf, "<{}>", generics);
}

buf.push(' ');
buf.push_str(trait_text);
buf.push_str(" for ");
buf.push_str(&impl_.self_ty().unwrap().syntax().text().to_string());
make::generic_param_list(itertools::chain(lifetime_params, ty_or_const_params))
});

let mut buf = String::with_capacity(code.len());
buf.push_str("\n\n");

// `impl{generic_params} {trait_text} for {impl_.self_ty()}`
buf.push_str("impl");
if let Some(generic_params) = &generic_params {
format_to!(buf, "{generic_params}")
}
format_to!(buf, " {trait_text} for {impl_ty}");

match impl_.where_clause() {
Some(where_clause) => {
format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
format_to!(buf, "\n{where_clause}\n{{\n{code}\n}}");
}
None => {
format_to!(buf, " {{\n{}\n}}", code);
format_to!(buf, " {{\n{code}\n}}");
}
}

Expand Down
12 changes: 7 additions & 5 deletions crates/ide-assists/src/handlers/generate_delegate_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
Some(field) => {
let field_name = field.name()?;
let field_ty = field.ty()?;
(format!("{}", field_name), field_ty, field.syntax().text_range())
(format!("{field_name}"), field_ty, field.syntax().text_range())
}
None => {
let field = ctx.find_node_at_offset::<ast::TupleField>()?;
let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
let field_list_index = field_list.fields().position(|it| it == field)?;
let field_ty = field.ty()?;
(format!("{}", field_list_index), field_ty, field.syntax().text_range())
(format!("{field_list_index}"), field_ty, field.syntax().text_range())
}
};

Expand All @@ -78,10 +78,12 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
let adt = ast::Adt::Struct(strukt.clone());
let name = method.name(ctx.db()).to_string();
let impl_def = find_struct_impl(ctx, &adt, &name).flatten();
let method_name = method.name(ctx.db());

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}()`"),
target,
|builder| {
// Create the function
Expand Down Expand Up @@ -151,12 +153,12 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
Some(cap) => {
let offset = strukt.syntax().text_range().end();
let snippet = render_snippet(cap, impl_def.syntax(), cursor);
let snippet = format!("\n\n{}", snippet);
let snippet = format!("\n\n{snippet}");
builder.insert_snippet(cap, offset, snippet);
}
None => {
let offset = strukt.syntax().text_range().end();
let snippet = format!("\n\n{}", impl_def.syntax());
let snippet = format!("\n\n{impl_def}");
builder.insert(offset, snippet);
}
}
Expand Down
12 changes: 5 additions & 7 deletions crates/ide-assists/src/handlers/generate_deref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
let target = field.syntax().text_range();
acc.add(
AssistId("generate_deref", AssistKind::Generate),
format!("Generate `{:?}` impl using `{}`", deref_type_to_generate, field_name),
format!("Generate `{deref_type_to_generate:?}` impl using `{field_name}`"),
target,
|edit| {
generate_edit(
Expand Down Expand Up @@ -106,7 +106,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
let target = field.syntax().text_range();
acc.add(
AssistId("generate_deref", AssistKind::Generate),
format!("Generate `{:?}` impl using `{}`", deref_type_to_generate, field.syntax()),
format!("Generate `{deref_type_to_generate:?}` impl using `{field}`"),
target,
|edit| {
generate_edit(
Expand All @@ -132,18 +132,16 @@ fn generate_edit(
let start_offset = strukt.syntax().text_range().end();
let impl_code = match deref_type {
DerefType::Deref => format!(
r#" type Target = {0};
r#" type Target = {field_type_syntax};

fn deref(&self) -> &Self::Target {{
&self.{1}
&self.{field_name}
}}"#,
field_type_syntax, field_name
),
DerefType::DerefMut => format!(
r#" fn deref_mut(&mut self) -> &mut Self::Target {{
&mut self.{}
&mut self.{field_name}
}}"#,
field_name
),
};
let strukt_adt = ast::Adt::Struct(strukt);
Expand Down
52 changes: 31 additions & 21 deletions crates/ide-assists/src/handlers/generate_documentation_template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,40 +139,44 @@ fn make_example_for_fn(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<St

let mut example = String::new();

let use_path = build_path(ast_func, ctx)?;
let is_unsafe = ast_func.unsafe_token().is_some();
let param_list = ast_func.param_list()?;
let ref_mut_params = ref_mut_params(&param_list);
let self_name = self_name(ast_func);

format_to!(example, "use {};\n\n", build_path(ast_func, ctx)?);
format_to!(example, "use {use_path};\n\n");
if let Some(self_name) = &self_name {
if let Some(mtbl) = is_ref_mut_self(ast_func) {
let mtbl = if mtbl == true { " mut" } else { "" };
format_to!(example, "let{} {} = ;\n", mtbl, self_name);
if let Some(mut_) = is_ref_mut_self(ast_func) {
let mut_ = if mut_ == true { "mut " } else { "" };
format_to!(example, "let {mut_}{self_name} = ;\n");
}
}
for param_name in &ref_mut_params {
format_to!(example, "let mut {} = ;\n", param_name);
format_to!(example, "let mut {param_name} = ;\n");
}
// Call the function, check result
let function_call = function_call(ast_func, &param_list, self_name.as_deref(), is_unsafe)?;
if returns_a_value(ast_func, ctx) {
if count_parameters(&param_list) < 3 {
format_to!(example, "assert_eq!({}, );\n", function_call);
format_to!(example, "assert_eq!({function_call}, );\n");
} else {
format_to!(example, "let result = {};\n", function_call);
format_to!(example, "let result = {function_call};\n");
example.push_str("assert_eq!(result, );\n");
}
} else {
format_to!(example, "{};\n", function_call);
format_to!(example, "{function_call};\n");
}
// Check the mutated values
if is_ref_mut_self(ast_func) == Some(true) {
format_to!(example, "assert_eq!({}, );", self_name?);
if let Some(self_name) = &self_name {
if is_ref_mut_self(ast_func) == Some(true) {
format_to!(example, "assert_eq!({self_name}, );");
}
}
for param_name in &ref_mut_params {
format_to!(example, "assert_eq!({}, );", param_name);
format_to!(example, "assert_eq!({param_name}, );");
}

Some(example)
}

Expand All @@ -189,7 +193,8 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
let intro_for_new = || {
let is_new = name == "new";
if is_new && ret_ty == self_ty {
Some(format!("Creates a new [`{}`].", linkable_self_ty?))
let self_ty = linkable_self_ty?;
Some(format!("Creates a new [`{self_ty}`]."))
} else {
None
}
Expand All @@ -214,7 +219,9 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
} else {
""
};
Some(format!("Returns{reference} the {what} of this [`{}`].", linkable_self_ty?))

let self_ty = linkable_self_ty?;
Some(format!("Returns{reference} the {what} of this [`{self_ty}`]."))
}
_ => None,
};
Expand All @@ -228,7 +235,9 @@ fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<S
if what == "len" {
what = "length".into()
};
Some(format!("Sets the {what} of this [`{}`].", linkable_self_ty?))

let self_ty = linkable_self_ty?;
Some(format!("Sets the {what} of this [`{self_ty}`]."))
};

if let Some(intro) = intro_for_new() {
Expand Down Expand Up @@ -404,7 +413,7 @@ fn arguments_from_params(param_list: &ast::ParamList) -> String {
// instance `TuplePat`) could be managed later.
Some(ast::Pat::IdentPat(ident_pat)) => match ident_pat.name() {
Some(name) => match is_a_ref_mut_param(&param) {
true => format!("&mut {}", name),
true => format!("&mut {name}"),
false => name.to_string(),
},
None => "_".to_string(),
Expand All @@ -424,14 +433,15 @@ fn function_call(
let name = ast_func.name()?;
let arguments = arguments_from_params(param_list);
let function_call = if param_list.self_param().is_some() {
format!("{}.{}({})", self_name?, name, arguments)
let self_ = self_name?;
format!("{self_}.{name}({arguments})")
} else if let Some(implementation) = self_partial_type(ast_func) {
format!("{}::{}({})", implementation, name, arguments)
format!("{implementation}::{name}({arguments})")
} else {
format!("{}({})", name, arguments)
format!("{name}({arguments})")
};
match is_unsafe {
true => Some(format!("unsafe {{ {} }}", function_call)),
true => Some(format!("unsafe {{ {function_call} }}")),
false => Some(function_call),
}
}
Expand Down Expand Up @@ -469,8 +479,8 @@ fn build_path(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option<String> {
.unwrap_or_else(|| "*".into());
let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into();
match module_def.canonical_path(ctx.db()) {
Some(path) => Some(format!("{}::{}::{}", crate_name, path, leaf)),
None => Some(format!("{}::{}", crate_name, leaf)),
Some(path) => Some(format!("{crate_name}::{path}::{leaf}")),
None => Some(format!("{crate_name}::{leaf}")),
}
}

Expand Down
16 changes: 5 additions & 11 deletions crates/ide-assists/src/handlers/generate_enum_is_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,15 @@ pub(crate) fn generate_enum_is_method(acc: &mut Assists, ctx: &AssistContext<'_>
"Generate an `is_` method for this enum variant",
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 method = format!(
" /// Returns `true` if the {} is [`{variant}`].
" /// Returns `true` if the {enum_lowercase_name} is [`{variant_name}`].
///
/// [`{variant}`]: {}::{variant}
/// [`{variant_name}`]: {enum_name}::{variant_name}
#[must_use]
{}fn {}(&self) -> bool {{
matches!(self, Self::{variant}{})
{vis}fn {fn_name}(&self) -> bool {{
matches!(self, Self::{variant_name}{pattern_suffix})
}}",
enum_lowercase_name,
enum_name,
vis,
fn_name,
pattern_suffix,
variant = variant_name
);

add_method_to_adt(builder, &parent_enum, impl_def, &method);
Expand Down
Loading