6 BLOCK_EXPR, BREAK_EXPR, CLOSURE_EXPR, COMMENT, LOOP_EXPR, MATCH_ARM, MATCH_GUARD,
7 PATH_EXPR, RETURN_EXPR,
12 use crate::{utils::suggest_name, AssistContext, AssistId, AssistKind, Assists};
14 // Assist: extract_variable
16 // Extracts subexpression into a variable.
26 // let $0var_name = (1 + 2);
30 pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
31 if ctx.has_empty_selection() {
35 let node = match ctx.covering_element() {
36 NodeOrToken::Node(it) => it,
37 NodeOrToken::Token(it) if it.kind() == COMMENT => {
38 cov_mark::hit!(extract_var_in_comment_is_not_applicable);
41 NodeOrToken::Token(it) => it.parent()?,
43 let node = node.ancestors().take_while(|anc| anc.text_range() == node.text_range()).last()?;
46 .take_while(|it| ctx.selection_trimmed().contains_range(it.text_range()))
47 .find_map(valid_target_expr)?;
49 if let Some(ty_info) = ctx.sema.type_of_expr(&to_extract) {
50 if ty_info.adjusted().is_unit() {
55 let anchor = Anchor::from(&to_extract)?;
56 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
57 let target = to_extract.syntax().text_range();
59 AssistId("extract_variable", AssistKind::RefactorExtract),
60 "Extract into variable",
64 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
65 Some(field) => field.name_ref(),
69 let mut buf = String::new();
71 let var_name = match &field_shorthand {
72 Some(it) => it.to_string(),
73 None => suggest_name::for_variable(&to_extract, &ctx.sema),
75 let expr_range = match &field_shorthand {
76 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
77 None => to_extract.syntax().text_range(),
81 Anchor::Before(_) | Anchor::Replace(_) => {
82 format_to!(buf, "let {} = ", var_name)
84 Anchor::WrapInBlock(_) => format_to!(buf, "{{ let {} = ", var_name),
86 format_to!(buf, "{}", to_extract.syntax());
88 if let Anchor::Replace(stmt) = anchor {
89 cov_mark::hit!(test_extract_var_expr_stmt);
90 if stmt.semicolon_token().is_none() {
93 match ctx.config.snippet_cap {
96 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
97 edit.replace_snippet(cap, expr_range, snip)
99 None => edit.replace(expr_range, buf),
106 // We want to maintain the indent level,
107 // but we do not want to duplicate possible
108 // extra newlines in the indent block
109 let text = indent.text();
110 if text.starts_with('\n') {
112 buf.push_str(text.trim_start_matches('\n'));
117 edit.replace(expr_range, var_name.clone());
118 let offset = anchor.syntax().text_range().start();
119 match ctx.config.snippet_cap {
122 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
123 edit.insert_snippet(cap, offset, snip)
125 None => edit.insert(offset, buf),
128 if let Anchor::WrapInBlock(_) = anchor {
129 edit.insert(anchor.syntax().text_range().end(), " }");
135 /// Check whether the node is a valid expression which can be extracted to a variable.
136 /// In general that's true for any expression, but in some cases that would produce invalid code.
137 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
139 PATH_EXPR | LOOP_EXPR => None,
140 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
141 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
143 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
145 _ => ast::Expr::cast(node),
152 Replace(ast::ExprStmt),
153 WrapInBlock(SyntaxNode),
157 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
161 .take_while(|it| !ast::Item::can_cast(it.kind()) || ast::MacroCall::can_cast(it.kind()))
164 node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr())
166 if expr.syntax() == &node {
167 cov_mark::hit!(test_extract_var_last_expr);
168 return Some(Anchor::Before(node));
172 if let Some(parent) = node.parent() {
173 if parent.kind() == CLOSURE_EXPR {
174 cov_mark::hit!(test_extract_var_in_closure_no_block);
175 return Some(Anchor::WrapInBlock(node));
177 if parent.kind() == MATCH_ARM {
178 if node.kind() == MATCH_GUARD {
179 cov_mark::hit!(test_extract_var_in_match_guard);
181 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
182 return Some(Anchor::WrapInBlock(node));
187 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
188 if let ast::Stmt::ExprStmt(stmt) = stmt {
189 if stmt.expr().as_ref() == Some(to_extract) {
190 return Some(Anchor::Replace(stmt));
193 return Some(Anchor::Before(node));
199 fn syntax(&self) -> &SyntaxNode {
201 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
202 Anchor::Replace(stmt) => stmt.syntax(),
209 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
214 fn test_extract_var_simple() {
223 let $0var_name = 1 + 1;
230 fn extract_var_in_comment_is_not_applicable() {
231 cov_mark::check!(extract_var_in_comment_is_not_applicable);
232 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
236 fn test_extract_var_expr_stmt() {
237 cov_mark::check!(test_extract_var_expr_stmt);
246 let $0var_name = 1 + 1;
258 let $0var_name = { let x = 0; x };
265 fn test_extract_var_part_of_expr_stmt() {
281 fn test_extract_var_last_expr() {
282 cov_mark::check!(test_extract_var_last_expr);
292 let $0var_name = 1 + 1;
304 fn bar(i: i32) -> i32 {
310 let $0bar = bar(1 + 1);
314 fn bar(i: i32) -> i32 {
322 fn test_extract_var_in_match_arm_no_block() {
323 cov_mark::check!(test_extract_var_in_match_arm_no_block);
329 let tuple = match x {
330 true => ($02 + 2$0, true)
338 let tuple = match x {
339 true => { let $0var_name = 2 + 2; (var_name, true) }
348 fn test_extract_var_in_match_arm_with_block() {
354 let tuple = match x {
366 let tuple = match x {
369 let $0var_name = 2 + y;
380 fn test_extract_var_in_match_guard() {
381 cov_mark::check!(test_extract_var_in_match_guard);
387 () if $010 > 0$0 => 1
394 let $0var_name = 10 > 0;
405 fn test_extract_var_in_closure_no_block() {
406 cov_mark::check!(test_extract_var_in_closure_no_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_in_closure_with_block() {
428 let lambda = |x: u32| { $0x * 2$0 };
433 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
440 fn test_extract_var_path_simple() {
445 let o = $0Some(true)$0;
450 let $0var_name = Some(true);
458 fn test_extract_var_path_method() {
463 let v = $0bar.foo()$0;
468 let $0foo = bar.foo();
476 fn test_extract_var_return() {
486 let $0var_name = 2 + 2;
494 fn test_extract_var_does_not_add_extra_whitespace() {
508 let $0var_name = 2 + 2;
525 let $0var_name = 2 + 2;
550 let $0var_name = 2 + 2;
558 fn test_extract_var_break() {
571 let $0var_name = 2 + 2;
580 fn test_extract_var_for_cast() {
585 let v = $00f32 as u32$0;
590 let $0var_name = 0f32 as u32;
598 fn extract_var_field_shorthand() {
624 fn extract_var_name_from_type() {
638 let $0test = { Test(10) };
646 fn extract_var_name_from_parameter() {
650 fn bar(test: u32, size: u32)
657 fn bar(test: u32, size: u32)
668 fn extract_var_parameter_name_has_precedence_over_type() {
672 struct TextSize(u32);
673 fn bar(test: u32, size: TextSize)
676 bar(1, $0{ TextSize(1+1) }$0);
680 struct TextSize(u32);
681 fn bar(test: u32, size: TextSize)
684 let $0size = { TextSize(1+1) };
692 fn extract_var_name_from_function() {
696 fn is_required(test: u32, size: u32) -> bool
699 $0is_required(1, 2)$0
703 fn is_required(test: u32, size: u32) -> bool
706 let $0is_required = is_required(1, 2);
714 fn extract_var_name_from_method() {
720 fn bar(&self, n: u32) -> u32 { n }
730 fn bar(&self, n: u32) -> u32 { n }
734 let $0bar = S.bar(1);
742 fn extract_var_name_from_method_param() {
748 fn bar(&self, n: u32, size: u32) { n }
758 fn bar(&self, n: u32, size: u32) { n }
770 fn extract_var_name_from_ufcs_method_param() {
776 fn bar(&self, n: u32, size: u32) { n }
780 S::bar(&S, $01 + 1$0, 2)
786 fn bar(&self, n: u32, size: u32) { n }
798 fn extract_var_parameter_name_has_precedence_over_function() {
802 fn bar(test: u32, size: u32)
805 bar(1, $0symbol_size(1, 2)$0);
809 fn bar(test: u32, size: u32)
812 let $0size = symbol_size(1, 2);
820 fn test_extract_var_for_return_not_applicable() {
821 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
825 fn test_extract_var_for_break_not_applicable() {
826 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
830 fn test_extract_var_unit_expr_not_applicable() {
831 check_assist_not_applicable(
845 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
847 fn extract_var_target() {
848 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
855 let tuple = match x {
856 true => ($02 + 2$0, true)
866 fn extract_var_no_block_body() {
867 check_assist_not_applicable(
870 const X: usize = $0100$0;