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.frange.range.is_empty() {
34 let node = match ctx.covering_element() {
35 NodeOrToken::Node(it) => it,
36 NodeOrToken::Token(it) if it.kind() == COMMENT => {
37 cov_mark::hit!(extract_var_in_comment_is_not_applicable);
40 NodeOrToken::Token(it) => it.parent()?,
42 let node = node.ancestors().take_while(|anc| anc.text_range() == node.text_range()).last()?;
45 .take_while(|it| ctx.frange.range.contains_range(it.text_range()))
46 .find_map(valid_target_expr)?;
48 if let Some(ty_info) = ctx.sema.type_of_expr(&to_extract) {
49 if ty_info.adjusted().is_unit() {
54 let anchor = Anchor::from(&to_extract)?;
55 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
56 let target = to_extract.syntax().text_range();
58 AssistId("extract_variable", AssistKind::RefactorExtract),
59 "Extract into variable",
63 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
64 Some(field) => field.name_ref(),
68 let mut buf = String::new();
70 let var_name = match &field_shorthand {
71 Some(it) => it.to_string(),
72 None => suggest_name::for_variable(&to_extract, &ctx.sema),
74 let expr_range = match &field_shorthand {
75 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
76 None => to_extract.syntax().text_range(),
80 Anchor::Before(_) | Anchor::Replace(_) => {
81 format_to!(buf, "let {} = ", var_name)
83 Anchor::WrapInBlock(_) => format_to!(buf, "{{ let {} = ", var_name),
85 format_to!(buf, "{}", to_extract.syntax());
87 if let Anchor::Replace(stmt) = anchor {
88 cov_mark::hit!(test_extract_var_expr_stmt);
89 if stmt.semicolon_token().is_none() {
92 match ctx.config.snippet_cap {
95 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
96 edit.replace_snippet(cap, expr_range, snip)
98 None => edit.replace(expr_range, buf),
105 // We want to maintain the indent level,
106 // but we do not want to duplicate possible
107 // extra newlines in the indent block
108 let text = indent.text();
109 if text.starts_with('\n') {
111 buf.push_str(text.trim_start_matches('\n'));
116 edit.replace(expr_range, var_name.clone());
117 let offset = anchor.syntax().text_range().start();
118 match ctx.config.snippet_cap {
121 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
122 edit.insert_snippet(cap, offset, snip)
124 None => edit.insert(offset, buf),
127 if let Anchor::WrapInBlock(_) = anchor {
128 edit.insert(anchor.syntax().text_range().end(), " }");
134 /// Check whether the node is a valid expression which can be extracted to a variable.
135 /// In general that's true for any expression, but in some cases that would produce invalid code.
136 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
138 PATH_EXPR | LOOP_EXPR => None,
139 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
140 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
142 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
144 _ => ast::Expr::cast(node),
151 Replace(ast::ExprStmt),
152 WrapInBlock(SyntaxNode),
156 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
160 .take_while(|it| !ast::Item::can_cast(it.kind()) || ast::MacroCall::can_cast(it.kind()))
163 node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr())
165 if expr.syntax() == &node {
166 cov_mark::hit!(test_extract_var_last_expr);
167 return Some(Anchor::Before(node));
171 if let Some(parent) = node.parent() {
172 if parent.kind() == CLOSURE_EXPR {
173 cov_mark::hit!(test_extract_var_in_closure_no_block);
174 return Some(Anchor::WrapInBlock(node));
176 if parent.kind() == MATCH_ARM {
177 if node.kind() == MATCH_GUARD {
178 cov_mark::hit!(test_extract_var_in_match_guard);
180 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
181 return Some(Anchor::WrapInBlock(node));
186 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
187 if let ast::Stmt::ExprStmt(stmt) = stmt {
188 if stmt.expr().as_ref() == Some(to_extract) {
189 return Some(Anchor::Replace(stmt));
192 return Some(Anchor::Before(node));
198 fn syntax(&self) -> &SyntaxNode {
200 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
201 Anchor::Replace(stmt) => stmt.syntax(),
208 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
213 fn test_extract_var_simple() {
222 let $0var_name = 1 + 1;
229 fn extract_var_in_comment_is_not_applicable() {
230 cov_mark::check!(extract_var_in_comment_is_not_applicable);
231 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
235 fn test_extract_var_expr_stmt() {
236 cov_mark::check!(test_extract_var_expr_stmt);
245 let $0var_name = 1 + 1;
257 let $0var_name = { let x = 0; x };
264 fn test_extract_var_part_of_expr_stmt() {
280 fn test_extract_var_last_expr() {
281 cov_mark::check!(test_extract_var_last_expr);
291 let $0var_name = 1 + 1;
303 fn bar(i: i32) -> i32 {
309 let $0bar = bar(1 + 1);
313 fn bar(i: i32) -> i32 {
321 fn test_extract_var_in_match_arm_no_block() {
322 cov_mark::check!(test_extract_var_in_match_arm_no_block);
328 let tuple = match x {
329 true => ($02 + 2$0, true)
337 let tuple = match x {
338 true => { let $0var_name = 2 + 2; (var_name, true) }
347 fn test_extract_var_in_match_arm_with_block() {
353 let tuple = match x {
365 let tuple = match x {
368 let $0var_name = 2 + y;
379 fn test_extract_var_in_match_guard() {
380 cov_mark::check!(test_extract_var_in_match_guard);
386 () if $010 > 0$0 => 1
393 let $0var_name = 10 > 0;
404 fn test_extract_var_in_closure_no_block() {
405 cov_mark::check!(test_extract_var_in_closure_no_block);
410 let lambda = |x: u32| $0x * 2$0;
415 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
422 fn test_extract_var_in_closure_with_block() {
427 let lambda = |x: u32| { $0x * 2$0 };
432 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
439 fn test_extract_var_path_simple() {
444 let o = $0Some(true)$0;
449 let $0var_name = Some(true);
457 fn test_extract_var_path_method() {
462 let v = $0bar.foo()$0;
467 let $0foo = bar.foo();
475 fn test_extract_var_return() {
485 let $0var_name = 2 + 2;
493 fn test_extract_var_does_not_add_extra_whitespace() {
507 let $0var_name = 2 + 2;
524 let $0var_name = 2 + 2;
549 let $0var_name = 2 + 2;
557 fn test_extract_var_break() {
570 let $0var_name = 2 + 2;
579 fn test_extract_var_for_cast() {
584 let v = $00f32 as u32$0;
589 let $0var_name = 0f32 as u32;
597 fn extract_var_field_shorthand() {
623 fn extract_var_name_from_type() {
637 let $0test = { Test(10) };
645 fn extract_var_name_from_parameter() {
649 fn bar(test: u32, size: u32)
656 fn bar(test: u32, size: u32)
667 fn extract_var_parameter_name_has_precedence_over_type() {
671 struct TextSize(u32);
672 fn bar(test: u32, size: TextSize)
675 bar(1, $0{ TextSize(1+1) }$0);
679 struct TextSize(u32);
680 fn bar(test: u32, size: TextSize)
683 let $0size = { TextSize(1+1) };
691 fn extract_var_name_from_function() {
695 fn is_required(test: u32, size: u32) -> bool
698 $0is_required(1, 2)$0
702 fn is_required(test: u32, size: u32) -> bool
705 let $0is_required = is_required(1, 2);
713 fn extract_var_name_from_method() {
719 fn bar(&self, n: u32) -> u32 { n }
729 fn bar(&self, n: u32) -> u32 { n }
733 let $0bar = S.bar(1);
741 fn extract_var_name_from_method_param() {
747 fn bar(&self, n: u32, size: u32) { n }
757 fn bar(&self, n: u32, size: u32) { n }
769 fn extract_var_name_from_ufcs_method_param() {
775 fn bar(&self, n: u32, size: u32) { n }
779 S::bar(&S, $01 + 1$0, 2)
785 fn bar(&self, n: u32, size: u32) { n }
797 fn extract_var_parameter_name_has_precedence_over_function() {
801 fn bar(test: u32, size: u32)
804 bar(1, $0symbol_size(1, 2)$0);
808 fn bar(test: u32, size: u32)
811 let $0size = symbol_size(1, 2);
819 fn test_extract_var_for_return_not_applicable() {
820 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
824 fn test_extract_var_for_break_not_applicable() {
825 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
829 fn test_extract_var_unit_expr_not_applicable() {
830 check_assist_not_applicable(
844 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
846 fn extract_var_target() {
847 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
854 let tuple = match x {
855 true => ($02 + 2$0, true)
865 fn extract_var_no_block_body() {
866 check_assist_not_applicable(
869 const X: usize = $0100$0;