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 if let Some(ty) = ctx.sema.type_of_expr(&to_extract) {
44 let anchor = Anchor::from(&to_extract)?;
45 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
46 let target = to_extract.syntax().text_range();
48 AssistId("extract_variable", AssistKind::RefactorExtract),
49 "Extract into variable",
53 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
54 Some(field) => field.name_ref(),
58 let mut buf = String::new();
60 let var_name = match &field_shorthand {
61 Some(it) => it.to_string(),
62 None => suggest_name::for_variable(&to_extract, &ctx.sema),
64 let expr_range = match &field_shorthand {
65 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
66 None => to_extract.syntax().text_range(),
69 if let Anchor::WrapInBlock(_) = anchor {
70 format_to!(buf, "{{ let {} = ", var_name);
72 format_to!(buf, "let {} = ", var_name);
74 format_to!(buf, "{}", to_extract.syntax());
76 if let Anchor::Replace(stmt) = anchor {
77 cov_mark::hit!(test_extract_var_expr_stmt);
78 if stmt.semicolon_token().is_none() {
81 match ctx.config.snippet_cap {
84 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
85 edit.replace_snippet(cap, expr_range, snip)
87 None => edit.replace(expr_range, buf),
94 // We want to maintain the indent level,
95 // but we do not want to duplicate possible
96 // extra newlines in the indent block
97 let text = indent.text();
98 if text.starts_with('\n') {
100 buf.push_str(text.trim_start_matches('\n'));
105 edit.replace(expr_range, var_name.clone());
106 let offset = anchor.syntax().text_range().start();
107 match ctx.config.snippet_cap {
110 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
111 edit.insert_snippet(cap, offset, snip)
113 None => edit.insert(offset, buf),
116 if let Anchor::WrapInBlock(_) = anchor {
117 edit.insert(anchor.syntax().text_range().end(), " }");
123 /// Check whether the node is a valid expression which can be extracted to a variable.
124 /// In general that's true for any expression, but in some cases that would produce invalid code.
125 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
127 PATH_EXPR | LOOP_EXPR => None,
128 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
129 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
131 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
133 _ => ast::Expr::cast(node),
139 Replace(ast::ExprStmt),
140 WrapInBlock(SyntaxNode),
144 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
145 to_extract.syntax().ancestors().find_map(|node| {
147 node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.tail_expr())
149 if expr.syntax() == &node {
150 cov_mark::hit!(test_extract_var_last_expr);
151 return Some(Anchor::Before(node));
155 if let Some(parent) = node.parent() {
156 if parent.kind() == CLOSURE_EXPR {
157 cov_mark::hit!(test_extract_var_in_closure_no_block);
158 return Some(Anchor::WrapInBlock(node));
160 if parent.kind() == MATCH_ARM {
161 if node.kind() == MATCH_GUARD {
162 cov_mark::hit!(test_extract_var_in_match_guard);
164 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
165 return Some(Anchor::WrapInBlock(node));
170 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
171 if let ast::Stmt::ExprStmt(stmt) = stmt {
172 if stmt.expr().as_ref() == Some(to_extract) {
173 return Some(Anchor::Replace(stmt));
176 return Some(Anchor::Before(node));
182 fn syntax(&self) -> &SyntaxNode {
184 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
185 Anchor::Replace(stmt) => stmt.syntax(),
192 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
197 fn test_extract_var_simple() {
206 let $0var_name = 1 + 1;
213 fn extract_var_in_comment_is_not_applicable() {
214 cov_mark::check!(extract_var_in_comment_is_not_applicable);
215 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
219 fn test_extract_var_expr_stmt() {
220 cov_mark::check!(test_extract_var_expr_stmt);
229 let $0var_name = 1 + 1;
241 let $0var_name = { let x = 0; x };
248 fn test_extract_var_part_of_expr_stmt() {
264 fn test_extract_var_last_expr() {
265 cov_mark::check!(test_extract_var_last_expr);
275 let $0var_name = 1 + 1;
287 fn bar(i: i32) -> i32 {
293 let $0bar = bar(1 + 1);
297 fn bar(i: i32) -> i32 {
305 fn test_extract_var_in_match_arm_no_block() {
306 cov_mark::check!(test_extract_var_in_match_arm_no_block);
312 let tuple = match x {
313 true => ($02 + 2$0, true)
321 let tuple = match x {
322 true => { let $0var_name = 2 + 2; (var_name, true) }
331 fn test_extract_var_in_match_arm_with_block() {
337 let tuple = match x {
349 let tuple = match x {
352 let $0var_name = 2 + y;
363 fn test_extract_var_in_match_guard() {
364 cov_mark::check!(test_extract_var_in_match_guard);
370 () if $010 > 0$0 => 1
377 let $0var_name = 10 > 0;
388 fn test_extract_var_in_closure_no_block() {
389 cov_mark::check!(test_extract_var_in_closure_no_block);
394 let lambda = |x: u32| $0x * 2$0;
399 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
406 fn test_extract_var_in_closure_with_block() {
411 let lambda = |x: u32| { $0x * 2$0 };
416 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
423 fn test_extract_var_path_simple() {
428 let o = $0Some(true)$0;
433 let $0var_name = Some(true);
441 fn test_extract_var_path_method() {
446 let v = $0bar.foo()$0;
451 let $0foo = bar.foo();
459 fn test_extract_var_return() {
469 let $0var_name = 2 + 2;
477 fn test_extract_var_does_not_add_extra_whitespace() {
491 let $0var_name = 2 + 2;
508 let $0var_name = 2 + 2;
533 let $0var_name = 2 + 2;
541 fn test_extract_var_break() {
554 let $0var_name = 2 + 2;
563 fn test_extract_var_for_cast() {
568 let v = $00f32 as u32$0;
573 let $0var_name = 0f32 as u32;
581 fn extract_var_field_shorthand() {
607 fn extract_var_name_from_type() {
621 let $0test = { Test(10) };
629 fn extract_var_name_from_parameter() {
633 fn bar(test: u32, size: u32)
640 fn bar(test: u32, size: u32)
651 fn extract_var_parameter_name_has_precedence_over_type() {
655 struct TextSize(u32);
656 fn bar(test: u32, size: TextSize)
659 bar(1, $0{ TextSize(1+1) }$0);
663 struct TextSize(u32);
664 fn bar(test: u32, size: TextSize)
667 let $0size = { TextSize(1+1) };
675 fn extract_var_name_from_function() {
679 fn is_required(test: u32, size: u32) -> bool
682 $0is_required(1, 2)$0
686 fn is_required(test: u32, size: u32) -> bool
689 let $0is_required = is_required(1, 2);
697 fn extract_var_name_from_method() {
703 fn bar(&self, n: u32) -> u32 { n }
713 fn bar(&self, n: u32) -> u32 { n }
717 let $0bar = S.bar(1);
725 fn extract_var_name_from_method_param() {
731 fn bar(&self, n: u32, size: u32) { n }
741 fn bar(&self, n: u32, size: u32) { n }
753 fn extract_var_name_from_ufcs_method_param() {
759 fn bar(&self, n: u32, size: u32) { n }
763 S::bar(&S, $01 + 1$0, 2)
769 fn bar(&self, n: u32, size: u32) { n }
781 fn extract_var_parameter_name_has_precedence_over_function() {
785 fn bar(test: u32, size: u32)
788 bar(1, $0symbol_size(1, 2)$0);
792 fn bar(test: u32, size: u32)
795 let $0size = symbol_size(1, 2);
803 fn test_extract_var_for_return_not_applicable() {
804 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
808 fn test_extract_var_for_break_not_applicable() {
809 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
813 fn test_extract_var_unit_expr_not_applicable() {
814 check_assist_not_applicable(
828 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
830 fn extract_var_target() {
831 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
838 let tuple = match x {
839 true => ($02 + 2$0, true)