Skip to content

Commit 7285130

Browse files
committed
Improve extract_function name
If the name contains `_`, it is likely to be descriptive Example --- ```rust fn foo(kind: i32) { let is_complex = $0kind != 0$0; } ``` **Before this PR** ```rust fn foo(kind: i32) { let is_complex = fun_name(kind); } fn fun_name(kind: i32) -> bool { kind != 0 } ``` **After this PR** ```rust fn foo(kind: i32) { let is_complex = is_complex(kind); } fn is_complex(kind: i32) -> bool { kind != 0 } ```
1 parent 39018ac commit 7285130

1 file changed

Lines changed: 21 additions & 5 deletions

File tree

crates/ide-assists/src/handlers/extract_function.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
120120

121121
let params = body.extracted_function_params(ctx, &container_info, locals_used);
122122

123-
let name = make_function_name(&semantics_scope);
123+
let name = make_function_name(&semantics_scope, &body);
124124

125125
let fun = Function {
126126
name,
@@ -241,7 +241,10 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
241241
)
242242
}
243243

244-
fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef {
244+
fn make_function_name(
245+
semantics_scope: &hir::SemanticsScope<'_>,
246+
body: &FunctionBody,
247+
) -> ast::NameRef {
245248
let mut names_in_scope = vec![];
246249
semantics_scope.process_all_names(&mut |name, _| {
247250
names_in_scope.push(
@@ -252,7 +255,10 @@ fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef
252255

253256
let default_name = "fun_name";
254257

255-
let mut name = default_name.to_owned();
258+
let mut name = body
259+
.suggest_name()
260+
.filter(|name| name.contains('_'))
261+
.unwrap_or_else(|| default_name.to_owned());
256262
let mut counter = 0;
257263
while names_in_scope.contains(&name) {
258264
counter += 1;
@@ -779,6 +785,16 @@ impl FunctionBody {
779785
fn contains_node(&self, node: &SyntaxNode) -> bool {
780786
self.contains_range(node.text_range())
781787
}
788+
789+
fn suggest_name(&self) -> Option<String> {
790+
if let Some(ast::Pat::IdentPat(pat)) = self.parent().and_then(ast::LetStmt::cast)?.pat()
791+
&& let Some(name) = pat.name().and_then(|it| it.ident_token())
792+
{
793+
Some(name.text().to_owned())
794+
} else {
795+
None
796+
}
797+
}
782798
}
783799

784800
impl FunctionBody {
@@ -5430,12 +5446,12 @@ impl Struct {
54305446
54315447
impl Trait for Struct {
54325448
fn bar(&self) -> i32 {
5433-
let three_squared = fun_name();
5449+
let three_squared = three_squared();
54345450
self.0 + three_squared
54355451
}
54365452
}
54375453
5438-
fn $0fun_name() -> i32 {
5454+
fn $0three_squared() -> i32 {
54395455
3 * 3
54405456
}
54415457
"#,

0 commit comments

Comments
 (0)