Skip to content

Commit

Permalink
Address another round of review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
jplatte committed Apr 5, 2023
1 parent d01a38c commit bc704e1
Showing 1 changed file with 9 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,35 +41,31 @@ pub(crate) fn convert_nested_function_to_closure(
let target = function.syntax().text_range();
let body = function.body()?;
let name = function.name()?;
let params = function.param_list()?;

let params_text = params.syntax().text().to_string();
let closure_params = params_text.strip_prefix("(").and_then(|p| p.strip_suffix(")"))?;
let param_list = 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 = &param_list.syntax().text().to_string();
let params = params.strip_prefix("(").unwrap_or(params);
let params = params.strip_suffix(")").unwrap_or(params);

let mut body = body.to_string();
if !has_semicolon {
if !has_semicolon(&function) {
body.push(';');
}
edit.replace(target, format!("let {} = |{}| {}", name, closure_params, body));
edit.replace(target, format!("let {name} = |{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()
.ancestors()
.skip(1)
.find_map(ast::Item::cast)
.map_or(false, |it| matches!(it, ast::Item::Fn(_)))
function.syntax().ancestors().skip(1).find_map(ast::Item::cast).map_or(false, |it| {
matches!(it, ast::Item::Fn(_) | ast::Item::Static(_) | ast::Item::Const(_))
})
}

/// Returns whether the given nested function has generic parameters.
Expand Down

0 comments on commit bc704e1

Please sign in to comment.