5 BLOCK_EXPR, BREAK_EXPR, CLOSURE_EXPR, COMMENT, LOOP_EXPR, MATCH_ARM, MATCH_GUARD,
6 PATH_EXPR, RETURN_EXPR,
11 use crate::{utils::suggest_name, AssistContext, AssistId, AssistKind, Assists};
13 // Assist: extract_variable
15 // Extracts subexpression into a variable.
25 // let $0var_name = (1 + 2);
29 pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
30 if ctx.frange.range.is_empty() {
33 let node = ctx.covering_element();
34 if node.kind() == COMMENT {
35 cov_mark::hit!(extract_var_in_comment_is_not_applicable);
38 let to_extract = node.ancestors().find_map(valid_target_expr)?;
39 let anchor = Anchor::from(&to_extract)?;
40 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
41 let target = to_extract.syntax().text_range();
43 AssistId("extract_variable", AssistKind::RefactorExtract),
44 "Extract into variable",
48 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
49 Some(field) => field.name_ref(),
53 let mut buf = String::new();
55 let var_name = match &field_shorthand {
56 Some(it) => it.to_string(),
57 None => suggest_name::for_variable(&to_extract, &ctx.sema),
59 let expr_range = match &field_shorthand {
60 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
61 None => to_extract.syntax().text_range(),
64 if let Anchor::WrapInBlock(_) = anchor {
65 format_to!(buf, "{{ let {} = ", var_name);
67 format_to!(buf, "let {} = ", var_name);
69 format_to!(buf, "{}", to_extract.syntax());
71 if let Anchor::Replace(stmt) = anchor {
72 cov_mark::hit!(test_extract_var_expr_stmt);
73 if stmt.semicolon_token().is_none() {
76 match ctx.config.snippet_cap {
79 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
80 edit.replace_snippet(cap, expr_range, snip)
82 None => edit.replace(expr_range, buf),
89 // We want to maintain the indent level,
90 // but we do not want to duplicate possible
91 // extra newlines in the indent block
92 let text = indent.text();
93 if text.starts_with('\n') {
95 buf.push_str(text.trim_start_matches('\n'));
100 edit.replace(expr_range, var_name.clone());
101 let offset = anchor.syntax().text_range().start();
102 match ctx.config.snippet_cap {
105 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
106 edit.insert_snippet(cap, offset, snip)
108 None => edit.insert(offset, buf),
111 if let Anchor::WrapInBlock(_) = anchor {
112 edit.insert(anchor.syntax().text_range().end(), " }");
118 /// Check whether the node is a valid expression which can be extracted to a variable.
119 /// In general that's true for any expression, but in some cases that would produce invalid code.
120 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
122 PATH_EXPR | LOOP_EXPR => None,
123 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
124 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
126 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
128 _ => ast::Expr::cast(node),
134 Replace(ast::ExprStmt),
135 WrapInBlock(SyntaxNode),
139 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
140 to_extract.syntax().ancestors().find_map(|node| {
142 node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.tail_expr())
144 if expr.syntax() == &node {
145 cov_mark::hit!(test_extract_var_last_expr);
146 return Some(Anchor::Before(node));
150 if let Some(parent) = node.parent() {
151 if parent.kind() == CLOSURE_EXPR {
152 cov_mark::hit!(test_extract_var_in_closure_no_block);
153 return Some(Anchor::WrapInBlock(node));
155 if parent.kind() == MATCH_ARM {
156 if node.kind() == MATCH_GUARD {
157 cov_mark::hit!(test_extract_var_in_match_guard);
159 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
160 return Some(Anchor::WrapInBlock(node));
165 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
166 if let ast::Stmt::ExprStmt(stmt) = stmt {
167 if stmt.expr().as_ref() == Some(to_extract) {
168 return Some(Anchor::Replace(stmt));
171 return Some(Anchor::Before(node));
177 fn syntax(&self) -> &SyntaxNode {
179 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
180 Anchor::Replace(stmt) => stmt.syntax(),
187 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
192 fn test_extract_var_simple() {
201 let $0var_name = 1 + 1;
208 fn extract_var_in_comment_is_not_applicable() {
209 cov_mark::check!(extract_var_in_comment_is_not_applicable);
210 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
214 fn test_extract_var_expr_stmt() {
215 cov_mark::check!(test_extract_var_expr_stmt);
224 let $0var_name = 1 + 1;
236 let $0var_name = { let x = 0; x };
243 fn test_extract_var_part_of_expr_stmt() {
259 fn test_extract_var_last_expr() {
260 cov_mark::check!(test_extract_var_last_expr);
270 let $0var_name = 1 + 1;
284 let $0bar = bar(1 + 1);
292 fn test_extract_var_in_match_arm_no_block() {
293 cov_mark::check!(test_extract_var_in_match_arm_no_block);
299 let tuple = match x {
300 true => ($02 + 2$0, true)
308 let tuple = match x {
309 true => { let $0var_name = 2 + 2; (var_name, true) }
318 fn test_extract_var_in_match_arm_with_block() {
324 let tuple = match x {
336 let tuple = match x {
339 let $0var_name = 2 + y;
350 fn test_extract_var_in_match_guard() {
351 cov_mark::check!(test_extract_var_in_match_guard);
357 () if $010 > 0$0 => 1
364 let $0var_name = 10 > 0;
375 fn test_extract_var_in_closure_no_block() {
376 cov_mark::check!(test_extract_var_in_closure_no_block);
381 let lambda = |x: u32| $0x * 2$0;
386 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
393 fn test_extract_var_in_closure_with_block() {
398 let lambda = |x: u32| { $0x * 2$0 };
403 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
410 fn test_extract_var_path_simple() {
415 let o = $0Some(true)$0;
420 let $0var_name = Some(true);
428 fn test_extract_var_path_method() {
433 let v = $0bar.foo()$0;
438 let $0foo = bar.foo();
446 fn test_extract_var_return() {
456 let $0var_name = 2 + 2;
464 fn test_extract_var_does_not_add_extra_whitespace() {
478 let $0var_name = 2 + 2;
495 let $0var_name = 2 + 2;
520 let $0var_name = 2 + 2;
528 fn test_extract_var_break() {
541 let $0var_name = 2 + 2;
550 fn test_extract_var_for_cast() {
555 let v = $00f32 as u32$0;
560 let $0var_name = 0f32 as u32;
568 fn extract_var_field_shorthand() {
594 fn extract_var_name_from_type() {
608 let $0test = { Test(10) };
616 fn extract_var_name_from_parameter() {
620 fn bar(test: u32, size: u32)
627 fn bar(test: u32, size: u32)
638 fn extract_var_parameter_name_has_precedence_over_type() {
642 struct TextSize(u32);
643 fn bar(test: u32, size: TextSize)
646 bar(1, $0{ TextSize(1+1) }$0);
650 struct TextSize(u32);
651 fn bar(test: u32, size: TextSize)
654 let $0size = { TextSize(1+1) };
662 fn extract_var_name_from_function() {
666 fn is_required(test: u32, size: u32) -> bool
669 $0is_required(1, 2)$0
673 fn is_required(test: u32, size: u32) -> bool
676 let $0is_required = is_required(1, 2);
684 fn extract_var_name_from_method() {
690 fn bar(&self, n: u32) -> u32 { n }
700 fn bar(&self, n: u32) -> u32 { n }
704 let $0bar = S.bar(1);
712 fn extract_var_name_from_method_param() {
718 fn bar(&self, n: u32, size: u32) { n }
728 fn bar(&self, n: u32, size: u32) { n }
740 fn extract_var_name_from_ufcs_method_param() {
746 fn bar(&self, n: u32, size: u32) { n }
750 S::bar(&S, $01 + 1$0, 2)
756 fn bar(&self, n: u32, size: u32) { n }
768 fn extract_var_parameter_name_has_precedence_over_function() {
772 fn bar(test: u32, size: u32)
775 bar(1, $0symbol_size(1, 2)$0);
779 fn bar(test: u32, size: u32)
782 let $0size = symbol_size(1, 2);
790 fn test_extract_var_for_return_not_applicable() {
791 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
795 fn test_extract_var_for_break_not_applicable() {
796 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
799 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
801 fn extract_var_target() {
802 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
809 let tuple = match x {
810 true => ($02 + 2$0, true)