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()))
163 if ast::MacroCall::can_cast(node.kind()) {
167 node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr())
169 if expr.syntax() == &node {
170 cov_mark::hit!(test_extract_var_last_expr);
171 return Some(Anchor::Before(node));
175 if let Some(parent) = node.parent() {
176 if parent.kind() == CLOSURE_EXPR {
177 cov_mark::hit!(test_extract_var_in_closure_no_block);
178 return Some(Anchor::WrapInBlock(node));
180 if parent.kind() == MATCH_ARM {
181 if node.kind() == MATCH_GUARD {
182 cov_mark::hit!(test_extract_var_in_match_guard);
184 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
185 return Some(Anchor::WrapInBlock(node));
190 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
191 if let ast::Stmt::ExprStmt(stmt) = stmt {
192 if stmt.expr().as_ref() == Some(to_extract) {
193 return Some(Anchor::Replace(stmt));
196 return Some(Anchor::Before(node));
202 fn syntax(&self) -> &SyntaxNode {
204 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
205 Anchor::Replace(stmt) => stmt.syntax(),
212 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
217 fn test_extract_var_simple() {
226 let $0var_name = 1 + 1;
233 fn extract_var_in_comment_is_not_applicable() {
234 cov_mark::check!(extract_var_in_comment_is_not_applicable);
235 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
239 fn test_extract_var_expr_stmt() {
240 cov_mark::check!(test_extract_var_expr_stmt);
249 let $0var_name = 1 + 1;
261 let $0var_name = { let x = 0; x };
268 fn test_extract_var_part_of_expr_stmt() {
284 fn test_extract_var_last_expr() {
285 cov_mark::check!(test_extract_var_last_expr);
295 let $0var_name = 1 + 1;
307 fn bar(i: i32) -> i32 {
313 let $0bar = bar(1 + 1);
317 fn bar(i: i32) -> i32 {
325 fn test_extract_var_in_match_arm_no_block() {
326 cov_mark::check!(test_extract_var_in_match_arm_no_block);
332 let tuple = match x {
333 true => ($02 + 2$0, true)
341 let tuple = match x {
342 true => { let $0var_name = 2 + 2; (var_name, true) }
351 fn test_extract_var_in_match_arm_with_block() {
357 let tuple = match x {
369 let tuple = match x {
372 let $0var_name = 2 + y;
383 fn test_extract_var_in_match_guard() {
384 cov_mark::check!(test_extract_var_in_match_guard);
390 () if $010 > 0$0 => 1
397 let $0var_name = 10 > 0;
408 fn test_extract_var_in_closure_no_block() {
409 cov_mark::check!(test_extract_var_in_closure_no_block);
414 let lambda = |x: u32| $0x * 2$0;
419 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
426 fn test_extract_var_in_closure_with_block() {
431 let lambda = |x: u32| { $0x * 2$0 };
436 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
443 fn test_extract_var_path_simple() {
448 let o = $0Some(true)$0;
453 let $0var_name = Some(true);
461 fn test_extract_var_path_method() {
466 let v = $0bar.foo()$0;
471 let $0foo = bar.foo();
479 fn test_extract_var_return() {
489 let $0var_name = 2 + 2;
497 fn test_extract_var_does_not_add_extra_whitespace() {
511 let $0var_name = 2 + 2;
528 let $0var_name = 2 + 2;
553 let $0var_name = 2 + 2;
561 fn test_extract_var_break() {
574 let $0var_name = 2 + 2;
583 fn test_extract_var_for_cast() {
588 let v = $00f32 as u32$0;
593 let $0var_name = 0f32 as u32;
601 fn extract_var_field_shorthand() {
627 fn extract_var_name_from_type() {
641 let $0test = { Test(10) };
649 fn extract_var_name_from_parameter() {
653 fn bar(test: u32, size: u32)
660 fn bar(test: u32, size: u32)
671 fn extract_var_parameter_name_has_precedence_over_type() {
675 struct TextSize(u32);
676 fn bar(test: u32, size: TextSize)
679 bar(1, $0{ TextSize(1+1) }$0);
683 struct TextSize(u32);
684 fn bar(test: u32, size: TextSize)
687 let $0size = { TextSize(1+1) };
695 fn extract_var_name_from_function() {
699 fn is_required(test: u32, size: u32) -> bool
702 $0is_required(1, 2)$0
706 fn is_required(test: u32, size: u32) -> bool
709 let $0is_required = is_required(1, 2);
717 fn extract_var_name_from_method() {
723 fn bar(&self, n: u32) -> u32 { n }
733 fn bar(&self, n: u32) -> u32 { n }
737 let $0bar = S.bar(1);
745 fn extract_var_name_from_method_param() {
751 fn bar(&self, n: u32, size: u32) { n }
761 fn bar(&self, n: u32, size: u32) { n }
773 fn extract_var_name_from_ufcs_method_param() {
779 fn bar(&self, n: u32, size: u32) { n }
783 S::bar(&S, $01 + 1$0, 2)
789 fn bar(&self, n: u32, size: u32) { n }
801 fn extract_var_parameter_name_has_precedence_over_function() {
805 fn bar(test: u32, size: u32)
808 bar(1, $0symbol_size(1, 2)$0);
812 fn bar(test: u32, size: u32)
815 let $0size = symbol_size(1, 2);
823 fn extract_macro_call() {
849 fn test_extract_var_for_return_not_applicable() {
850 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
854 fn test_extract_var_for_break_not_applicable() {
855 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
859 fn test_extract_var_unit_expr_not_applicable() {
860 check_assist_not_applicable(
874 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
876 fn extract_var_target() {
877 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
884 let tuple = match x {
885 true => ($02 + 2$0, true)
895 fn extract_var_no_block_body() {
896 check_assist_not_applicable(
899 const X: usize = $0100$0;