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);
40 .take_while(|it| it.text_range().contains_range(ctx.frange.range))
41 .find_map(valid_target_expr)?;
42 if let Some(ty_info) = ctx.sema.type_of_expr(&to_extract) {
43 if ty_info.adjusted().is_unit() {
47 let anchor = Anchor::from(&to_extract)?;
48 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
49 let target = to_extract.syntax().text_range();
51 AssistId("extract_variable", AssistKind::RefactorExtract),
52 "Extract into variable",
56 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
57 Some(field) => field.name_ref(),
61 let mut buf = String::new();
63 let var_name = match &field_shorthand {
64 Some(it) => it.to_string(),
65 None => suggest_name::for_variable(&to_extract, &ctx.sema),
67 let expr_range = match &field_shorthand {
68 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
69 None => to_extract.syntax().text_range(),
72 if let Anchor::WrapInBlock(_) = anchor {
73 format_to!(buf, "{{ let {} = ", var_name);
75 format_to!(buf, "let {} = ", var_name);
77 format_to!(buf, "{}", to_extract.syntax());
79 if let Anchor::Replace(stmt) = anchor {
80 cov_mark::hit!(test_extract_var_expr_stmt);
81 if stmt.semicolon_token().is_none() {
84 match ctx.config.snippet_cap {
87 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
88 edit.replace_snippet(cap, expr_range, snip)
90 None => edit.replace(expr_range, buf),
97 // We want to maintain the indent level,
98 // but we do not want to duplicate possible
99 // extra newlines in the indent block
100 let text = indent.text();
101 if text.starts_with('\n') {
103 buf.push_str(text.trim_start_matches('\n'));
108 edit.replace(expr_range, var_name.clone());
109 let offset = anchor.syntax().text_range().start();
110 match ctx.config.snippet_cap {
113 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
114 edit.insert_snippet(cap, offset, snip)
116 None => edit.insert(offset, buf),
119 if let Anchor::WrapInBlock(_) = anchor {
120 edit.insert(anchor.syntax().text_range().end(), " }");
126 /// Check whether the node is a valid expression which can be extracted to a variable.
127 /// In general that's true for any expression, but in some cases that would produce invalid code.
128 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
130 PATH_EXPR | LOOP_EXPR => None,
131 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
132 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
134 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
136 _ => ast::Expr::cast(node),
142 Replace(ast::ExprStmt),
143 WrapInBlock(SyntaxNode),
147 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
148 to_extract.syntax().ancestors().take_while(|it| !ast::Item::can_cast(it.kind())).find_map(
151 node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.tail_expr())
153 if expr.syntax() == &node {
154 cov_mark::hit!(test_extract_var_last_expr);
155 return Some(Anchor::Before(node));
159 if let Some(parent) = node.parent() {
160 if parent.kind() == CLOSURE_EXPR {
161 cov_mark::hit!(test_extract_var_in_closure_no_block);
162 return Some(Anchor::WrapInBlock(node));
164 if parent.kind() == MATCH_ARM {
165 if node.kind() == MATCH_GUARD {
166 cov_mark::hit!(test_extract_var_in_match_guard);
168 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
169 return Some(Anchor::WrapInBlock(node));
174 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
175 if let ast::Stmt::ExprStmt(stmt) = stmt {
176 if stmt.expr().as_ref() == Some(to_extract) {
177 return Some(Anchor::Replace(stmt));
180 return Some(Anchor::Before(node));
187 fn syntax(&self) -> &SyntaxNode {
189 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
190 Anchor::Replace(stmt) => stmt.syntax(),
197 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
202 fn test_extract_var_simple() {
211 let $0var_name = 1 + 1;
218 fn extract_var_in_comment_is_not_applicable() {
219 cov_mark::check!(extract_var_in_comment_is_not_applicable);
220 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
224 fn test_extract_var_expr_stmt() {
225 cov_mark::check!(test_extract_var_expr_stmt);
234 let $0var_name = 1 + 1;
246 let $0var_name = { let x = 0; x };
253 fn test_extract_var_part_of_expr_stmt() {
269 fn test_extract_var_last_expr() {
270 cov_mark::check!(test_extract_var_last_expr);
280 let $0var_name = 1 + 1;
292 fn bar(i: i32) -> i32 {
298 let $0bar = bar(1 + 1);
302 fn bar(i: i32) -> i32 {
310 fn test_extract_var_in_match_arm_no_block() {
311 cov_mark::check!(test_extract_var_in_match_arm_no_block);
317 let tuple = match x {
318 true => ($02 + 2$0, true)
326 let tuple = match x {
327 true => { let $0var_name = 2 + 2; (var_name, true) }
336 fn test_extract_var_in_match_arm_with_block() {
342 let tuple = match x {
354 let tuple = match x {
357 let $0var_name = 2 + y;
368 fn test_extract_var_in_match_guard() {
369 cov_mark::check!(test_extract_var_in_match_guard);
375 () if $010 > 0$0 => 1
382 let $0var_name = 10 > 0;
393 fn test_extract_var_in_closure_no_block() {
394 cov_mark::check!(test_extract_var_in_closure_no_block);
399 let lambda = |x: u32| $0x * 2$0;
404 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
411 fn test_extract_var_in_closure_with_block() {
416 let lambda = |x: u32| { $0x * 2$0 };
421 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
428 fn test_extract_var_path_simple() {
433 let o = $0Some(true)$0;
438 let $0var_name = Some(true);
446 fn test_extract_var_path_method() {
451 let v = $0bar.foo()$0;
456 let $0foo = bar.foo();
464 fn test_extract_var_return() {
474 let $0var_name = 2 + 2;
482 fn test_extract_var_does_not_add_extra_whitespace() {
496 let $0var_name = 2 + 2;
513 let $0var_name = 2 + 2;
538 let $0var_name = 2 + 2;
546 fn test_extract_var_break() {
559 let $0var_name = 2 + 2;
568 fn test_extract_var_for_cast() {
573 let v = $00f32 as u32$0;
578 let $0var_name = 0f32 as u32;
586 fn extract_var_field_shorthand() {
612 fn extract_var_name_from_type() {
626 let $0test = { Test(10) };
634 fn extract_var_name_from_parameter() {
638 fn bar(test: u32, size: u32)
645 fn bar(test: u32, size: u32)
656 fn extract_var_parameter_name_has_precedence_over_type() {
660 struct TextSize(u32);
661 fn bar(test: u32, size: TextSize)
664 bar(1, $0{ TextSize(1+1) }$0);
668 struct TextSize(u32);
669 fn bar(test: u32, size: TextSize)
672 let $0size = { TextSize(1+1) };
680 fn extract_var_name_from_function() {
684 fn is_required(test: u32, size: u32) -> bool
687 $0is_required(1, 2)$0
691 fn is_required(test: u32, size: u32) -> bool
694 let $0is_required = is_required(1, 2);
702 fn extract_var_name_from_method() {
708 fn bar(&self, n: u32) -> u32 { n }
718 fn bar(&self, n: u32) -> u32 { n }
722 let $0bar = S.bar(1);
730 fn extract_var_name_from_method_param() {
736 fn bar(&self, n: u32, size: u32) { n }
746 fn bar(&self, n: u32, size: u32) { n }
758 fn extract_var_name_from_ufcs_method_param() {
764 fn bar(&self, n: u32, size: u32) { n }
768 S::bar(&S, $01 + 1$0, 2)
774 fn bar(&self, n: u32, size: u32) { n }
786 fn extract_var_parameter_name_has_precedence_over_function() {
790 fn bar(test: u32, size: u32)
793 bar(1, $0symbol_size(1, 2)$0);
797 fn bar(test: u32, size: u32)
800 let $0size = symbol_size(1, 2);
808 fn test_extract_var_for_return_not_applicable() {
809 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
813 fn test_extract_var_for_break_not_applicable() {
814 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
818 fn test_extract_var_unit_expr_not_applicable() {
819 check_assist_not_applicable(
833 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
835 fn extract_var_target() {
836 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
843 let tuple = match x {
844 true => ($02 + 2$0, true)
854 fn extract_var_no_block_body() {
855 check_assist_not_applicable(
858 const X: usize = $0100$0;