aboutsummaryrefslogtreecommitdiff
path: root/crates/assists/src/handlers/extract_function.rs
diff options
context:
space:
mode:
authorChetan Khilosiya <[email protected]>2021-02-22 18:47:48 +0000
committerChetan Khilosiya <[email protected]>2021-02-22 19:29:16 +0000
commite4756cb4f6e66097638b9d101589358976be2ba8 (patch)
treeb6ca0ae6b45b57834476ae0f9985cec3a6bd9090 /crates/assists/src/handlers/extract_function.rs
parent8687053b118f47ce1a4962d0baa19b22d40d2758 (diff)
7526: Rename crate assists to ide_assists.
Diffstat (limited to 'crates/assists/src/handlers/extract_function.rs')
-rw-r--r--crates/assists/src/handlers/extract_function.rs3378
1 files changed, 0 insertions, 3378 deletions
diff --git a/crates/assists/src/handlers/extract_function.rs b/crates/assists/src/handlers/extract_function.rs
deleted file mode 100644
index 9f34cc725..000000000
--- a/crates/assists/src/handlers/extract_function.rs
+++ /dev/null
@@ -1,3378 +0,0 @@
1use std::iter;
2
3use ast::make;
4use either::Either;
5use hir::{HirDisplay, Local};
6use ide_db::{
7 defs::{Definition, NameRefClass},
8 search::{FileReference, ReferenceAccess, SearchScope},
9};
10use itertools::Itertools;
11use stdx::format_to;
12use syntax::{
13 algo::SyntaxRewriter,
14 ast::{
15 self,
16 edit::{AstNodeEdit, IndentLevel},
17 AstNode,
18 },
19 SyntaxElement,
20 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR},
21 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
22};
23use test_utils::mark;
24
25use crate::{
26 assist_context::{AssistContext, Assists},
27 AssistId,
28};
29
30// Assist: extract_function
31//
32// Extracts selected statements into new function.
33//
34// ```
35// fn main() {
36// let n = 1;
37// $0let m = n + 2;
38// let k = m + n;$0
39// let g = 3;
40// }
41// ```
42// ->
43// ```
44// fn main() {
45// let n = 1;
46// fun_name(n);
47// let g = 3;
48// }
49//
50// fn $0fun_name(n: i32) {
51// let m = n + 2;
52// let k = m + n;
53// }
54// ```
55pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
56 if ctx.frange.range.is_empty() {
57 return None;
58 }
59
60 let node = ctx.covering_element();
61 if node.kind() == COMMENT {
62 mark::hit!(extract_function_in_comment_is_not_applicable);
63 return None;
64 }
65
66 let node = element_to_node(node);
67
68 let body = extraction_target(&node, ctx.frange.range)?;
69
70 let vars_used_in_body = vars_used_in_body(ctx, &body);
71 let self_param = self_param_from_usages(ctx, &body, &vars_used_in_body);
72
73 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
74 let insert_after = scope_for_fn_insertion(&body, anchor)?;
75 let module = ctx.sema.scope(&insert_after).module()?;
76
77 let vars_defined_in_body_and_outlive = vars_defined_in_body_and_outlive(ctx, &body);
78 let ret_ty = body_return_ty(ctx, &body)?;
79
80 // FIXME: we compute variables that outlive here just to check `never!` condition
81 // this requires traversing whole `body` (cheap) and finding all references (expensive)
82 // maybe we can move this check to `edit` closure somehow?
83 if stdx::never!(!vars_defined_in_body_and_outlive.is_empty() && !ret_ty.is_unit()) {
84 // We should not have variables that outlive body if we have expression block
85 return None;
86 }
87 let control_flow = external_control_flow(ctx, &body)?;
88
89 let target_range = body.text_range();
90
91 acc.add(
92 AssistId("extract_function", crate::AssistKind::RefactorExtract),
93 "Extract into function",
94 target_range,
95 move |builder| {
96 let params = extracted_function_params(ctx, &body, &vars_used_in_body);
97
98 let fun = Function {
99 name: "fun_name".to_string(),
100 self_param: self_param.map(|(_, pat)| pat),
101 params,
102 control_flow,
103 ret_ty,
104 body,
105 vars_defined_in_body_and_outlive,
106 };
107
108 let new_indent = IndentLevel::from_node(&insert_after);
109 let old_indent = fun.body.indent_level();
110
111 builder.replace(target_range, format_replacement(ctx, &fun, old_indent));
112
113 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
114 let insert_offset = insert_after.text_range().end();
115 builder.insert(insert_offset, fn_def);
116 },
117 )
118}
119
120fn external_control_flow(ctx: &AssistContext, body: &FunctionBody) -> Option<ControlFlow> {
121 let mut ret_expr = None;
122 let mut try_expr = None;
123 let mut break_expr = None;
124 let mut continue_expr = None;
125 let (syntax, text_range) = match body {
126 FunctionBody::Expr(expr) => (expr.syntax(), expr.syntax().text_range()),
127 FunctionBody::Span { parent, text_range } => (parent.syntax(), *text_range),
128 };
129
130 let mut nested_loop = None;
131 let mut nested_scope = None;
132
133 for e in syntax.preorder() {
134 let e = match e {
135 WalkEvent::Enter(e) => e,
136 WalkEvent::Leave(e) => {
137 if nested_loop.as_ref() == Some(&e) {
138 nested_loop = None;
139 }
140 if nested_scope.as_ref() == Some(&e) {
141 nested_scope = None;
142 }
143 continue;
144 }
145 };
146 if nested_scope.is_some() {
147 continue;
148 }
149 if !text_range.contains_range(e.text_range()) {
150 continue;
151 }
152 match e.kind() {
153 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
154 if nested_loop.is_none() {
155 nested_loop = Some(e);
156 }
157 }
158 SyntaxKind::FN
159 | SyntaxKind::CONST
160 | SyntaxKind::STATIC
161 | SyntaxKind::IMPL
162 | SyntaxKind::MODULE => {
163 if nested_scope.is_none() {
164 nested_scope = Some(e);
165 }
166 }
167 SyntaxKind::RETURN_EXPR => {
168 ret_expr = Some(ast::ReturnExpr::cast(e).unwrap());
169 }
170 SyntaxKind::TRY_EXPR => {
171 try_expr = Some(ast::TryExpr::cast(e).unwrap());
172 }
173 SyntaxKind::BREAK_EXPR if nested_loop.is_none() => {
174 break_expr = Some(ast::BreakExpr::cast(e).unwrap());
175 }
176 SyntaxKind::CONTINUE_EXPR if nested_loop.is_none() => {
177 continue_expr = Some(ast::ContinueExpr::cast(e).unwrap());
178 }
179 _ => {}
180 }
181 }
182
183 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
184 (Some(e), None, None, None) => {
185 let func = e.syntax().ancestors().find_map(ast::Fn::cast)?;
186 let def = ctx.sema.to_def(&func)?;
187 let ret_ty = def.ret_type(ctx.db());
188 let kind = try_kind_of_ty(ret_ty, ctx)?;
189
190 Some(FlowKind::Try { kind })
191 }
192 (Some(_), Some(r), None, None) => match r.expr() {
193 Some(expr) => {
194 if let Some(kind) = expr_err_kind(&expr, ctx) {
195 Some(FlowKind::TryReturn { expr, kind })
196 } else {
197 mark::hit!(external_control_flow_try_and_return_non_err);
198 return None;
199 }
200 }
201 None => return None,
202 },
203 (Some(_), _, _, _) => {
204 mark::hit!(external_control_flow_try_and_bc);
205 return None;
206 }
207 (None, Some(r), None, None) => match r.expr() {
208 Some(expr) => Some(FlowKind::ReturnValue(expr)),
209 None => Some(FlowKind::Return),
210 },
211 (None, Some(_), _, _) => {
212 mark::hit!(external_control_flow_return_and_bc);
213 return None;
214 }
215 (None, None, Some(_), Some(_)) => {
216 mark::hit!(external_control_flow_break_and_continue);
217 return None;
218 }
219 (None, None, Some(b), None) => match b.expr() {
220 Some(expr) => Some(FlowKind::BreakValue(expr)),
221 None => Some(FlowKind::Break),
222 },
223 (None, None, None, Some(_)) => Some(FlowKind::Continue),
224 (None, None, None, None) => None,
225 };
226
227 Some(ControlFlow { kind })
228}
229
230/// Checks is expr is `Err(_)` or `None`
231fn expr_err_kind(expr: &ast::Expr, ctx: &AssistContext) -> Option<TryKind> {
232 let func_name = match expr {
233 ast::Expr::CallExpr(call_expr) => call_expr.expr()?,
234 ast::Expr::PathExpr(_) => expr.clone(),
235 _ => return None,
236 };
237 let text = func_name.syntax().text();
238
239 if text == "Err" {
240 Some(TryKind::Result { ty: ctx.sema.type_of_expr(expr)? })
241 } else if text == "None" {
242 Some(TryKind::Option)
243 } else {
244 None
245 }
246}
247
248#[derive(Debug)]
249struct Function {
250 name: String,
251 self_param: Option<ast::SelfParam>,
252 params: Vec<Param>,
253 control_flow: ControlFlow,
254 ret_ty: RetType,
255 body: FunctionBody,
256 vars_defined_in_body_and_outlive: Vec<Local>,
257}
258
259#[derive(Debug)]
260struct Param {
261 var: Local,
262 ty: hir::Type,
263 has_usages_afterwards: bool,
264 has_mut_inside_body: bool,
265 is_copy: bool,
266}
267
268#[derive(Debug)]
269struct ControlFlow {
270 kind: Option<FlowKind>,
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274enum ParamKind {
275 Value,
276 MutValue,
277 SharedRef,
278 MutRef,
279}
280
281#[derive(Debug, Eq, PartialEq)]
282enum FunType {
283 Unit,
284 Single(hir::Type),
285 Tuple(Vec<hir::Type>),
286}
287
288impl Function {
289 fn return_type(&self, ctx: &AssistContext) -> FunType {
290 match &self.ret_ty {
291 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
292 RetType::Expr(ty) => FunType::Single(ty.clone()),
293 RetType::Stmt => match self.vars_defined_in_body_and_outlive.as_slice() {
294 [] => FunType::Unit,
295 [var] => FunType::Single(var.ty(ctx.db())),
296 vars => {
297 let types = vars.iter().map(|v| v.ty(ctx.db())).collect();
298 FunType::Tuple(types)
299 }
300 },
301 }
302 }
303}
304
305impl ParamKind {
306 fn is_ref(&self) -> bool {
307 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
308 }
309}
310
311impl Param {
312 fn kind(&self) -> ParamKind {
313 match (self.has_usages_afterwards, self.has_mut_inside_body, self.is_copy) {
314 (true, true, _) => ParamKind::MutRef,
315 (true, false, false) => ParamKind::SharedRef,
316 (false, true, _) => ParamKind::MutValue,
317 (true, false, true) | (false, false, _) => ParamKind::Value,
318 }
319 }
320
321 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
322 let var = path_expr_from_local(ctx, self.var);
323 match self.kind() {
324 ParamKind::Value | ParamKind::MutValue => var,
325 ParamKind::SharedRef => make::expr_ref(var, false),
326 ParamKind::MutRef => make::expr_ref(var, true),
327 }
328 }
329
330 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
331 let var = self.var.name(ctx.db()).unwrap().to_string();
332 let var_name = make::name(&var);
333 let pat = match self.kind() {
334 ParamKind::MutValue => make::ident_mut_pat(var_name),
335 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
336 make::ident_pat(var_name)
337 }
338 };
339
340 let ty = make_ty(&self.ty, ctx, module);
341 let ty = match self.kind() {
342 ParamKind::Value | ParamKind::MutValue => ty,
343 ParamKind::SharedRef => make::ty_ref(ty, false),
344 ParamKind::MutRef => make::ty_ref(ty, true),
345 };
346
347 make::param(pat.into(), ty)
348 }
349}
350
351/// Control flow that is exported from extracted function
352///
353/// E.g.:
354/// ```rust,no_run
355/// loop {
356/// $0
357/// if 42 == 42 {
358/// break;
359/// }
360/// $0
361/// }
362/// ```
363#[derive(Debug, Clone)]
364enum FlowKind {
365 /// Return without value (`return;`)
366 Return,
367 /// Return with value (`return $expr;`)
368 ReturnValue(ast::Expr),
369 Try {
370 kind: TryKind,
371 },
372 TryReturn {
373 expr: ast::Expr,
374 kind: TryKind,
375 },
376 /// Break without value (`return;`)
377 Break,
378 /// Break with value (`break $expr;`)
379 BreakValue(ast::Expr),
380 /// Continue
381 Continue,
382}
383
384#[derive(Debug, Clone)]
385enum TryKind {
386 Option,
387 Result { ty: hir::Type },
388}
389
390impl FlowKind {
391 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
392 match self {
393 FlowKind::Return | FlowKind::ReturnValue(_) => make::expr_return(expr),
394 FlowKind::Break | FlowKind::BreakValue(_) => make::expr_break(expr),
395 FlowKind::Try { .. } | FlowKind::TryReturn { .. } => {
396 stdx::never!("cannot have result handler with try");
397 expr.unwrap_or_else(|| make::expr_return(None))
398 }
399 FlowKind::Continue => {
400 stdx::always!(expr.is_none(), "continue with value is not possible");
401 make::expr_continue()
402 }
403 }
404 }
405
406 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
407 match self {
408 FlowKind::ReturnValue(expr)
409 | FlowKind::BreakValue(expr)
410 | FlowKind::TryReturn { expr, .. } => ctx.sema.type_of_expr(expr),
411 FlowKind::Try { .. } => {
412 stdx::never!("try does not have defined expr_ty");
413 None
414 }
415 FlowKind::Return | FlowKind::Break | FlowKind::Continue => None,
416 }
417 }
418}
419
420fn try_kind_of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
421 if ty.is_unknown() {
422 // We favour Result for `expr?`
423 return Some(TryKind::Result { ty });
424 }
425 let adt = ty.as_adt()?;
426 let name = adt.name(ctx.db());
427 // FIXME: use lang items to determine if it is std type or user defined
428 // E.g. if user happens to define type named `Option`, we would have false positive
429 match name.to_string().as_str() {
430 "Option" => Some(TryKind::Option),
431 "Result" => Some(TryKind::Result { ty }),
432 _ => None,
433 }
434}
435
436#[derive(Debug)]
437enum RetType {
438 Expr(hir::Type),
439 Stmt,
440}
441
442impl RetType {
443 fn is_unit(&self) -> bool {
444 match self {
445 RetType::Expr(ty) => ty.is_unit(),
446 RetType::Stmt => true,
447 }
448 }
449}
450
451/// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
452#[derive(Debug)]
453enum FunctionBody {
454 Expr(ast::Expr),
455 Span { parent: ast::BlockExpr, text_range: TextRange },
456}
457
458impl FunctionBody {
459 fn from_whole_node(node: SyntaxNode) -> Option<Self> {
460 match node.kind() {
461 PATH_EXPR => None,
462 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
463 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
464 BLOCK_EXPR => ast::BlockExpr::cast(node)
465 .filter(|it| it.is_standalone())
466 .map(Into::into)
467 .map(Self::Expr),
468 _ => ast::Expr::cast(node).map(Self::Expr),
469 }
470 }
471
472 fn from_range(node: SyntaxNode, text_range: TextRange) -> Option<FunctionBody> {
473 let block = ast::BlockExpr::cast(node)?;
474 Some(Self::Span { parent: block, text_range })
475 }
476
477 fn indent_level(&self) -> IndentLevel {
478 match &self {
479 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
480 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
481 }
482 }
483
484 fn tail_expr(&self) -> Option<ast::Expr> {
485 match &self {
486 FunctionBody::Expr(expr) => Some(expr.clone()),
487 FunctionBody::Span { parent, text_range } => {
488 let tail_expr = parent.tail_expr()?;
489 if text_range.contains_range(tail_expr.syntax().text_range()) {
490 Some(tail_expr)
491 } else {
492 None
493 }
494 }
495 }
496 }
497
498 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
499 match self {
500 FunctionBody::Expr(expr) => Either::Right(expr.syntax().descendants()),
501 FunctionBody::Span { parent, text_range } => Either::Left(
502 parent
503 .syntax()
504 .descendants()
505 .filter(move |it| text_range.contains_range(it.text_range())),
506 ),
507 }
508 }
509
510 fn text_range(&self) -> TextRange {
511 match self {
512 FunctionBody::Expr(expr) => expr.syntax().text_range(),
513 FunctionBody::Span { parent: _, text_range } => *text_range,
514 }
515 }
516
517 fn contains_range(&self, range: TextRange) -> bool {
518 self.text_range().contains_range(range)
519 }
520
521 fn preceedes_range(&self, range: TextRange) -> bool {
522 self.text_range().end() <= range.start()
523 }
524
525 fn contains_node(&self, node: &SyntaxNode) -> bool {
526 self.contains_range(node.text_range())
527 }
528}
529
530impl HasTokenAtOffset for FunctionBody {
531 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
532 match self {
533 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
534 FunctionBody::Span { parent, text_range } => {
535 match parent.syntax().token_at_offset(offset) {
536 TokenAtOffset::None => TokenAtOffset::None,
537 TokenAtOffset::Single(t) => {
538 if text_range.contains_range(t.text_range()) {
539 TokenAtOffset::Single(t)
540 } else {
541 TokenAtOffset::None
542 }
543 }
544 TokenAtOffset::Between(a, b) => {
545 match (
546 text_range.contains_range(a.text_range()),
547 text_range.contains_range(b.text_range()),
548 ) {
549 (true, true) => TokenAtOffset::Between(a, b),
550 (true, false) => TokenAtOffset::Single(a),
551 (false, true) => TokenAtOffset::Single(b),
552 (false, false) => TokenAtOffset::None,
553 }
554 }
555 }
556 }
557 }
558 }
559}
560
561/// node or token's parent
562fn element_to_node(node: SyntaxElement) -> SyntaxNode {
563 match node {
564 syntax::NodeOrToken::Node(n) => n,
565 syntax::NodeOrToken::Token(t) => t.parent(),
566 }
567}
568
569/// Try to guess what user wants to extract
570///
571/// We have basically have two cases:
572/// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
573/// Then we can use `ast::Expr`
574/// * We want a few statements for a block. E.g.
575/// ```rust,no_run
576/// fn foo() -> i32 {
577/// let m = 1;
578/// $0
579/// let n = 2;
580/// let k = 3;
581/// k + n
582/// $0
583/// }
584/// ```
585///
586fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
587 // we have selected exactly the expr node
588 // wrap it before anything else
589 if node.text_range() == selection_range {
590 let body = FunctionBody::from_whole_node(node.clone());
591 if body.is_some() {
592 return body;
593 }
594 }
595
596 // we have selected a few statements in a block
597 // so covering_element returns the whole block
598 if node.kind() == BLOCK_EXPR {
599 let body = FunctionBody::from_range(node.clone(), selection_range);
600 if body.is_some() {
601 return body;
602 }
603 }
604
605 // we have selected single statement
606 // `from_whole_node` failed because (let) statement is not and expression
607 // so we try to expand covering_element to parent and repeat the previous
608 if let Some(parent) = node.parent() {
609 if parent.kind() == BLOCK_EXPR {
610 let body = FunctionBody::from_range(parent, selection_range);
611 if body.is_some() {
612 return body;
613 }
614 }
615 }
616
617 // select the closest containing expr (both ifs are used)
618 std::iter::once(node.clone()).chain(node.ancestors()).find_map(FunctionBody::from_whole_node)
619}
620
621/// list local variables that are referenced in `body`
622fn vars_used_in_body(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
623 // FIXME: currently usages inside macros are not found
624 body.descendants()
625 .filter_map(ast::NameRef::cast)
626 .filter_map(|name_ref| NameRefClass::classify(&ctx.sema, &name_ref))
627 .map(|name_kind| name_kind.referenced(ctx.db()))
628 .filter_map(|definition| match definition {
629 Definition::Local(local) => Some(local),
630 _ => None,
631 })
632 .unique()
633 .collect()
634}
635
636/// find `self` param, that was not defined inside `body`
637///
638/// It should skip `self` params from impls inside `body`
639fn self_param_from_usages(
640 ctx: &AssistContext,
641 body: &FunctionBody,
642 vars_used_in_body: &[Local],
643) -> Option<(Local, ast::SelfParam)> {
644 let mut iter = vars_used_in_body
645 .iter()
646 .filter(|var| var.is_self(ctx.db()))
647 .map(|var| (var, var.source(ctx.db())))
648 .filter(|(_, src)| is_defined_before(ctx, body, src))
649 .filter_map(|(&node, src)| match src.value {
650 Either::Right(it) => Some((node, it)),
651 Either::Left(_) => {
652 stdx::never!(false, "Local::is_self returned true, but source is IdentPat");
653 None
654 }
655 });
656
657 let self_param = iter.next();
658 stdx::always!(
659 iter.next().is_none(),
660 "body references two different self params, both defined outside"
661 );
662
663 self_param
664}
665
666/// find variables that should be extracted as params
667///
668/// Computes additional info that affects param type and mutability
669fn extracted_function_params(
670 ctx: &AssistContext,
671 body: &FunctionBody,
672 vars_used_in_body: &[Local],
673) -> Vec<Param> {
674 vars_used_in_body
675 .iter()
676 .filter(|var| !var.is_self(ctx.db()))
677 .map(|node| (node, node.source(ctx.db())))
678 .filter(|(_, src)| is_defined_before(ctx, body, src))
679 .filter_map(|(&node, src)| {
680 if src.value.is_left() {
681 Some(node)
682 } else {
683 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
684 None
685 }
686 })
687 .map(|var| {
688 let usages = LocalUsages::find(ctx, var);
689 let ty = var.ty(ctx.db());
690 let is_copy = ty.is_copy(ctx.db());
691 Param {
692 var,
693 ty,
694 has_usages_afterwards: has_usages_after_body(&usages, body),
695 has_mut_inside_body: has_exclusive_usages(ctx, &usages, body),
696 is_copy,
697 }
698 })
699 .collect()
700}
701
702fn has_usages_after_body(usages: &LocalUsages, body: &FunctionBody) -> bool {
703 usages.iter().any(|reference| body.preceedes_range(reference.range))
704}
705
706/// checks if relevant var is used with `&mut` access inside body
707fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
708 usages
709 .iter()
710 .filter(|reference| body.contains_range(reference.range))
711 .any(|reference| reference_is_exclusive(reference, body, ctx))
712}
713
714/// checks if this reference requires `&mut` access inside body
715fn reference_is_exclusive(
716 reference: &FileReference,
717 body: &FunctionBody,
718 ctx: &AssistContext,
719) -> bool {
720 // we directly modify variable with set: `n = 0`, `n += 1`
721 if reference.access == Some(ReferenceAccess::Write) {
722 return true;
723 }
724
725 // we take `&mut` reference to variable: `&mut v`
726 let path = match path_element_of_reference(body, reference) {
727 Some(path) => path,
728 None => return false,
729 };
730
731 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
732}
733
734/// checks if this expr requires `&mut` access, recurses on field access
735fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
736 let parent = expr.syntax().parent()?;
737
738 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
739 if bin_expr.op_kind()?.is_assignment() {
740 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
741 }
742 return Some(false);
743 }
744
745 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
746 return Some(ref_expr.mut_token().is_some());
747 }
748
749 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
750 let func = ctx.sema.resolve_method_call(&method_call)?;
751 let self_param = func.self_param(ctx.db())?;
752 let access = self_param.access(ctx.db());
753
754 return Some(matches!(access, hir::Access::Exclusive));
755 }
756
757 if let Some(field) = ast::FieldExpr::cast(parent) {
758 return expr_require_exclusive_access(ctx, &field.into());
759 }
760
761 Some(false)
762}
763
764/// Container of local varaible usages
765///
766/// Semanticall same as `UsageSearchResult`, but provides more convenient interface
767struct LocalUsages(ide_db::search::UsageSearchResult);
768
769impl LocalUsages {
770 fn find(ctx: &AssistContext, var: Local) -> Self {
771 Self(
772 Definition::Local(var)
773 .usages(&ctx.sema)
774 .in_scope(SearchScope::single_file(ctx.frange.file_id))
775 .all(),
776 )
777 }
778
779 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
780 self.0.iter().flat_map(|(_, rs)| rs.iter())
781 }
782}
783
784trait HasTokenAtOffset {
785 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
786}
787
788impl HasTokenAtOffset for SyntaxNode {
789 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
790 SyntaxNode::token_at_offset(&self, offset)
791 }
792}
793
794/// find relevant `ast::PathExpr` for reference
795///
796/// # Preconditions
797///
798/// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
799fn path_element_of_reference(
800 node: &dyn HasTokenAtOffset,
801 reference: &FileReference,
802) -> Option<ast::Expr> {
803 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
804 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
805 None
806 })?;
807 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
808 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
809 None
810 })?;
811 stdx::always!(matches!(path, ast::Expr::PathExpr(_)));
812 Some(path)
813}
814
815/// list local variables defined inside `body`
816fn vars_defined_in_body(body: &FunctionBody, ctx: &AssistContext) -> Vec<Local> {
817 // FIXME: this doesn't work well with macros
818 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
819 body.descendants()
820 .filter_map(ast::IdentPat::cast)
821 .filter_map(|let_stmt| ctx.sema.to_def(&let_stmt))
822 .unique()
823 .collect()
824}
825
826/// list local variables defined inside `body` that should be returned from extracted function
827fn vars_defined_in_body_and_outlive(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
828 let mut vars_defined_in_body = vars_defined_in_body(&body, ctx);
829 vars_defined_in_body.retain(|var| var_outlives_body(ctx, body, var));
830 vars_defined_in_body
831}
832
833/// checks if the relevant local was defined before(outside of) body
834fn is_defined_before(
835 ctx: &AssistContext,
836 body: &FunctionBody,
837 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
838) -> bool {
839 src.file_id.original_file(ctx.db()) == ctx.frange.file_id
840 && !body.contains_node(&either_syntax(&src.value))
841}
842
843fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
844 match value {
845 Either::Left(pat) => pat.syntax(),
846 Either::Right(it) => it.syntax(),
847 }
848}
849
850/// checks if local variable is used after(outside of) body
851fn var_outlives_body(ctx: &AssistContext, body: &FunctionBody, var: &Local) -> bool {
852 let usages = LocalUsages::find(ctx, *var);
853 let has_usages = usages.iter().any(|reference| body.preceedes_range(reference.range));
854 has_usages
855}
856
857fn body_return_ty(ctx: &AssistContext, body: &FunctionBody) -> Option<RetType> {
858 match body.tail_expr() {
859 Some(expr) => {
860 let ty = ctx.sema.type_of_expr(&expr)?;
861 Some(RetType::Expr(ty))
862 }
863 None => Some(RetType::Stmt),
864 }
865}
866/// Where to put extracted function definition
867#[derive(Debug)]
868enum Anchor {
869 /// Extract free function and put right after current top-level function
870 Freestanding,
871 /// Extract method and put right after current function in the impl-block
872 Method,
873}
874
875/// find where to put extracted function definition
876///
877/// Function should be put right after returned node
878fn scope_for_fn_insertion(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
879 match body {
880 FunctionBody::Expr(e) => scope_for_fn_insertion_node(e.syntax(), anchor),
881 FunctionBody::Span { parent, .. } => scope_for_fn_insertion_node(parent.syntax(), anchor),
882 }
883}
884
885fn scope_for_fn_insertion_node(node: &SyntaxNode, anchor: Anchor) -> Option<SyntaxNode> {
886 let mut ancestors = node.ancestors().peekable();
887 let mut last_ancestor = None;
888 while let Some(next_ancestor) = ancestors.next() {
889 match next_ancestor.kind() {
890 SyntaxKind::SOURCE_FILE => break,
891 SyntaxKind::ITEM_LIST => {
892 if !matches!(anchor, Anchor::Freestanding) {
893 continue;
894 }
895 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
896 break;
897 }
898 }
899 SyntaxKind::ASSOC_ITEM_LIST => {
900 if !matches!(anchor, Anchor::Method) {
901 continue;
902 }
903 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
904 break;
905 }
906 }
907 _ => {}
908 }
909 last_ancestor = Some(next_ancestor);
910 }
911 last_ancestor
912}
913
914fn format_replacement(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
915 let ret_ty = fun.return_type(ctx);
916
917 let args = fun.params.iter().map(|param| param.to_arg(ctx));
918 let args = make::arg_list(args);
919 let call_expr = if fun.self_param.is_some() {
920 let self_arg = make::expr_path(make_path_from_text("self"));
921 make::expr_method_call(self_arg, &fun.name, args)
922 } else {
923 let func = make::expr_path(make_path_from_text(&fun.name));
924 make::expr_call(func, args)
925 };
926
927 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
928
929 let expr = handler.make_call_expr(call_expr).indent(indent);
930
931 let mut buf = String::new();
932 match fun.vars_defined_in_body_and_outlive.as_slice() {
933 [] => {}
934 [var] => format_to!(buf, "let {} = ", var.name(ctx.db()).unwrap()),
935 [v0, vs @ ..] => {
936 buf.push_str("let (");
937 format_to!(buf, "{}", v0.name(ctx.db()).unwrap());
938 for var in vs {
939 format_to!(buf, ", {}", var.name(ctx.db()).unwrap());
940 }
941 buf.push_str(") = ");
942 }
943 }
944 format_to!(buf, "{}", expr);
945 if fun.ret_ty.is_unit()
946 && (!fun.vars_defined_in_body_and_outlive.is_empty() || !expr.is_block_like())
947 {
948 buf.push(';');
949 }
950 buf
951}
952
953enum FlowHandler {
954 None,
955 Try { kind: TryKind },
956 If { action: FlowKind },
957 IfOption { action: FlowKind },
958 MatchOption { none: FlowKind },
959 MatchResult { err: FlowKind },
960}
961
962impl FlowHandler {
963 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
964 match &fun.control_flow.kind {
965 None => FlowHandler::None,
966 Some(flow_kind) => {
967 let action = flow_kind.clone();
968 if *ret_ty == FunType::Unit {
969 match flow_kind {
970 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
971 FlowHandler::If { action }
972 }
973 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
974 FlowHandler::IfOption { action }
975 }
976 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
977 FlowHandler::Try { kind: kind.clone() }
978 }
979 }
980 } else {
981 match flow_kind {
982 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
983 FlowHandler::MatchOption { none: action }
984 }
985 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
986 FlowHandler::MatchResult { err: action }
987 }
988 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
989 FlowHandler::Try { kind: kind.clone() }
990 }
991 }
992 }
993 }
994 }
995 }
996
997 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
998 match self {
999 FlowHandler::None => call_expr,
1000 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1001 FlowHandler::If { action } => {
1002 let action = action.make_result_handler(None);
1003 let stmt = make::expr_stmt(action);
1004 let block = make::block_expr(iter::once(stmt.into()), None);
1005 let condition = make::condition(call_expr, None);
1006 make::expr_if(condition, block, None)
1007 }
1008 FlowHandler::IfOption { action } => {
1009 let path = make_path_from_text("Some");
1010 let value_pat = make::ident_pat(make::name("value"));
1011 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1012 let cond = make::condition(call_expr, Some(pattern.into()));
1013 let value = make::expr_path(make_path_from_text("value"));
1014 let action_expr = action.make_result_handler(Some(value));
1015 let action_stmt = make::expr_stmt(action_expr);
1016 let then = make::block_expr(iter::once(action_stmt.into()), None);
1017 make::expr_if(cond, then, None)
1018 }
1019 FlowHandler::MatchOption { none } => {
1020 let some_name = "value";
1021
1022 let some_arm = {
1023 let path = make_path_from_text("Some");
1024 let value_pat = make::ident_pat(make::name(some_name));
1025 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1026 let value = make::expr_path(make_path_from_text(some_name));
1027 make::match_arm(iter::once(pat.into()), value)
1028 };
1029 let none_arm = {
1030 let path = make_path_from_text("None");
1031 let pat = make::path_pat(path);
1032 make::match_arm(iter::once(pat), none.make_result_handler(None))
1033 };
1034 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1035 make::expr_match(call_expr, arms)
1036 }
1037 FlowHandler::MatchResult { err } => {
1038 let ok_name = "value";
1039 let err_name = "value";
1040
1041 let ok_arm = {
1042 let path = make_path_from_text("Ok");
1043 let value_pat = make::ident_pat(make::name(ok_name));
1044 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1045 let value = make::expr_path(make_path_from_text(ok_name));
1046 make::match_arm(iter::once(pat.into()), value)
1047 };
1048 let err_arm = {
1049 let path = make_path_from_text("Err");
1050 let value_pat = make::ident_pat(make::name(err_name));
1051 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1052 let value = make::expr_path(make_path_from_text(err_name));
1053 make::match_arm(iter::once(pat.into()), err.make_result_handler(Some(value)))
1054 };
1055 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1056 make::expr_match(call_expr, arms)
1057 }
1058 }
1059 }
1060}
1061
1062fn make_path_from_text(text: &str) -> ast::Path {
1063 make::path_unqualified(make::path_segment(make::name_ref(text)))
1064}
1065
1066fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1067 let name = var.name(ctx.db()).unwrap().to_string();
1068 make::expr_path(make_path_from_text(&name))
1069}
1070
1071fn format_function(
1072 ctx: &AssistContext,
1073 module: hir::Module,
1074 fun: &Function,
1075 old_indent: IndentLevel,
1076 new_indent: IndentLevel,
1077) -> String {
1078 let mut fn_def = String::new();
1079 let params = make_param_list(ctx, module, fun);
1080 let ret_ty = make_ret_ty(ctx, module, fun);
1081 let body = make_body(ctx, old_indent, new_indent, fun);
1082 format_to!(fn_def, "\n\n{}fn $0{}{}", new_indent, fun.name, params);
1083 if let Some(ret_ty) = ret_ty {
1084 format_to!(fn_def, " {}", ret_ty);
1085 }
1086 format_to!(fn_def, " {}", body);
1087
1088 fn_def
1089}
1090
1091fn make_param_list(ctx: &AssistContext, module: hir::Module, fun: &Function) -> ast::ParamList {
1092 let self_param = fun.self_param.clone();
1093 let params = fun.params.iter().map(|param| param.to_param(ctx, module));
1094 make::param_list(self_param, params)
1095}
1096
1097impl FunType {
1098 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1099 match self {
1100 FunType::Unit => make::ty_unit(),
1101 FunType::Single(ty) => make_ty(ty, ctx, module),
1102 FunType::Tuple(types) => match types.as_slice() {
1103 [] => {
1104 stdx::never!("tuple type with 0 elements");
1105 make::ty_unit()
1106 }
1107 [ty] => {
1108 stdx::never!("tuple type with 1 element");
1109 make_ty(ty, ctx, module)
1110 }
1111 types => {
1112 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1113 make::ty_tuple(types)
1114 }
1115 },
1116 }
1117 }
1118}
1119
1120fn make_ret_ty(ctx: &AssistContext, module: hir::Module, fun: &Function) -> Option<ast::RetType> {
1121 let fun_ty = fun.return_type(ctx);
1122 let handler = FlowHandler::from_ret_ty(fun, &fun_ty);
1123 let ret_ty = match &handler {
1124 FlowHandler::None => {
1125 if matches!(fun_ty, FunType::Unit) {
1126 return None;
1127 }
1128 fun_ty.make_ty(ctx, module)
1129 }
1130 FlowHandler::Try { kind: TryKind::Option } => {
1131 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1132 }
1133 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1134 let handler_ty = parent_ret_ty
1135 .type_parameters()
1136 .nth(1)
1137 .map(|ty| make_ty(&ty, ctx, module))
1138 .unwrap_or_else(make::ty_unit);
1139 make::ty_generic(
1140 make::name_ref("Result"),
1141 vec![fun_ty.make_ty(ctx, module), handler_ty],
1142 )
1143 }
1144 FlowHandler::If { .. } => make::ty("bool"),
1145 FlowHandler::IfOption { action } => {
1146 let handler_ty = action
1147 .expr_ty(ctx)
1148 .map(|ty| make_ty(&ty, ctx, module))
1149 .unwrap_or_else(make::ty_unit);
1150 make::ty_generic(make::name_ref("Option"), iter::once(handler_ty))
1151 }
1152 FlowHandler::MatchOption { .. } => {
1153 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1154 }
1155 FlowHandler::MatchResult { err } => {
1156 let handler_ty =
1157 err.expr_ty(ctx).map(|ty| make_ty(&ty, ctx, module)).unwrap_or_else(make::ty_unit);
1158 make::ty_generic(
1159 make::name_ref("Result"),
1160 vec![fun_ty.make_ty(ctx, module), handler_ty],
1161 )
1162 }
1163 };
1164 Some(make::ret_type(ret_ty))
1165}
1166
1167fn make_body(
1168 ctx: &AssistContext,
1169 old_indent: IndentLevel,
1170 new_indent: IndentLevel,
1171 fun: &Function,
1172) -> ast::BlockExpr {
1173 let ret_ty = fun.return_type(ctx);
1174 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1175 let block = match &fun.body {
1176 FunctionBody::Expr(expr) => {
1177 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1178 let expr = ast::Expr::cast(expr).unwrap();
1179 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1180
1181 make::block_expr(Vec::new(), Some(expr))
1182 }
1183 FunctionBody::Span { parent, text_range } => {
1184 let mut elements: Vec<_> = parent
1185 .syntax()
1186 .children()
1187 .filter(|it| text_range.contains_range(it.text_range()))
1188 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1189 .collect();
1190
1191 let mut tail_expr = match elements.pop() {
1192 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1193 elements.push(node);
1194 None
1195 }),
1196 None => None,
1197 };
1198
1199 if tail_expr.is_none() {
1200 match fun.vars_defined_in_body_and_outlive.as_slice() {
1201 [] => {}
1202 [var] => {
1203 tail_expr = Some(path_expr_from_local(ctx, *var));
1204 }
1205 vars => {
1206 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, *var));
1207 let expr = make::expr_tuple(exprs);
1208 tail_expr = Some(expr);
1209 }
1210 }
1211 }
1212
1213 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1214 Some(stmt) => Some(stmt),
1215 None => {
1216 stdx::never!("block contains non-statement");
1217 None
1218 }
1219 });
1220
1221 let body_indent = IndentLevel(1);
1222 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1223 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1224
1225 make::block_expr(elements, tail_expr)
1226 }
1227 };
1228
1229 let block = match &handler {
1230 FlowHandler::None => block,
1231 FlowHandler::Try { kind } => {
1232 let block = with_default_tail_expr(block, make::expr_unit());
1233 map_tail_expr(block, |tail_expr| {
1234 let constructor = match kind {
1235 TryKind::Option => "Some",
1236 TryKind::Result { .. } => "Ok",
1237 };
1238 let func = make::expr_path(make_path_from_text(constructor));
1239 let args = make::arg_list(iter::once(tail_expr));
1240 make::expr_call(func, args)
1241 })
1242 }
1243 FlowHandler::If { .. } => {
1244 let lit_false = ast::Literal::cast(make::tokens::literal("false").parent()).unwrap();
1245 with_tail_expr(block, lit_false.into())
1246 }
1247 FlowHandler::IfOption { .. } => {
1248 let none = make::expr_path(make_path_from_text("None"));
1249 with_tail_expr(block, none)
1250 }
1251 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1252 let some = make::expr_path(make_path_from_text("Some"));
1253 let args = make::arg_list(iter::once(tail_expr));
1254 make::expr_call(some, args)
1255 }),
1256 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1257 let ok = make::expr_path(make_path_from_text("Ok"));
1258 let args = make::arg_list(iter::once(tail_expr));
1259 make::expr_call(ok, args)
1260 }),
1261 };
1262
1263 block.indent(new_indent)
1264}
1265
1266fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1267 let tail_expr = match block.tail_expr() {
1268 Some(tail_expr) => tail_expr,
1269 None => return block,
1270 };
1271 make::block_expr(block.statements(), Some(f(tail_expr)))
1272}
1273
1274fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1275 match block.tail_expr() {
1276 Some(_) => block,
1277 None => make::block_expr(block.statements(), Some(tail_expr)),
1278 }
1279}
1280
1281fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1282 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1283 let stmts = block.statements().chain(stmt_tail);
1284 make::block_expr(stmts, Some(tail_expr))
1285}
1286
1287fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1288 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "()".to_string())
1289}
1290
1291fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1292 let ty_str = format_type(ty, ctx, module);
1293 make::ty(&ty_str)
1294}
1295
1296fn rewrite_body_segment(
1297 ctx: &AssistContext,
1298 params: &[Param],
1299 handler: &FlowHandler,
1300 syntax: &SyntaxNode,
1301) -> SyntaxNode {
1302 let syntax = fix_param_usages(ctx, params, syntax);
1303 update_external_control_flow(handler, &syntax)
1304}
1305
1306/// change all usages to account for added `&`/`&mut` for some params
1307fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1308 let mut rewriter = SyntaxRewriter::default();
1309 for param in params {
1310 if !param.kind().is_ref() {
1311 continue;
1312 }
1313
1314 let usages = LocalUsages::find(ctx, param.var);
1315 let usages = usages
1316 .iter()
1317 .filter(|reference| syntax.text_range().contains_range(reference.range))
1318 .filter_map(|reference| path_element_of_reference(syntax, reference));
1319 for path in usages {
1320 match path.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1321 Some(ast::Expr::MethodCallExpr(_)) | Some(ast::Expr::FieldExpr(_)) => {
1322 // do nothing
1323 }
1324 Some(ast::Expr::RefExpr(node))
1325 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1326 {
1327 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1328 }
1329 Some(ast::Expr::RefExpr(node))
1330 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1331 {
1332 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1333 }
1334 Some(_) | None => {
1335 rewriter.replace_ast(&path, &make::expr_prefix(T![*], path.clone()));
1336 }
1337 };
1338 }
1339 }
1340
1341 rewriter.rewrite(syntax)
1342}
1343
1344fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> SyntaxNode {
1345 let mut rewriter = SyntaxRewriter::default();
1346
1347 let mut nested_loop = None;
1348 let mut nested_scope = None;
1349 for event in syntax.preorder() {
1350 let node = match event {
1351 WalkEvent::Enter(e) => {
1352 match e.kind() {
1353 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1354 if nested_loop.is_none() {
1355 nested_loop = Some(e.clone());
1356 }
1357 }
1358 SyntaxKind::FN
1359 | SyntaxKind::CONST
1360 | SyntaxKind::STATIC
1361 | SyntaxKind::IMPL
1362 | SyntaxKind::MODULE => {
1363 if nested_scope.is_none() {
1364 nested_scope = Some(e.clone());
1365 }
1366 }
1367 _ => {}
1368 }
1369 e
1370 }
1371 WalkEvent::Leave(e) => {
1372 if nested_loop.as_ref() == Some(&e) {
1373 nested_loop = None;
1374 }
1375 if nested_scope.as_ref() == Some(&e) {
1376 nested_scope = None;
1377 }
1378 continue;
1379 }
1380 };
1381 if nested_scope.is_some() {
1382 continue;
1383 }
1384 let expr = match ast::Expr::cast(node) {
1385 Some(e) => e,
1386 None => continue,
1387 };
1388 match expr {
1389 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1390 let expr = return_expr.expr();
1391 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1392 rewriter.replace_ast(&return_expr.into(), &replacement);
1393 }
1394 }
1395 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1396 let expr = break_expr.expr();
1397 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1398 rewriter.replace_ast(&break_expr.into(), &replacement);
1399 }
1400 }
1401 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1402 if let Some(replacement) = make_rewritten_flow(handler, None) {
1403 rewriter.replace_ast(&continue_expr.into(), &replacement);
1404 }
1405 }
1406 _ => {
1407 // do nothing
1408 }
1409 }
1410 }
1411
1412 rewriter.rewrite(syntax)
1413}
1414
1415fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1416 let value = match handler {
1417 FlowHandler::None | FlowHandler::Try { .. } => return None,
1418 FlowHandler::If { .. } => {
1419 ast::Literal::cast(make::tokens::literal("true").parent()).unwrap().into()
1420 }
1421 FlowHandler::IfOption { .. } => {
1422 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1423 let args = make::arg_list(iter::once(expr));
1424 make::expr_call(make::expr_path(make_path_from_text("Some")), args)
1425 }
1426 FlowHandler::MatchOption { .. } => make::expr_path(make_path_from_text("None")),
1427 FlowHandler::MatchResult { .. } => {
1428 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1429 let args = make::arg_list(iter::once(expr));
1430 make::expr_call(make::expr_path(make_path_from_text("Err")), args)
1431 }
1432 };
1433 Some(make::expr_return(Some(value)))
1434}
1435
1436#[cfg(test)]
1437mod tests {
1438 use crate::tests::{check_assist, check_assist_not_applicable};
1439
1440 use super::*;
1441
1442 #[test]
1443 fn no_args_from_binary_expr() {
1444 check_assist(
1445 extract_function,
1446 r#"
1447fn foo() {
1448 foo($01 + 1$0);
1449}"#,
1450 r#"
1451fn foo() {
1452 foo(fun_name());
1453}
1454
1455fn $0fun_name() -> i32 {
1456 1 + 1
1457}"#,
1458 );
1459 }
1460
1461 #[test]
1462 fn no_args_from_binary_expr_in_module() {
1463 check_assist(
1464 extract_function,
1465 r#"
1466mod bar {
1467 fn foo() {
1468 foo($01 + 1$0);
1469 }
1470}"#,
1471 r#"
1472mod bar {
1473 fn foo() {
1474 foo(fun_name());
1475 }
1476
1477 fn $0fun_name() -> i32 {
1478 1 + 1
1479 }
1480}"#,
1481 );
1482 }
1483
1484 #[test]
1485 fn no_args_from_binary_expr_indented() {
1486 check_assist(
1487 extract_function,
1488 r#"
1489fn foo() {
1490 $0{ 1 + 1 }$0;
1491}"#,
1492 r#"
1493fn foo() {
1494 fun_name();
1495}
1496
1497fn $0fun_name() -> i32 {
1498 { 1 + 1 }
1499}"#,
1500 );
1501 }
1502
1503 #[test]
1504 fn no_args_from_stmt_with_last_expr() {
1505 check_assist(
1506 extract_function,
1507 r#"
1508fn foo() -> i32 {
1509 let k = 1;
1510 $0let m = 1;
1511 m + 1$0
1512}"#,
1513 r#"
1514fn foo() -> i32 {
1515 let k = 1;
1516 fun_name()
1517}
1518
1519fn $0fun_name() -> i32 {
1520 let m = 1;
1521 m + 1
1522}"#,
1523 );
1524 }
1525
1526 #[test]
1527 fn no_args_from_stmt_unit() {
1528 check_assist(
1529 extract_function,
1530 r#"
1531fn foo() {
1532 let k = 3;
1533 $0let m = 1;
1534 let n = m + 1;$0
1535 let g = 5;
1536}"#,
1537 r#"
1538fn foo() {
1539 let k = 3;
1540 fun_name();
1541 let g = 5;
1542}
1543
1544fn $0fun_name() {
1545 let m = 1;
1546 let n = m + 1;
1547}"#,
1548 );
1549 }
1550
1551 #[test]
1552 fn no_args_if() {
1553 check_assist(
1554 extract_function,
1555 r#"
1556fn foo() {
1557 $0if true { }$0
1558}"#,
1559 r#"
1560fn foo() {
1561 fun_name();
1562}
1563
1564fn $0fun_name() {
1565 if true { }
1566}"#,
1567 );
1568 }
1569
1570 #[test]
1571 fn no_args_if_else() {
1572 check_assist(
1573 extract_function,
1574 r#"
1575fn foo() -> i32 {
1576 $0if true { 1 } else { 2 }$0
1577}"#,
1578 r#"
1579fn foo() -> i32 {
1580 fun_name()
1581}
1582
1583fn $0fun_name() -> i32 {
1584 if true { 1 } else { 2 }
1585}"#,
1586 );
1587 }
1588
1589 #[test]
1590 fn no_args_if_let_else() {
1591 check_assist(
1592 extract_function,
1593 r#"
1594fn foo() -> i32 {
1595 $0if let true = false { 1 } else { 2 }$0
1596}"#,
1597 r#"
1598fn foo() -> i32 {
1599 fun_name()
1600}
1601
1602fn $0fun_name() -> i32 {
1603 if let true = false { 1 } else { 2 }
1604}"#,
1605 );
1606 }
1607
1608 #[test]
1609 fn no_args_match() {
1610 check_assist(
1611 extract_function,
1612 r#"
1613fn foo() -> i32 {
1614 $0match true {
1615 true => 1,
1616 false => 2,
1617 }$0
1618}"#,
1619 r#"
1620fn foo() -> i32 {
1621 fun_name()
1622}
1623
1624fn $0fun_name() -> i32 {
1625 match true {
1626 true => 1,
1627 false => 2,
1628 }
1629}"#,
1630 );
1631 }
1632
1633 #[test]
1634 fn no_args_while() {
1635 check_assist(
1636 extract_function,
1637 r#"
1638fn foo() {
1639 $0while true { }$0
1640}"#,
1641 r#"
1642fn foo() {
1643 fun_name();
1644}
1645
1646fn $0fun_name() {
1647 while true { }
1648}"#,
1649 );
1650 }
1651
1652 #[test]
1653 fn no_args_for() {
1654 check_assist(
1655 extract_function,
1656 r#"
1657fn foo() {
1658 $0for v in &[0, 1] { }$0
1659}"#,
1660 r#"
1661fn foo() {
1662 fun_name();
1663}
1664
1665fn $0fun_name() {
1666 for v in &[0, 1] { }
1667}"#,
1668 );
1669 }
1670
1671 #[test]
1672 fn no_args_from_loop_unit() {
1673 check_assist(
1674 extract_function,
1675 r#"
1676fn foo() {
1677 $0loop {
1678 let m = 1;
1679 }$0
1680}"#,
1681 r#"
1682fn foo() {
1683 fun_name()
1684}
1685
1686fn $0fun_name() -> ! {
1687 loop {
1688 let m = 1;
1689 }
1690}"#,
1691 );
1692 }
1693
1694 #[test]
1695 fn no_args_from_loop_with_return() {
1696 check_assist(
1697 extract_function,
1698 r#"
1699fn foo() {
1700 let v = $0loop {
1701 let m = 1;
1702 break m;
1703 }$0;
1704}"#,
1705 r#"
1706fn foo() {
1707 let v = fun_name();
1708}
1709
1710fn $0fun_name() -> i32 {
1711 loop {
1712 let m = 1;
1713 break m;
1714 }
1715}"#,
1716 );
1717 }
1718
1719 #[test]
1720 fn no_args_from_match() {
1721 check_assist(
1722 extract_function,
1723 r#"
1724fn foo() {
1725 let v: i32 = $0match Some(1) {
1726 Some(x) => x,
1727 None => 0,
1728 }$0;
1729}"#,
1730 r#"
1731fn foo() {
1732 let v: i32 = fun_name();
1733}
1734
1735fn $0fun_name() -> i32 {
1736 match Some(1) {
1737 Some(x) => x,
1738 None => 0,
1739 }
1740}"#,
1741 );
1742 }
1743
1744 #[test]
1745 fn argument_form_expr() {
1746 check_assist(
1747 extract_function,
1748 r"
1749fn foo() -> u32 {
1750 let n = 2;
1751 $0n+2$0
1752}",
1753 r"
1754fn foo() -> u32 {
1755 let n = 2;
1756 fun_name(n)
1757}
1758
1759fn $0fun_name(n: u32) -> u32 {
1760 n+2
1761}",
1762 )
1763 }
1764
1765 #[test]
1766 fn argument_used_twice_form_expr() {
1767 check_assist(
1768 extract_function,
1769 r"
1770fn foo() -> u32 {
1771 let n = 2;
1772 $0n+n$0
1773}",
1774 r"
1775fn foo() -> u32 {
1776 let n = 2;
1777 fun_name(n)
1778}
1779
1780fn $0fun_name(n: u32) -> u32 {
1781 n+n
1782}",
1783 )
1784 }
1785
1786 #[test]
1787 fn two_arguments_form_expr() {
1788 check_assist(
1789 extract_function,
1790 r"
1791fn foo() -> u32 {
1792 let n = 2;
1793 let m = 3;
1794 $0n+n*m$0
1795}",
1796 r"
1797fn foo() -> u32 {
1798 let n = 2;
1799 let m = 3;
1800 fun_name(n, m)
1801}
1802
1803fn $0fun_name(n: u32, m: u32) -> u32 {
1804 n+n*m
1805}",
1806 )
1807 }
1808
1809 #[test]
1810 fn argument_and_locals() {
1811 check_assist(
1812 extract_function,
1813 r"
1814fn foo() -> u32 {
1815 let n = 2;
1816 $0let m = 1;
1817 n + m$0
1818}",
1819 r"
1820fn foo() -> u32 {
1821 let n = 2;
1822 fun_name(n)
1823}
1824
1825fn $0fun_name(n: u32) -> u32 {
1826 let m = 1;
1827 n + m
1828}",
1829 )
1830 }
1831
1832 #[test]
1833 fn in_comment_is_not_applicable() {
1834 mark::check!(extract_function_in_comment_is_not_applicable);
1835 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
1836 }
1837
1838 #[test]
1839 fn part_of_expr_stmt() {
1840 check_assist(
1841 extract_function,
1842 "
1843fn foo() {
1844 $01$0 + 1;
1845}",
1846 "
1847fn foo() {
1848 fun_name() + 1;
1849}
1850
1851fn $0fun_name() -> i32 {
1852 1
1853}",
1854 );
1855 }
1856
1857 #[test]
1858 fn function_expr() {
1859 check_assist(
1860 extract_function,
1861 r#"
1862fn foo() {
1863 $0bar(1 + 1)$0
1864}"#,
1865 r#"
1866fn foo() {
1867 fun_name();
1868}
1869
1870fn $0fun_name() {
1871 bar(1 + 1)
1872}"#,
1873 )
1874 }
1875
1876 #[test]
1877 fn extract_from_nested() {
1878 check_assist(
1879 extract_function,
1880 r"
1881fn main() {
1882 let x = true;
1883 let tuple = match x {
1884 true => ($02 + 2$0, true)
1885 _ => (0, false)
1886 };
1887}",
1888 r"
1889fn main() {
1890 let x = true;
1891 let tuple = match x {
1892 true => (fun_name(), true)
1893 _ => (0, false)
1894 };
1895}
1896
1897fn $0fun_name() -> i32 {
1898 2 + 2
1899}",
1900 );
1901 }
1902
1903 #[test]
1904 fn param_from_closure() {
1905 check_assist(
1906 extract_function,
1907 r"
1908fn main() {
1909 let lambda = |x: u32| $0x * 2$0;
1910}",
1911 r"
1912fn main() {
1913 let lambda = |x: u32| fun_name(x);
1914}
1915
1916fn $0fun_name(x: u32) -> u32 {
1917 x * 2
1918}",
1919 );
1920 }
1921
1922 #[test]
1923 fn extract_return_stmt() {
1924 check_assist(
1925 extract_function,
1926 r"
1927fn foo() -> u32 {
1928 $0return 2 + 2$0;
1929}",
1930 r"
1931fn foo() -> u32 {
1932 return fun_name();
1933}
1934
1935fn $0fun_name() -> u32 {
1936 2 + 2
1937}",
1938 );
1939 }
1940
1941 #[test]
1942 fn does_not_add_extra_whitespace() {
1943 check_assist(
1944 extract_function,
1945 r"
1946fn foo() -> u32 {
1947
1948
1949 $0return 2 + 2$0;
1950}",
1951 r"
1952fn foo() -> u32 {
1953
1954
1955 return fun_name();
1956}
1957
1958fn $0fun_name() -> u32 {
1959 2 + 2
1960}",
1961 );
1962 }
1963
1964 #[test]
1965 fn break_stmt() {
1966 check_assist(
1967 extract_function,
1968 r"
1969fn main() {
1970 let result = loop {
1971 $0break 2 + 2$0;
1972 };
1973}",
1974 r"
1975fn main() {
1976 let result = loop {
1977 break fun_name();
1978 };
1979}
1980
1981fn $0fun_name() -> i32 {
1982 2 + 2
1983}",
1984 );
1985 }
1986
1987 #[test]
1988 fn extract_cast() {
1989 check_assist(
1990 extract_function,
1991 r"
1992fn main() {
1993 let v = $00f32 as u32$0;
1994}",
1995 r"
1996fn main() {
1997 let v = fun_name();
1998}
1999
2000fn $0fun_name() -> u32 {
2001 0f32 as u32
2002}",
2003 );
2004 }
2005
2006 #[test]
2007 fn return_not_applicable() {
2008 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2009 }
2010
2011 #[test]
2012 fn method_to_freestanding() {
2013 check_assist(
2014 extract_function,
2015 r"
2016struct S;
2017
2018impl S {
2019 fn foo(&self) -> i32 {
2020 $01+1$0
2021 }
2022}",
2023 r"
2024struct S;
2025
2026impl S {
2027 fn foo(&self) -> i32 {
2028 fun_name()
2029 }
2030}
2031
2032fn $0fun_name() -> i32 {
2033 1+1
2034}",
2035 );
2036 }
2037
2038 #[test]
2039 fn method_with_reference() {
2040 check_assist(
2041 extract_function,
2042 r"
2043struct S { f: i32 };
2044
2045impl S {
2046 fn foo(&self) -> i32 {
2047 $01+self.f$0
2048 }
2049}",
2050 r"
2051struct S { f: i32 };
2052
2053impl S {
2054 fn foo(&self) -> i32 {
2055 self.fun_name()
2056 }
2057
2058 fn $0fun_name(&self) -> i32 {
2059 1+self.f
2060 }
2061}",
2062 );
2063 }
2064
2065 #[test]
2066 fn method_with_mut() {
2067 check_assist(
2068 extract_function,
2069 r"
2070struct S { f: i32 };
2071
2072impl S {
2073 fn foo(&mut self) {
2074 $0self.f += 1;$0
2075 }
2076}",
2077 r"
2078struct S { f: i32 };
2079
2080impl S {
2081 fn foo(&mut self) {
2082 self.fun_name();
2083 }
2084
2085 fn $0fun_name(&mut self) {
2086 self.f += 1;
2087 }
2088}",
2089 );
2090 }
2091
2092 #[test]
2093 fn variable_defined_inside_and_used_after_no_ret() {
2094 check_assist(
2095 extract_function,
2096 r"
2097fn foo() {
2098 let n = 1;
2099 $0let k = n * n;$0
2100 let m = k + 1;
2101}",
2102 r"
2103fn foo() {
2104 let n = 1;
2105 let k = fun_name(n);
2106 let m = k + 1;
2107}
2108
2109fn $0fun_name(n: i32) -> i32 {
2110 let k = n * n;
2111 k
2112}",
2113 );
2114 }
2115
2116 #[test]
2117 fn two_variables_defined_inside_and_used_after_no_ret() {
2118 check_assist(
2119 extract_function,
2120 r"
2121fn foo() {
2122 let n = 1;
2123 $0let k = n * n;
2124 let m = k + 2;$0
2125 let h = k + m;
2126}",
2127 r"
2128fn foo() {
2129 let n = 1;
2130 let (k, m) = fun_name(n);
2131 let h = k + m;
2132}
2133
2134fn $0fun_name(n: i32) -> (i32, i32) {
2135 let k = n * n;
2136 let m = k + 2;
2137 (k, m)
2138}",
2139 );
2140 }
2141
2142 #[test]
2143 fn nontrivial_patterns_define_variables() {
2144 check_assist(
2145 extract_function,
2146 r"
2147struct Counter(i32);
2148fn foo() {
2149 $0let Counter(n) = Counter(0);$0
2150 let m = n;
2151}",
2152 r"
2153struct Counter(i32);
2154fn foo() {
2155 let n = fun_name();
2156 let m = n;
2157}
2158
2159fn $0fun_name() -> i32 {
2160 let Counter(n) = Counter(0);
2161 n
2162}",
2163 );
2164 }
2165
2166 #[test]
2167 fn struct_with_two_fields_pattern_define_variables() {
2168 check_assist(
2169 extract_function,
2170 r"
2171struct Counter { n: i32, m: i32 };
2172fn foo() {
2173 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2174 let h = n + k;
2175}",
2176 r"
2177struct Counter { n: i32, m: i32 };
2178fn foo() {
2179 let (n, k) = fun_name();
2180 let h = n + k;
2181}
2182
2183fn $0fun_name() -> (i32, i32) {
2184 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2185 (n, k)
2186}",
2187 );
2188 }
2189
2190 #[test]
2191 fn mut_var_from_outer_scope() {
2192 check_assist(
2193 extract_function,
2194 r"
2195fn foo() {
2196 let mut n = 1;
2197 $0n += 1;$0
2198 let m = n + 1;
2199}",
2200 r"
2201fn foo() {
2202 let mut n = 1;
2203 fun_name(&mut n);
2204 let m = n + 1;
2205}
2206
2207fn $0fun_name(n: &mut i32) {
2208 *n += 1;
2209}",
2210 );
2211 }
2212
2213 #[test]
2214 fn mut_field_from_outer_scope() {
2215 check_assist(
2216 extract_function,
2217 r"
2218struct C { n: i32 }
2219fn foo() {
2220 let mut c = C { n: 0 };
2221 $0c.n += 1;$0
2222 let m = c.n + 1;
2223}",
2224 r"
2225struct C { n: i32 }
2226fn foo() {
2227 let mut c = C { n: 0 };
2228 fun_name(&mut c);
2229 let m = c.n + 1;
2230}
2231
2232fn $0fun_name(c: &mut C) {
2233 c.n += 1;
2234}",
2235 );
2236 }
2237
2238 #[test]
2239 fn mut_nested_field_from_outer_scope() {
2240 check_assist(
2241 extract_function,
2242 r"
2243struct P { n: i32}
2244struct C { p: P }
2245fn foo() {
2246 let mut c = C { p: P { n: 0 } };
2247 let mut v = C { p: P { n: 0 } };
2248 let u = C { p: P { n: 0 } };
2249 $0c.p.n += u.p.n;
2250 let r = &mut v.p.n;$0
2251 let m = c.p.n + v.p.n + u.p.n;
2252}",
2253 r"
2254struct P { n: i32}
2255struct C { p: P }
2256fn foo() {
2257 let mut c = C { p: P { n: 0 } };
2258 let mut v = C { p: P { n: 0 } };
2259 let u = C { p: P { n: 0 } };
2260 fun_name(&mut c, &u, &mut v);
2261 let m = c.p.n + v.p.n + u.p.n;
2262}
2263
2264fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2265 c.p.n += u.p.n;
2266 let r = &mut v.p.n;
2267}",
2268 );
2269 }
2270
2271 #[test]
2272 fn mut_param_many_usages_stmt() {
2273 check_assist(
2274 extract_function,
2275 r"
2276fn bar(k: i32) {}
2277trait I: Copy {
2278 fn succ(&self) -> Self;
2279 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2280}
2281impl I for i32 {
2282 fn succ(&self) -> Self { *self + 1 }
2283}
2284fn foo() {
2285 let mut n = 1;
2286 $0n += n;
2287 bar(n);
2288 bar(n+1);
2289 bar(n*n);
2290 bar(&n);
2291 n.inc();
2292 let v = &mut n;
2293 *v = v.succ();
2294 n.succ();$0
2295 let m = n + 1;
2296}",
2297 r"
2298fn bar(k: i32) {}
2299trait I: Copy {
2300 fn succ(&self) -> Self;
2301 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2302}
2303impl I for i32 {
2304 fn succ(&self) -> Self { *self + 1 }
2305}
2306fn foo() {
2307 let mut n = 1;
2308 fun_name(&mut n);
2309 let m = n + 1;
2310}
2311
2312fn $0fun_name(n: &mut i32) {
2313 *n += *n;
2314 bar(*n);
2315 bar(*n+1);
2316 bar(*n**n);
2317 bar(&*n);
2318 n.inc();
2319 let v = n;
2320 *v = v.succ();
2321 n.succ();
2322}",
2323 );
2324 }
2325
2326 #[test]
2327 fn mut_param_many_usages_expr() {
2328 check_assist(
2329 extract_function,
2330 r"
2331fn bar(k: i32) {}
2332trait I: Copy {
2333 fn succ(&self) -> Self;
2334 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2335}
2336impl I for i32 {
2337 fn succ(&self) -> Self { *self + 1 }
2338}
2339fn foo() {
2340 let mut n = 1;
2341 $0{
2342 n += n;
2343 bar(n);
2344 bar(n+1);
2345 bar(n*n);
2346 bar(&n);
2347 n.inc();
2348 let v = &mut n;
2349 *v = v.succ();
2350 n.succ();
2351 }$0
2352 let m = n + 1;
2353}",
2354 r"
2355fn bar(k: i32) {}
2356trait I: Copy {
2357 fn succ(&self) -> Self;
2358 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2359}
2360impl I for i32 {
2361 fn succ(&self) -> Self { *self + 1 }
2362}
2363fn foo() {
2364 let mut n = 1;
2365 fun_name(&mut n);
2366 let m = n + 1;
2367}
2368
2369fn $0fun_name(n: &mut i32) {
2370 {
2371 *n += *n;
2372 bar(*n);
2373 bar(*n+1);
2374 bar(*n**n);
2375 bar(&*n);
2376 n.inc();
2377 let v = n;
2378 *v = v.succ();
2379 n.succ();
2380 }
2381}",
2382 );
2383 }
2384
2385 #[test]
2386 fn mut_param_by_value() {
2387 check_assist(
2388 extract_function,
2389 r"
2390fn foo() {
2391 let mut n = 1;
2392 $0n += 1;$0
2393}",
2394 r"
2395fn foo() {
2396 let mut n = 1;
2397 fun_name(n);
2398}
2399
2400fn $0fun_name(mut n: i32) {
2401 n += 1;
2402}",
2403 );
2404 }
2405
2406 #[test]
2407 fn mut_param_because_of_mut_ref() {
2408 check_assist(
2409 extract_function,
2410 r"
2411fn foo() {
2412 let mut n = 1;
2413 $0let v = &mut n;
2414 *v += 1;$0
2415 let k = n;
2416}",
2417 r"
2418fn foo() {
2419 let mut n = 1;
2420 fun_name(&mut n);
2421 let k = n;
2422}
2423
2424fn $0fun_name(n: &mut i32) {
2425 let v = n;
2426 *v += 1;
2427}",
2428 );
2429 }
2430
2431 #[test]
2432 fn mut_param_by_value_because_of_mut_ref() {
2433 check_assist(
2434 extract_function,
2435 r"
2436fn foo() {
2437 let mut n = 1;
2438 $0let v = &mut n;
2439 *v += 1;$0
2440}",
2441 r"
2442fn foo() {
2443 let mut n = 1;
2444 fun_name(n);
2445}
2446
2447fn $0fun_name(mut n: i32) {
2448 let v = &mut n;
2449 *v += 1;
2450}",
2451 );
2452 }
2453
2454 #[test]
2455 fn mut_method_call() {
2456 check_assist(
2457 extract_function,
2458 r"
2459trait I {
2460 fn inc(&mut self);
2461}
2462impl I for i32 {
2463 fn inc(&mut self) { *self += 1 }
2464}
2465fn foo() {
2466 let mut n = 1;
2467 $0n.inc();$0
2468}",
2469 r"
2470trait I {
2471 fn inc(&mut self);
2472}
2473impl I for i32 {
2474 fn inc(&mut self) { *self += 1 }
2475}
2476fn foo() {
2477 let mut n = 1;
2478 fun_name(n);
2479}
2480
2481fn $0fun_name(mut n: i32) {
2482 n.inc();
2483}",
2484 );
2485 }
2486
2487 #[test]
2488 fn shared_method_call() {
2489 check_assist(
2490 extract_function,
2491 r"
2492trait I {
2493 fn succ(&self);
2494}
2495impl I for i32 {
2496 fn succ(&self) { *self + 1 }
2497}
2498fn foo() {
2499 let mut n = 1;
2500 $0n.succ();$0
2501}",
2502 r"
2503trait I {
2504 fn succ(&self);
2505}
2506impl I for i32 {
2507 fn succ(&self) { *self + 1 }
2508}
2509fn foo() {
2510 let mut n = 1;
2511 fun_name(n);
2512}
2513
2514fn $0fun_name(n: i32) {
2515 n.succ();
2516}",
2517 );
2518 }
2519
2520 #[test]
2521 fn mut_method_call_with_other_receiver() {
2522 check_assist(
2523 extract_function,
2524 r"
2525trait I {
2526 fn inc(&mut self, n: i32);
2527}
2528impl I for i32 {
2529 fn inc(&mut self, n: i32) { *self += n }
2530}
2531fn foo() {
2532 let mut n = 1;
2533 $0let mut m = 2;
2534 m.inc(n);$0
2535}",
2536 r"
2537trait I {
2538 fn inc(&mut self, n: i32);
2539}
2540impl I for i32 {
2541 fn inc(&mut self, n: i32) { *self += n }
2542}
2543fn foo() {
2544 let mut n = 1;
2545 fun_name(n);
2546}
2547
2548fn $0fun_name(n: i32) {
2549 let mut m = 2;
2550 m.inc(n);
2551}",
2552 );
2553 }
2554
2555 #[test]
2556 fn non_copy_without_usages_after() {
2557 check_assist(
2558 extract_function,
2559 r"
2560struct Counter(i32);
2561fn foo() {
2562 let c = Counter(0);
2563 $0let n = c.0;$0
2564}",
2565 r"
2566struct Counter(i32);
2567fn foo() {
2568 let c = Counter(0);
2569 fun_name(c);
2570}
2571
2572fn $0fun_name(c: Counter) {
2573 let n = c.0;
2574}",
2575 );
2576 }
2577
2578 #[test]
2579 fn non_copy_used_after() {
2580 check_assist(
2581 extract_function,
2582 r"
2583struct Counter(i32);
2584fn foo() {
2585 let c = Counter(0);
2586 $0let n = c.0;$0
2587 let m = c.0;
2588}",
2589 r"
2590struct Counter(i32);
2591fn foo() {
2592 let c = Counter(0);
2593 fun_name(&c);
2594 let m = c.0;
2595}
2596
2597fn $0fun_name(c: &Counter) {
2598 let n = c.0;
2599}",
2600 );
2601 }
2602
2603 #[test]
2604 fn copy_used_after() {
2605 check_assist(
2606 extract_function,
2607 r##"
2608#[lang = "copy"]
2609pub trait Copy {}
2610impl Copy for i32 {}
2611fn foo() {
2612 let n = 0;
2613 $0let m = n;$0
2614 let k = n;
2615}"##,
2616 r##"
2617#[lang = "copy"]
2618pub trait Copy {}
2619impl Copy for i32 {}
2620fn foo() {
2621 let n = 0;
2622 fun_name(n);
2623 let k = n;
2624}
2625
2626fn $0fun_name(n: i32) {
2627 let m = n;
2628}"##,
2629 )
2630 }
2631
2632 #[test]
2633 fn copy_custom_used_after() {
2634 check_assist(
2635 extract_function,
2636 r##"
2637#[lang = "copy"]
2638pub trait Copy {}
2639struct Counter(i32);
2640impl Copy for Counter {}
2641fn foo() {
2642 let c = Counter(0);
2643 $0let n = c.0;$0
2644 let m = c.0;
2645}"##,
2646 r##"
2647#[lang = "copy"]
2648pub trait Copy {}
2649struct Counter(i32);
2650impl Copy for Counter {}
2651fn foo() {
2652 let c = Counter(0);
2653 fun_name(c);
2654 let m = c.0;
2655}
2656
2657fn $0fun_name(c: Counter) {
2658 let n = c.0;
2659}"##,
2660 );
2661 }
2662
2663 #[test]
2664 fn indented_stmts() {
2665 check_assist(
2666 extract_function,
2667 r"
2668fn foo() {
2669 if true {
2670 loop {
2671 $0let n = 1;
2672 let m = 2;$0
2673 }
2674 }
2675}",
2676 r"
2677fn foo() {
2678 if true {
2679 loop {
2680 fun_name();
2681 }
2682 }
2683}
2684
2685fn $0fun_name() {
2686 let n = 1;
2687 let m = 2;
2688}",
2689 );
2690 }
2691
2692 #[test]
2693 fn indented_stmts_inside_mod() {
2694 check_assist(
2695 extract_function,
2696 r"
2697mod bar {
2698 fn foo() {
2699 if true {
2700 loop {
2701 $0let n = 1;
2702 let m = 2;$0
2703 }
2704 }
2705 }
2706}",
2707 r"
2708mod bar {
2709 fn foo() {
2710 if true {
2711 loop {
2712 fun_name();
2713 }
2714 }
2715 }
2716
2717 fn $0fun_name() {
2718 let n = 1;
2719 let m = 2;
2720 }
2721}",
2722 );
2723 }
2724
2725 #[test]
2726 fn break_loop() {
2727 check_assist(
2728 extract_function,
2729 r##"
2730enum Option<T> {
2731 #[lang = "None"] None,
2732 #[lang = "Some"] Some(T),
2733}
2734use Option::*;
2735fn foo() {
2736 loop {
2737 let n = 1;
2738 $0let m = n + 1;
2739 break;
2740 let k = 2;$0
2741 let h = 1 + k;
2742 }
2743}"##,
2744 r##"
2745enum Option<T> {
2746 #[lang = "None"] None,
2747 #[lang = "Some"] Some(T),
2748}
2749use Option::*;
2750fn foo() {
2751 loop {
2752 let n = 1;
2753 let k = match fun_name(n) {
2754 Some(value) => value,
2755 None => break,
2756 };
2757 let h = 1 + k;
2758 }
2759}
2760
2761fn $0fun_name(n: i32) -> Option<i32> {
2762 let m = n + 1;
2763 return None;
2764 let k = 2;
2765 Some(k)
2766}"##,
2767 );
2768 }
2769
2770 #[test]
2771 fn return_to_parent() {
2772 check_assist(
2773 extract_function,
2774 r##"
2775#[lang = "copy"]
2776pub trait Copy {}
2777impl Copy for i32 {}
2778enum Result<T, E> {
2779 #[lang = "Ok"] Ok(T),
2780 #[lang = "Err"] Err(E),
2781}
2782use Result::*;
2783fn foo() -> i64 {
2784 let n = 1;
2785 $0let m = n + 1;
2786 return 1;
2787 let k = 2;$0
2788 (n + k) as i64
2789}"##,
2790 r##"
2791#[lang = "copy"]
2792pub trait Copy {}
2793impl Copy for i32 {}
2794enum Result<T, E> {
2795 #[lang = "Ok"] Ok(T),
2796 #[lang = "Err"] Err(E),
2797}
2798use Result::*;
2799fn foo() -> i64 {
2800 let n = 1;
2801 let k = match fun_name(n) {
2802 Ok(value) => value,
2803 Err(value) => return value,
2804 };
2805 (n + k) as i64
2806}
2807
2808fn $0fun_name(n: i32) -> Result<i32, i64> {
2809 let m = n + 1;
2810 return Err(1);
2811 let k = 2;
2812 Ok(k)
2813}"##,
2814 );
2815 }
2816
2817 #[test]
2818 fn break_and_continue() {
2819 mark::check!(external_control_flow_break_and_continue);
2820 check_assist_not_applicable(
2821 extract_function,
2822 r##"
2823fn foo() {
2824 loop {
2825 let n = 1;
2826 $0let m = n + 1;
2827 break;
2828 let k = 2;
2829 continue;
2830 let k = k + 1;$0
2831 let r = n + k;
2832 }
2833}"##,
2834 );
2835 }
2836
2837 #[test]
2838 fn return_and_break() {
2839 mark::check!(external_control_flow_return_and_bc);
2840 check_assist_not_applicable(
2841 extract_function,
2842 r##"
2843fn foo() {
2844 loop {
2845 let n = 1;
2846 $0let m = n + 1;
2847 break;
2848 let k = 2;
2849 return;
2850 let k = k + 1;$0
2851 let r = n + k;
2852 }
2853}"##,
2854 );
2855 }
2856
2857 #[test]
2858 fn break_loop_with_if() {
2859 check_assist(
2860 extract_function,
2861 r##"
2862fn foo() {
2863 loop {
2864 let mut n = 1;
2865 $0let m = n + 1;
2866 break;
2867 n += m;$0
2868 let h = 1 + n;
2869 }
2870}"##,
2871 r##"
2872fn foo() {
2873 loop {
2874 let mut n = 1;
2875 if fun_name(&mut n) {
2876 break;
2877 }
2878 let h = 1 + n;
2879 }
2880}
2881
2882fn $0fun_name(n: &mut i32) -> bool {
2883 let m = *n + 1;
2884 return true;
2885 *n += m;
2886 false
2887}"##,
2888 );
2889 }
2890
2891 #[test]
2892 fn break_loop_nested() {
2893 check_assist(
2894 extract_function,
2895 r##"
2896fn foo() {
2897 loop {
2898 let mut n = 1;
2899 $0let m = n + 1;
2900 if m == 42 {
2901 break;
2902 }$0
2903 let h = 1;
2904 }
2905}"##,
2906 r##"
2907fn foo() {
2908 loop {
2909 let mut n = 1;
2910 if fun_name(n) {
2911 break;
2912 }
2913 let h = 1;
2914 }
2915}
2916
2917fn $0fun_name(n: i32) -> bool {
2918 let m = n + 1;
2919 if m == 42 {
2920 return true;
2921 }
2922 false
2923}"##,
2924 );
2925 }
2926
2927 #[test]
2928 fn return_from_nested_loop() {
2929 check_assist(
2930 extract_function,
2931 r##"
2932fn foo() {
2933 loop {
2934 let n = 1;
2935 $0
2936 let k = 1;
2937 loop {
2938 return;
2939 }
2940 let m = k + 1;$0
2941 let h = 1 + m;
2942 }
2943}"##,
2944 r##"
2945fn foo() {
2946 loop {
2947 let n = 1;
2948 let m = match fun_name() {
2949 Some(value) => value,
2950 None => return,
2951 };
2952 let h = 1 + m;
2953 }
2954}
2955
2956fn $0fun_name() -> Option<i32> {
2957 let k = 1;
2958 loop {
2959 return None;
2960 }
2961 let m = k + 1;
2962 Some(m)
2963}"##,
2964 );
2965 }
2966
2967 #[test]
2968 fn break_from_nested_loop() {
2969 check_assist(
2970 extract_function,
2971 r##"
2972fn foo() {
2973 loop {
2974 let n = 1;
2975 $0let k = 1;
2976 loop {
2977 break;
2978 }
2979 let m = k + 1;$0
2980 let h = 1 + m;
2981 }
2982}"##,
2983 r##"
2984fn foo() {
2985 loop {
2986 let n = 1;
2987 let m = fun_name();
2988 let h = 1 + m;
2989 }
2990}
2991
2992fn $0fun_name() -> i32 {
2993 let k = 1;
2994 loop {
2995 break;
2996 }
2997 let m = k + 1;
2998 m
2999}"##,
3000 );
3001 }
3002
3003 #[test]
3004 fn break_from_nested_and_outer_loops() {
3005 check_assist(
3006 extract_function,
3007 r##"
3008fn foo() {
3009 loop {
3010 let n = 1;
3011 $0let k = 1;
3012 loop {
3013 break;
3014 }
3015 if k == 42 {
3016 break;
3017 }
3018 let m = k + 1;$0
3019 let h = 1 + m;
3020 }
3021}"##,
3022 r##"
3023fn foo() {
3024 loop {
3025 let n = 1;
3026 let m = match fun_name() {
3027 Some(value) => value,
3028 None => break,
3029 };
3030 let h = 1 + m;
3031 }
3032}
3033
3034fn $0fun_name() -> Option<i32> {
3035 let k = 1;
3036 loop {
3037 break;
3038 }
3039 if k == 42 {
3040 return None;
3041 }
3042 let m = k + 1;
3043 Some(m)
3044}"##,
3045 );
3046 }
3047
3048 #[test]
3049 fn return_from_nested_fn() {
3050 check_assist(
3051 extract_function,
3052 r##"
3053fn foo() {
3054 loop {
3055 let n = 1;
3056 $0let k = 1;
3057 fn test() {
3058 return;
3059 }
3060 let m = k + 1;$0
3061 let h = 1 + m;
3062 }
3063}"##,
3064 r##"
3065fn foo() {
3066 loop {
3067 let n = 1;
3068 let m = fun_name();
3069 let h = 1 + m;
3070 }
3071}
3072
3073fn $0fun_name() -> i32 {
3074 let k = 1;
3075 fn test() {
3076 return;
3077 }
3078 let m = k + 1;
3079 m
3080}"##,
3081 );
3082 }
3083
3084 #[test]
3085 fn break_with_value() {
3086 check_assist(
3087 extract_function,
3088 r##"
3089fn foo() -> i32 {
3090 loop {
3091 let n = 1;
3092 $0let k = 1;
3093 if k == 42 {
3094 break 3;
3095 }
3096 let m = k + 1;$0
3097 let h = 1;
3098 }
3099}"##,
3100 r##"
3101fn foo() -> i32 {
3102 loop {
3103 let n = 1;
3104 if let Some(value) = fun_name() {
3105 break value;
3106 }
3107 let h = 1;
3108 }
3109}
3110
3111fn $0fun_name() -> Option<i32> {
3112 let k = 1;
3113 if k == 42 {
3114 return Some(3);
3115 }
3116 let m = k + 1;
3117 None
3118}"##,
3119 );
3120 }
3121
3122 #[test]
3123 fn break_with_value_and_return() {
3124 check_assist(
3125 extract_function,
3126 r##"
3127fn foo() -> i64 {
3128 loop {
3129 let n = 1;
3130 $0
3131 let k = 1;
3132 if k == 42 {
3133 break 3;
3134 }
3135 let m = k + 1;$0
3136 let h = 1 + m;
3137 }
3138}"##,
3139 r##"
3140fn foo() -> i64 {
3141 loop {
3142 let n = 1;
3143 let m = match fun_name() {
3144 Ok(value) => value,
3145 Err(value) => break value,
3146 };
3147 let h = 1 + m;
3148 }
3149}
3150
3151fn $0fun_name() -> Result<i32, i64> {
3152 let k = 1;
3153 if k == 42 {
3154 return Err(3);
3155 }
3156 let m = k + 1;
3157 Ok(m)
3158}"##,
3159 );
3160 }
3161
3162 #[test]
3163 fn try_option() {
3164 check_assist(
3165 extract_function,
3166 r##"
3167enum Option<T> { None, Some(T), }
3168use Option::*;
3169fn bar() -> Option<i32> { None }
3170fn foo() -> Option<()> {
3171 let n = bar()?;
3172 $0let k = foo()?;
3173 let m = k + 1;$0
3174 let h = 1 + m;
3175 Some(())
3176}"##,
3177 r##"
3178enum Option<T> { None, Some(T), }
3179use Option::*;
3180fn bar() -> Option<i32> { None }
3181fn foo() -> Option<()> {
3182 let n = bar()?;
3183 let m = fun_name()?;
3184 let h = 1 + m;
3185 Some(())
3186}
3187
3188fn $0fun_name() -> Option<i32> {
3189 let k = foo()?;
3190 let m = k + 1;
3191 Some(m)
3192}"##,
3193 );
3194 }
3195
3196 #[test]
3197 fn try_option_unit() {
3198 check_assist(
3199 extract_function,
3200 r##"
3201enum Option<T> { None, Some(T), }
3202use Option::*;
3203fn foo() -> Option<()> {
3204 let n = 1;
3205 $0let k = foo()?;
3206 let m = k + 1;$0
3207 let h = 1 + n;
3208 Some(())
3209}"##,
3210 r##"
3211enum Option<T> { None, Some(T), }
3212use Option::*;
3213fn foo() -> Option<()> {
3214 let n = 1;
3215 fun_name()?;
3216 let h = 1 + n;
3217 Some(())
3218}
3219
3220fn $0fun_name() -> Option<()> {
3221 let k = foo()?;
3222 let m = k + 1;
3223 Some(())
3224}"##,
3225 );
3226 }
3227
3228 #[test]
3229 fn try_result() {
3230 check_assist(
3231 extract_function,
3232 r##"
3233enum Result<T, E> { Ok(T), Err(E), }
3234use Result::*;
3235fn foo() -> Result<(), i64> {
3236 let n = 1;
3237 $0let k = foo()?;
3238 let m = k + 1;$0
3239 let h = 1 + m;
3240 Ok(())
3241}"##,
3242 r##"
3243enum Result<T, E> { Ok(T), Err(E), }
3244use Result::*;
3245fn foo() -> Result<(), i64> {
3246 let n = 1;
3247 let m = fun_name()?;
3248 let h = 1 + m;
3249 Ok(())
3250}
3251
3252fn $0fun_name() -> Result<i32, i64> {
3253 let k = foo()?;
3254 let m = k + 1;
3255 Ok(m)
3256}"##,
3257 );
3258 }
3259
3260 #[test]
3261 fn try_option_with_return() {
3262 check_assist(
3263 extract_function,
3264 r##"
3265enum Option<T> { None, Some(T) }
3266use Option::*;
3267fn foo() -> Option<()> {
3268 let n = 1;
3269 $0let k = foo()?;
3270 if k == 42 {
3271 return None;
3272 }
3273 let m = k + 1;$0
3274 let h = 1 + m;
3275 Some(())
3276}"##,
3277 r##"
3278enum Option<T> { None, Some(T) }
3279use Option::*;
3280fn foo() -> Option<()> {
3281 let n = 1;
3282 let m = fun_name()?;
3283 let h = 1 + m;
3284 Some(())
3285}
3286
3287fn $0fun_name() -> Option<i32> {
3288 let k = foo()?;
3289 if k == 42 {
3290 return None;
3291 }
3292 let m = k + 1;
3293 Some(m)
3294}"##,
3295 );
3296 }
3297
3298 #[test]
3299 fn try_result_with_return() {
3300 check_assist(
3301 extract_function,
3302 r##"
3303enum Result<T, E> { Ok(T), Err(E), }
3304use Result::*;
3305fn foo() -> Result<(), i64> {
3306 let n = 1;
3307 $0let k = foo()?;
3308 if k == 42 {
3309 return Err(1);
3310 }
3311 let m = k + 1;$0
3312 let h = 1 + m;
3313 Ok(())
3314}"##,
3315 r##"
3316enum Result<T, E> { Ok(T), Err(E), }
3317use Result::*;
3318fn foo() -> Result<(), i64> {
3319 let n = 1;
3320 let m = fun_name()?;
3321 let h = 1 + m;
3322 Ok(())
3323}
3324
3325fn $0fun_name() -> Result<i32, i64> {
3326 let k = foo()?;
3327 if k == 42 {
3328 return Err(1);
3329 }
3330 let m = k + 1;
3331 Ok(m)
3332}"##,
3333 );
3334 }
3335
3336 #[test]
3337 fn try_and_break() {
3338 mark::check!(external_control_flow_try_and_bc);
3339 check_assist_not_applicable(
3340 extract_function,
3341 r##"
3342enum Option<T> { None, Some(T) }
3343use Option::*;
3344fn foo() -> Option<()> {
3345 loop {
3346 let n = Some(1);
3347 $0let m = n? + 1;
3348 break;
3349 let k = 2;
3350 let k = k + 1;$0
3351 let r = n + k;
3352 }
3353 Some(())
3354}"##,
3355 );
3356 }
3357
3358 #[test]
3359 fn try_and_return_ok() {
3360 mark::check!(external_control_flow_try_and_return_non_err);
3361 check_assist_not_applicable(
3362 extract_function,
3363 r##"
3364enum Result<T, E> { Ok(T), Err(E), }
3365use Result::*;
3366fn foo() -> Result<(), i64> {
3367 let n = 1;
3368 $0let k = foo()?;
3369 if k == 42 {
3370 return Ok(1);
3371 }
3372 let m = k + 1;$0
3373 let h = 1 + m;
3374 Ok(())
3375}"##,
3376 );
3377 }
3378}