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 ref_kind: RefKind = if let Some(receiver_type) = get_receiver_type(&ctx, &to_extract) {
56 if receiver_type.is_mutable_reference() {
58 } else if receiver_type.is_reference() {
67 let anchor = Anchor::from(&to_extract)?;
68 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
69 let target = to_extract.syntax().text_range();
71 AssistId("extract_variable", AssistKind::RefactorExtract),
72 "Extract into variable",
76 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
77 Some(field) => field.name_ref(),
81 let mut buf = String::new();
83 let var_name = match &field_shorthand {
84 Some(it) => it.to_string(),
85 None => suggest_name::for_variable(&to_extract, &ctx.sema),
87 let expr_range = match &field_shorthand {
88 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
89 None => to_extract.syntax().text_range(),
92 let reference_modifier = match ref_kind {
93 RefKind::MutRef => "&mut ",
99 Anchor::Before(_) | Anchor::Replace(_) => {
100 format_to!(buf, "let {} = {}", var_name, reference_modifier)
102 Anchor::WrapInBlock(_) => {
103 format_to!(buf, "{{ let {} = {}", var_name, reference_modifier)
106 format_to!(buf, "{}", to_extract.syntax());
108 if let Anchor::Replace(stmt) = anchor {
109 cov_mark::hit!(test_extract_var_expr_stmt);
110 if stmt.semicolon_token().is_none() {
113 match ctx.config.snippet_cap {
116 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
117 edit.replace_snippet(cap, expr_range, snip)
119 None => edit.replace(expr_range, buf),
126 // We want to maintain the indent level,
127 // but we do not want to duplicate possible
128 // extra newlines in the indent block
129 let text = indent.text();
130 if text.starts_with('\n') {
132 buf.push_str(text.trim_start_matches('\n'));
137 edit.replace(expr_range, var_name.clone());
138 let offset = anchor.syntax().text_range().start();
139 match ctx.config.snippet_cap {
142 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
143 edit.insert_snippet(cap, offset, snip)
145 None => edit.insert(offset, buf),
148 if let Anchor::WrapInBlock(_) = anchor {
149 edit.insert(anchor.syntax().text_range().end(), " }");
155 /// Check whether the node is a valid expression which can be extracted to a variable.
156 /// In general that's true for any expression, but in some cases that would produce invalid code.
157 fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
159 PATH_EXPR | LOOP_EXPR => None,
160 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
161 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
163 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
165 _ => ast::Expr::cast(node),
169 fn get_receiver_type(ctx: &AssistContext, expression: &ast::Expr) -> Option<hir::Type> {
170 let receiver = get_receiver(expression.to_owned())?;
171 Some(ctx.sema.type_of_expr(&receiver)?.original())
174 fn get_receiver(expression: ast::Expr) -> Option<ast::Expr> {
176 ast::Expr::FieldExpr(field) if field.expr().is_some() => {
177 let nested_expression = &field.expr()?;
178 get_receiver(nested_expression.to_owned())
180 ast::Expr::PathExpr(_) => Some(expression),
195 Replace(ast::ExprStmt),
196 WrapInBlock(SyntaxNode),
200 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
204 .take_while(|it| !ast::Item::can_cast(it.kind()) || ast::MacroCall::can_cast(it.kind()))
206 if ast::MacroCall::can_cast(node.kind()) {
210 node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr())
212 if expr.syntax() == &node {
213 cov_mark::hit!(test_extract_var_last_expr);
214 return Some(Anchor::Before(node));
218 if let Some(parent) = node.parent() {
219 if parent.kind() == CLOSURE_EXPR {
220 cov_mark::hit!(test_extract_var_in_closure_no_block);
221 return Some(Anchor::WrapInBlock(node));
223 if parent.kind() == MATCH_ARM {
224 if node.kind() == MATCH_GUARD {
225 cov_mark::hit!(test_extract_var_in_match_guard);
227 cov_mark::hit!(test_extract_var_in_match_arm_no_block);
228 return Some(Anchor::WrapInBlock(node));
233 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
234 if let ast::Stmt::ExprStmt(stmt) = stmt {
235 if stmt.expr().as_ref() == Some(to_extract) {
236 return Some(Anchor::Replace(stmt));
239 return Some(Anchor::Before(node));
245 fn syntax(&self) -> &SyntaxNode {
247 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
248 Anchor::Replace(stmt) => stmt.syntax(),
255 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
260 fn test_extract_var_simple() {
269 let $0var_name = 1 + 1;
276 fn extract_var_in_comment_is_not_applicable() {
277 cov_mark::check!(extract_var_in_comment_is_not_applicable);
278 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* $0comment$0 */ 1; }");
282 fn test_extract_var_expr_stmt() {
283 cov_mark::check!(test_extract_var_expr_stmt);
292 let $0var_name = 1 + 1;
304 let $0var_name = { let x = 0; x };
311 fn test_extract_var_part_of_expr_stmt() {
327 fn test_extract_var_last_expr() {
328 cov_mark::check!(test_extract_var_last_expr);
338 let $0var_name = 1 + 1;
350 fn bar(i: i32) -> i32 {
356 let $0bar = bar(1 + 1);
360 fn bar(i: i32) -> i32 {
368 fn test_extract_var_in_match_arm_no_block() {
369 cov_mark::check!(test_extract_var_in_match_arm_no_block);
375 let tuple = match x {
376 true => ($02 + 2$0, true)
384 let tuple = match x {
385 true => { let $0var_name = 2 + 2; (var_name, true) }
394 fn test_extract_var_in_match_arm_with_block() {
400 let tuple = match x {
412 let tuple = match x {
415 let $0var_name = 2 + y;
426 fn test_extract_var_in_match_guard() {
427 cov_mark::check!(test_extract_var_in_match_guard);
433 () if $010 > 0$0 => 1
440 let $0var_name = 10 > 0;
451 fn test_extract_var_in_closure_no_block() {
452 cov_mark::check!(test_extract_var_in_closure_no_block);
457 let lambda = |x: u32| $0x * 2$0;
462 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
469 fn test_extract_var_in_closure_with_block() {
474 let lambda = |x: u32| { $0x * 2$0 };
479 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
486 fn test_extract_var_path_simple() {
491 let o = $0Some(true)$0;
496 let $0var_name = Some(true);
504 fn test_extract_var_path_method() {
509 let v = $0bar.foo()$0;
514 let $0foo = bar.foo();
522 fn test_extract_var_return() {
532 let $0var_name = 2 + 2;
540 fn test_extract_var_does_not_add_extra_whitespace() {
554 let $0var_name = 2 + 2;
571 let $0var_name = 2 + 2;
596 let $0var_name = 2 + 2;
604 fn test_extract_var_break() {
617 let $0var_name = 2 + 2;
626 fn test_extract_var_for_cast() {
631 let v = $00f32 as u32$0;
636 let $0var_name = 0f32 as u32;
644 fn extract_var_field_shorthand() {
670 fn extract_var_name_from_type() {
684 let $0test = { Test(10) };
692 fn extract_var_name_from_parameter() {
696 fn bar(test: u32, size: u32)
703 fn bar(test: u32, size: u32)
714 fn extract_var_parameter_name_has_precedence_over_type() {
718 struct TextSize(u32);
719 fn bar(test: u32, size: TextSize)
722 bar(1, $0{ TextSize(1+1) }$0);
726 struct TextSize(u32);
727 fn bar(test: u32, size: TextSize)
730 let $0size = { TextSize(1+1) };
738 fn extract_var_name_from_function() {
742 fn is_required(test: u32, size: u32) -> bool
745 $0is_required(1, 2)$0
749 fn is_required(test: u32, size: u32) -> bool
752 let $0is_required = is_required(1, 2);
760 fn extract_var_name_from_method() {
766 fn bar(&self, n: u32) -> u32 { n }
776 fn bar(&self, n: u32) -> u32 { n }
780 let $0bar = S.bar(1);
788 fn extract_var_name_from_method_param() {
794 fn bar(&self, n: u32, size: u32) { n }
804 fn bar(&self, n: u32, size: u32) { n }
816 fn extract_var_name_from_ufcs_method_param() {
822 fn bar(&self, n: u32, size: u32) { n }
826 S::bar(&S, $01 + 1$0, 2)
832 fn bar(&self, n: u32, size: u32) { n }
844 fn extract_var_parameter_name_has_precedence_over_function() {
848 fn bar(test: u32, size: u32)
851 bar(1, $0symbol_size(1, 2)$0);
855 fn bar(test: u32, size: u32)
858 let $0size = symbol_size(1, 2);
866 fn extract_macro_call() {
892 fn test_extract_var_for_return_not_applicable() {
893 check_assist_not_applicable(extract_variable, "fn foo() { $0return$0; } ");
897 fn test_extract_var_for_break_not_applicable() {
898 check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
902 fn test_extract_var_unit_expr_not_applicable() {
903 check_assist_not_applicable(
917 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
919 fn extract_var_target() {
920 check_assist_target(extract_variable, "fn foo() -> u32 { $0return 2 + 2$0; }", "2 + 2");
927 let tuple = match x {
928 true => ($02 + 2$0, true)
938 fn extract_var_no_block_body() {
939 check_assist_not_applicable(
942 const X: usize = $0100$0;
948 fn test_extract_var_mutable_reference_parameter() {
965 let $0var_name = &mut s.vec;
972 fn test_extract_var_mutable_reference_parameter_deep_nesting() {
987 $0f.field.field.vec$0.push(0);
1001 let $0var_name = &mut f.field.field.vec;
1008 fn test_extract_var_reference_parameter() {
1015 fn do_thing(&self) {
1025 $0s.sub$0.do_thing();
1031 fn do_thing(&self) {
1048 fn test_extract_var_reference_parameter_deep_nesting() {
1054 fn do_thing(&self) {
1072 $0s.sub.field.field$0.do_thing();
1077 fn do_thing(&self) {
1095 let $0z = &s.sub.field.field;
1102 fn test_extract_var_regular_parameter() {
1109 fn do_thing(&self) {
1119 $0s.sub$0.do_thing();
1125 fn do_thing(&self) {