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(),
79 if let Anchor::WrapInBlock(_) = anchor {
80 format_to!(buf, "{{ let {} = ", var_name);
82 format_to!(buf, "let {} = ", var_name);
84 format_to!(buf, "{}", to_extract.syntax());
86 if let Anchor::Replace(stmt) = anchor {
87 cov_mark::hit!(test_extract_var_expr_stmt);
88 if stmt.semicolon_token().is_none() {
91 match ctx.config.snippet_cap {
94 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
95 edit.replace_snippet(cap, expr_range, snip)
97 None => edit.replace(expr_range, buf),
104 // We want to maintain the indent level,
105 // but we do not want to duplicate possible
106 // extra newlines in the indent block
107 let text = indent.text();
108 if text.starts_with('\n') {
110 buf.push_str(text.trim_start_matches('\n'));
115 edit.replace(expr_range, var_name.clone());
116 let offset = anchor.syntax().text_range().start();
117 match ctx.config.snippet_cap {
120 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
121 edit.insert_snippet(cap, offset, snip)
123 None => edit.insert(offset, buf),
126 if let Anchor::WrapInBlock(_) = anchor {
127 edit.insert(anchor.syntax().text_range().end(), " }");
133 /// Check whether the node is a valid expression which can be extracted to a variable.
134 /// In general that's true for any expression, but in some cases that would produce invalid code.
135 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
137 PATH_EXPR | LOOP_EXPR => None,
138 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
139 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
141 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
143 _ => ast::Expr::cast(node),
150 Replace(ast::ExprStmt),
151 WrapInBlock(SyntaxNode),
155 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
159 .take_while(|it| !ast::Item::can_cast(it.kind()) || ast::MacroCall::can_cast(it.kind()))
162 node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr())
164 if expr.syntax() == &node {
165 cov_mark::hit!(test_extract_var_last_expr);
166 return Some(Anchor::Before(node));
170 if let Some(parent) = node.parent() {
171 if parent.kind() == CLOSURE_EXPR {
172 cov_mark::hit!(test_extract_var_in_closure_no_block);
173 return Some(Anchor::WrapInBlock(node));
175 if parent.kind() == MATCH_ARM {
176 if node.kind() == MATCH_GUARD {
177 cov_mark::hit!(test_extract_var_in_match_guard);
179 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
180 return Some(Anchor::WrapInBlock(node));
185 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
186 if let ast::Stmt::ExprStmt(stmt) = stmt {
187 if stmt.expr().as_ref() == Some(to_extract) {
188 return Some(Anchor::Replace(stmt));
191 return Some(Anchor::Before(node));
197 fn syntax(&self) -> &SyntaxNode {
199 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
200 Anchor::Replace(stmt) => stmt.syntax(),
207 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
212 fn test_extract_var_simple() {
221 let $0var_name = 1 + 1;
228 fn extract_var_in_comment_is_not_applicable() {
229 cov_mark::check!(extract_var_in_comment_is_not_applicable);
230 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
234 fn test_extract_var_expr_stmt() {
235 cov_mark::check!(test_extract_var_expr_stmt);
244 let $0var_name = 1 + 1;
256 let $0var_name = { let x = 0; x };
263 fn test_extract_var_part_of_expr_stmt() {
279 fn test_extract_var_last_expr() {
280 cov_mark::check!(test_extract_var_last_expr);
290 let $0var_name = 1 + 1;
302 fn bar(i: i32) -> i32 {
308 let $0bar = bar(1 + 1);
312 fn bar(i: i32) -> i32 {
320 fn test_extract_var_in_match_arm_no_block() {
321 cov_mark::check!(test_extract_var_in_match_arm_no_block);
327 let tuple = match x {
328 true => ($02 + 2$0, true)
336 let tuple = match x {
337 true => { let $0var_name = 2 + 2; (var_name, true) }
346 fn test_extract_var_in_match_arm_with_block() {
352 let tuple = match x {
364 let tuple = match x {
367 let $0var_name = 2 + y;
378 fn test_extract_var_in_match_guard() {
379 cov_mark::check!(test_extract_var_in_match_guard);
385 () if $010 > 0$0 => 1
392 let $0var_name = 10 > 0;
403 fn test_extract_var_in_closure_no_block() {
404 cov_mark::check!(test_extract_var_in_closure_no_block);
409 let lambda = |x: u32| $0x * 2$0;
414 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
421 fn test_extract_var_in_closure_with_block() {
426 let lambda = |x: u32| { $0x * 2$0 };
431 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
438 fn test_extract_var_path_simple() {
443 let o = $0Some(true)$0;
448 let $0var_name = Some(true);
456 fn test_extract_var_path_method() {
461 let v = $0bar.foo()$0;
466 let $0foo = bar.foo();
474 fn test_extract_var_return() {
484 let $0var_name = 2 + 2;
492 fn test_extract_var_does_not_add_extra_whitespace() {
506 let $0var_name = 2 + 2;
523 let $0var_name = 2 + 2;
548 let $0var_name = 2 + 2;
556 fn test_extract_var_break() {
569 let $0var_name = 2 + 2;
578 fn test_extract_var_for_cast() {
583 let v = $00f32 as u32$0;
588 let $0var_name = 0f32 as u32;
596 fn extract_var_field_shorthand() {
622 fn extract_var_name_from_type() {
636 let $0test = { Test(10) };
644 fn extract_var_name_from_parameter() {
648 fn bar(test: u32, size: u32)
655 fn bar(test: u32, size: u32)
666 fn extract_var_parameter_name_has_precedence_over_type() {
670 struct TextSize(u32);
671 fn bar(test: u32, size: TextSize)
674 bar(1, $0{ TextSize(1+1) }$0);
678 struct TextSize(u32);
679 fn bar(test: u32, size: TextSize)
682 let $0size = { TextSize(1+1) };
690 fn extract_var_name_from_function() {
694 fn is_required(test: u32, size: u32) -> bool
697 $0is_required(1, 2)$0
701 fn is_required(test: u32, size: u32) -> bool
704 let $0is_required = is_required(1, 2);
712 fn extract_var_name_from_method() {
718 fn bar(&self, n: u32) -> u32 { n }
728 fn bar(&self, n: u32) -> u32 { n }
732 let $0bar = S.bar(1);
740 fn extract_var_name_from_method_param() {
746 fn bar(&self, n: u32, size: u32) { n }
756 fn bar(&self, n: u32, size: u32) { n }
768 fn extract_var_name_from_ufcs_method_param() {
774 fn bar(&self, n: u32, size: u32) { n }
778 S::bar(&S, $01 + 1$0, 2)
784 fn bar(&self, n: u32, size: u32) { n }
796 fn extract_var_parameter_name_has_precedence_over_function() {
800 fn bar(test: u32, size: u32)
803 bar(1, $0symbol_size(1, 2)$0);
807 fn bar(test: u32, size: u32)
810 let $0size = symbol_size(1, 2);
818 fn test_extract_var_for_return_not_applicable() {
819 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
823 fn test_extract_var_for_break_not_applicable() {
824 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
828 fn test_extract_var_unit_expr_not_applicable() {
829 check_assist_not_applicable(
843 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
845 fn extract_var_target() {
846 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
853 let tuple = match x {
854 true => ($02 + 2$0, true)
864 fn extract_var_no_block_body() {
865 check_assist_not_applicable(
868 const X: usize = $0100$0;