use hir::{FileRange, Semantics};
use ide_db::text_edit::TextRange;
use ide_db::{
EditionedFileId, RootDatabase,
defs::Definition,
search::{SearchScope, UsageSearchResult},
};
use syntax::{
AstNode,
ast::{self, HasGenericParams, HasName, HasTypeBounds, Name, NameLike, PathType, make},
match_ast,
};
use crate::{AssistContext, AssistId, Assists};
// Assist: replace_named_generic_with_impl
//
// Replaces named generic with an `impl Trait` in function argument.
//
// ```
// fn new
>(location: P) -> Self {}
// ```
// ->
// ```
// fn new(location: impl AsRef) -> Self {}
// ```
pub(crate) fn replace_named_generic_with_impl(
acc: &mut Assists,
ctx: &AssistContext<'_>,
) -> Option<()> {
// finds `>`
let type_param = ctx.find_node_at_offset::()?;
// returns `P`
let type_param_name = type_param.name()?;
// The list of type bounds / traits: `AsRef`
let type_bound_list = type_param.type_bound_list()?;
let fn_ = type_param.syntax().ancestors().find_map(ast::Fn::cast)?;
let param_list_text_range = fn_.param_list()?.syntax().text_range();
let type_param_hir_def = ctx.sema.to_def(&type_param)?;
let type_param_def = Definition::GenericParam(hir::GenericParam::TypeParam(type_param_hir_def));
// get all usage references for the type param
let usage_refs = find_usages(&ctx.sema, &fn_, type_param_def, ctx.file_id());
if usage_refs.is_empty() {
return None;
}
// All usage references need to be valid (inside the function param list)
if !check_valid_usages(&usage_refs, param_list_text_range) {
return None;
}
let mut path_types_to_replace = Vec::new();
for (_a, refs) in usage_refs.iter() {
for usage_ref in refs {
let Some(name_like) = usage_ref.name.clone().into_name_like() else {
continue;
};
let param_node = find_path_type(&ctx.sema, &type_param_name, &name_like)?;
path_types_to_replace.push(param_node);
}
}
let target = type_param.syntax().text_range();
acc.add(
AssistId::refactor_rewrite("replace_named_generic_with_impl"),
"Replace named generic with impl trait",
target,
|edit| {
let mut editor = edit.make_editor(type_param.syntax());
// remove trait from generic param list
if let Some(generic_params) = fn_.generic_param_list() {
let params: Vec = generic_params
.clone()
.generic_params()
.filter(|it| it.syntax() != type_param.syntax())
.collect();
if params.is_empty() {
editor.delete(generic_params.syntax());
} else {
let new_generic_param_list = make::generic_param_list(params);
editor.replace(
generic_params.syntax(),
new_generic_param_list.syntax().clone_for_update(),
);
}
}
let new_bounds = make::impl_trait_type(type_bound_list);
for path_type in path_types_to_replace.iter().rev() {
editor.replace(path_type.syntax(), new_bounds.clone_for_update().syntax());
}
edit.add_file_edits(ctx.vfs_file_id(), editor);
},
)
}
fn find_path_type(
sema: &Semantics<'_, RootDatabase>,
type_param_name: &Name,
param: &NameLike,
) -> Option {
let path_type =
sema.ancestors_with_macros(param.syntax().clone()).find_map(ast::PathType::cast)?;
// Ignore any path types that look like `P::Assoc`
if path_type.path()?.as_single_name_ref()?.text() != type_param_name.text() {
return None;
}
let ancestors = sema.ancestors_with_macros(path_type.syntax().clone());
let mut in_generic_arg_list = false;
let mut is_associated_type = false;
// walking the ancestors checks them in a heuristic way until the `Fn` node is reached.
for ancestor in ancestors {
match_ast! {
match ancestor {
ast::PathSegment(ps) => {
match ps.kind()? {
ast::PathSegmentKind::Name(_name_ref) => (),
ast::PathSegmentKind::Type { .. } => return None,
_ => return None,
}
},
ast::GenericArgList(_) => {
in_generic_arg_list = true;
},
ast::AssocTypeArg(_) => {
is_associated_type = true;
},
ast::ImplTraitType(_) => {
if in_generic_arg_list && !is_associated_type {
return None;
}
},
ast::DynTraitType(_) => {
if !is_associated_type {
return None;
}
},
ast::Fn(_) => return Some(path_type),
_ => (),
}
}
}
None
}
/// Returns all usage references for the given type parameter definition.
fn find_usages(
sema: &Semantics<'_, RootDatabase>,
fn_: &ast::Fn,
type_param_def: Definition,
file_id: EditionedFileId,
) -> UsageSearchResult {
let file_range = FileRange { file_id, range: fn_.syntax().text_range() };
type_param_def.usages(sema).in_scope(&SearchScope::file_range(file_range)).all()
}
fn check_valid_usages(usages: &UsageSearchResult, param_list_range: TextRange) -> bool {
usages
.iter()
.flat_map(|(_, usage_refs)| usage_refs)
.all(|usage_ref| param_list_range.contains_range(usage_ref.range))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{check_assist, check_assist_not_applicable};
#[test]
fn replace_generic_moves_into_function() {
check_assist(
replace_named_generic_with_impl,
r#"fn new(input: T) -> Self {}"#,
r#"fn new(input: impl ToString) -> Self {}"#,
);
}
#[test]
fn replace_generic_with_inner_associated_type() {
check_assist(
replace_named_generic_with_impl,
r#"fn new