-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Assist to convert nested function to closure. #13467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
mdx97
wants to merge
6
commits into
rust-lang:master
from
mdx97:mathew/convert-nested-function-to-closure
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7cb1192
Assist to convert nested function to closure.
mathew-horner 9049978
Make assist only applicable when cursor is on function name.
mathew-horner b4d294c
Don't parse file to find out if the nested function has a semicolon.
mathew-horner 514e75a
Make assist not applicable when the nested function has generic param…
mathew-horner cc2ff7a
Move has_semicolon call into assist callback.
mathew-horner 214dfc5
Merge branch 'master' into mathew/convert-nested-function-to-closure
mathew-horner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
185 changes: 185 additions & 0 deletions
185
crates/ide-assists/src/handlers/convert_nested_function_to_closure.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,185 @@ | ||
use ide_db::assists::{AssistId, AssistKind}; | ||
use syntax::ast::{self, HasGenericParams, HasName}; | ||
use syntax::{AstNode, SyntaxKind}; | ||
|
||
use crate::assist_context::{AssistContext, Assists}; | ||
|
||
// Assist: convert_nested_function_to_closure | ||
// | ||
// Converts a function that is defined within the body of another function into a closure. | ||
// | ||
// ``` | ||
// fn main() { | ||
// fn fo$0o(label: &str, number: u64) { | ||
// println!("{}: {}", label, number); | ||
// } | ||
// | ||
// foo("Bar", 100); | ||
// } | ||
// ``` | ||
// -> | ||
// ``` | ||
// fn main() { | ||
// let foo = |label: &str, number: u64| { | ||
// println!("{}: {}", label, number); | ||
// }; | ||
// | ||
// foo("Bar", 100); | ||
// } | ||
// ``` | ||
pub(crate) fn convert_nested_function_to_closure( | ||
acc: &mut Assists, | ||
ctx: &AssistContext<'_>, | ||
) -> Option<()> { | ||
let name = ctx.find_node_at_offset::<ast::Name>()?; | ||
let function = name.syntax().parent().and_then(ast::Fn::cast)?; | ||
|
||
if !is_nested_function(&function) || is_generic(&function) { | ||
return None; | ||
} | ||
|
||
let target = function.syntax().text_range(); | ||
let body = function.body()?; | ||
let name = function.name()?; | ||
let params = function.param_list()?; | ||
|
||
acc.add( | ||
AssistId("convert_nested_function_to_closure", AssistKind::RefactorRewrite), | ||
"Convert nested function to closure", | ||
target, | ||
|edit| { | ||
let has_semicolon = has_semicolon(&function); | ||
let params_text = params.syntax().text().to_string(); | ||
let params_text_trimmed = | ||
params_text.strip_prefix("(").and_then(|p| p.strip_suffix(")")); | ||
|
||
if let Some(closure_params) = params_text_trimmed { | ||
let body = body.to_string(); | ||
let body = if has_semicolon { body } else { format!("{};", body) }; | ||
edit.replace(target, format!("let {} = |{}| {}", name, closure_params, body)); | ||
} | ||
}, | ||
) | ||
} | ||
|
||
/// Returns whether the given function is nested within the body of another function. | ||
fn is_nested_function(function: &ast::Fn) -> bool { | ||
function | ||
.syntax() | ||
.parent() | ||
.map(|p| p.ancestors().any(|a| a.kind() == SyntaxKind::FN)) | ||
.unwrap_or(false) | ||
} | ||
|
||
/// Returns whether the given nested function has generic parameters. | ||
fn is_generic(function: &ast::Fn) -> bool { | ||
function.generic_param_list().is_some() | ||
} | ||
|
||
/// Returns whether the given nested function has a trailing semicolon. | ||
fn has_semicolon(function: &ast::Fn) -> bool { | ||
function | ||
.syntax() | ||
.next_sibling_or_token() | ||
.map(|t| t.kind() == SyntaxKind::SEMICOLON) | ||
.unwrap_or(false) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::tests::{check_assist, check_assist_not_applicable}; | ||
|
||
use super::convert_nested_function_to_closure; | ||
|
||
#[test] | ||
fn convert_nested_function_to_closure_works() { | ||
check_assist( | ||
convert_nested_function_to_closure, | ||
r#" | ||
fn main() { | ||
fn $0foo(a: u64, b: u64) -> u64 { | ||
2 * (a + b) | ||
} | ||
|
||
_ = foo(3, 4); | ||
} | ||
"#, | ||
r#" | ||
fn main() { | ||
let foo = |a: u64, b: u64| { | ||
2 * (a + b) | ||
}; | ||
|
||
_ = foo(3, 4); | ||
} | ||
"#, | ||
); | ||
} | ||
|
||
#[test] | ||
fn convert_nested_function_to_closure_works_with_existing_semicolon() { | ||
check_assist( | ||
convert_nested_function_to_closure, | ||
r#" | ||
fn main() { | ||
fn foo$0(a: u64, b: u64) -> u64 { | ||
2 * (a + b) | ||
}; | ||
|
||
_ = foo(3, 4); | ||
} | ||
"#, | ||
r#" | ||
fn main() { | ||
let foo = |a: u64, b: u64| { | ||
2 * (a + b) | ||
}; | ||
|
||
_ = foo(3, 4); | ||
} | ||
"#, | ||
); | ||
} | ||
|
||
#[test] | ||
fn convert_nested_function_to_closure_does_not_work_on_top_level_function() { | ||
check_assist_not_applicable( | ||
convert_nested_function_to_closure, | ||
r#" | ||
fn ma$0in() {} | ||
"#, | ||
); | ||
} | ||
|
||
#[test] | ||
fn convert_nested_function_to_closure_does_not_work_when_cursor_off_name() { | ||
check_assist_not_applicable( | ||
convert_nested_function_to_closure, | ||
r#" | ||
fn main() { | ||
fn foo(a: u64, $0b: u64) -> u64 { | ||
2 * (a + b) | ||
}; | ||
|
||
_ = foo(3, 4); | ||
} | ||
"#, | ||
); | ||
} | ||
|
||
#[test] | ||
fn convert_nested_function_to_closure_does_not_work_if_function_has_generic_params() { | ||
check_assist_not_applicable( | ||
convert_nested_function_to_closure, | ||
r#" | ||
fn main() { | ||
fn fo$0o<S: Into<String>>(s: S) -> String { | ||
s.into() | ||
}; | ||
|
||
_ = foo("hello"); | ||
} | ||
"#, | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will trigger incorrectly if we have an associated function nested in a function (very rare that someone does this but it could happen), so it might be nicer to do the following
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure what that snippet is supposed to do, namely because there are two arguments that are passed to
unwrap_or
. Would it be easier to just check if the function is an associated function?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh my bad, this was supposed to be a
map_or_else
. But yes it would be easier to just check if it is an assocaited function actually, that is go from theast::Fn
to thehir
version and check if that is an assoc item.