5 use hir::{HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
9 insert_use::{insert_use, ImportScope},
11 node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
14 search::{FileReference, ReferenceCategory, SearchScope},
15 FxIndexSet, RootDatabase,
17 use itertools::Itertools;
22 edit::{AstNodeEdit, IndentLevel},
25 match_ast, ted, SyntaxElement,
26 SyntaxKind::{self, COMMENT},
27 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
31 assist_context::{AssistContext, Assists, TreeMutator},
35 // Assist: extract_function
37 // Extracts selected statements into new function.
55 // fn $0fun_name(n: i32) {
60 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
61 let range = ctx.selection_trimmed();
66 let node = ctx.covering_element();
67 if node.kind() == COMMENT {
68 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
72 println!("initial node: {:?}", node);
74 let node = match node {
75 syntax::NodeOrToken::Node(n) => n,
76 syntax::NodeOrToken::Token(t) => t.parent()?,
79 println!("next node: {:?}", node);
80 let body = extraction_target(&node, range)?;
81 println!("body: {:?}", body);
82 let container_info = body.analyze_container(&ctx.sema)?;
84 let (locals_used, self_param) = body.analyze(&ctx.sema);
86 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
87 let insert_after = node_to_insert_after(&body, anchor)?;
88 let module = ctx.sema.scope(&insert_after).module()?;
90 let ret_ty = body.return_ty(ctx)?;
91 let control_flow = body.external_control_flow(ctx, &container_info)?;
92 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
94 let target_range = body.text_range();
96 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
99 AssistId("extract_function", crate::AssistKind::RefactorExtract),
100 "Extract into function",
103 let outliving_locals: Vec<_> = ret_values.collect();
104 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
105 // We should not have variables that outlive body if we have expression block
110 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
113 name: make::name_ref("fun_name"),
120 mods: container_info,
123 let new_indent = IndentLevel::from_node(&insert_after);
124 let old_indent = fun.body.indent_level();
126 builder.replace(target_range, make_call(ctx, &fun, old_indent));
128 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
129 let insert_offset = insert_after.text_range().end();
131 if fn_def.contains("ControlFlow") {
132 let scope = match scope {
133 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
134 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
135 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
138 let control_flow_enum =
139 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
141 if let Some(control_flow_enum) = control_flow_enum {
142 let mod_path = module.find_use_path_prefixed(
144 ModuleDef::from(control_flow_enum),
145 ctx.config.insert_use.prefix_kind,
148 if let Some(mod_path) = mod_path {
149 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
154 match ctx.config.snippet_cap {
155 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
156 None => builder.insert(insert_offset, fn_def),
162 /// Try to guess what user wants to extract
164 /// We have basically have two cases:
165 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
166 /// Then we can use `ast::Expr`
167 /// * We want a few statements for a block. E.g.
169 /// fn foo() -> i32 {
179 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
180 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
182 ast::Stmt::Item(_) => None,
183 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
184 node.parent().and_then(ast::StmtList::cast)?,
190 println!("node: {:?}", node);
192 // Covering element returned the parent block of one or multiple statements that have been selected
193 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
194 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
195 if block_expr.syntax().text_range() == selection_range {
196 return FunctionBody::from_expr(block_expr.into());
200 // Extract the full statements.
201 println!("stmt_list: {:?}", stmt_list);
202 println!("selection_range: {:?}", selection_range);
203 return Some(FunctionBody::from_range(stmt_list, selection_range));
206 let expr = ast::Expr::cast(node.clone())?;
207 // A node got selected fully
208 if node.text_range() == selection_range {
209 return FunctionBody::from_expr(expr);
212 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
218 self_param: Option<ast::SelfParam>,
220 control_flow: ControlFlow,
223 outliving_locals: Vec<OutlivedLocal>,
236 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
244 #[derive(Debug, Eq, PartialEq)]
248 Tuple(Vec<hir::Type>),
251 /// Where to put extracted function definition
254 /// Extract free function and put right after current top-level function
256 /// Extract method and put right after current function in the impl-block
260 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
261 // probably be merged somehow.
264 kind: Option<FlowKind>,
269 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
270 #[derive(Clone, Debug)]
271 struct ContainerInfo {
274 parent_loop: Option<SyntaxNode>,
275 /// The function's return type, const's type etc.
276 ret_type: Option<hir::Type>,
279 /// Control flow that is exported from extracted function
291 #[derive(Debug, Clone)]
293 /// Return with value (`return $expr;`)
294 Return(Option<ast::Expr>),
298 /// Break with value (`break $expr;`)
299 Break(Option<ast::Expr>),
304 #[derive(Debug, Clone)]
307 Result { ty: hir::Type },
317 fn is_unit(&self) -> bool {
319 RetType::Expr(ty) => ty.is_unit(),
320 RetType::Stmt => true,
325 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
326 /// This is the future function body, the part that is being extracted.
330 Span { parent: ast::StmtList, text_range: TextRange },
334 struct OutlivedLocal {
336 mut_usage_outside_body: bool,
339 /// Container of local variable usages
341 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
342 struct LocalUsages(ide_db::search::UsageSearchResult);
345 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
347 Definition::Local(var)
349 .in_scope(SearchScope::single_file(ctx.file_id()))
354 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
355 self.0.iter().flat_map(|(_, rs)| rs)
360 fn return_type(&self, ctx: &AssistContext) -> FunType {
362 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
363 RetType::Expr(ty) => FunType::Single(ty.clone()),
364 RetType::Stmt => match self.outliving_locals.as_slice() {
366 [var] => FunType::Single(var.local.ty(ctx.db())),
368 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
369 FunType::Tuple(types)
377 fn is_ref(&self) -> bool {
378 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
383 fn kind(&self) -> ParamKind {
384 match (self.move_local, self.requires_mut, self.is_copy) {
385 (false, true, _) => ParamKind::MutRef,
386 (false, false, false) => ParamKind::SharedRef,
387 (true, true, _) => ParamKind::MutValue,
388 (_, false, _) => ParamKind::Value,
392 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
393 let var = path_expr_from_local(ctx, self.var);
395 ParamKind::Value | ParamKind::MutValue => var,
396 ParamKind::SharedRef => make::expr_ref(var, false),
397 ParamKind::MutRef => make::expr_ref(var, true),
401 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
402 let var = self.var.name(ctx.db()).unwrap().to_string();
403 let var_name = make::name(&var);
404 let pat = match self.kind() {
405 ParamKind::MutValue => make::ident_pat(false, true, var_name),
406 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
407 make::ext::simple_ident_pat(var_name)
411 let ty = make_ty(&self.ty, ctx, module);
412 let ty = match self.kind() {
413 ParamKind::Value | ParamKind::MutValue => ty,
414 ParamKind::SharedRef => make::ty_ref(ty, false),
415 ParamKind::MutRef => make::ty_ref(ty, true),
418 make::param(pat.into(), ty)
423 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
425 // We favour Result for `expr?`
426 return Some(TryKind::Result { ty });
428 let adt = ty.as_adt()?;
429 let name = adt.name(ctx.db());
430 // FIXME: use lang items to determine if it is std type or user defined
431 // E.g. if user happens to define type named `Option`, we would have false positive
432 match name.to_string().as_str() {
433 "Option" => Some(TryKind::Option),
434 "Result" => Some(TryKind::Result { ty }),
441 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
443 FlowKind::Return(_) => make::expr_return(expr),
444 FlowKind::Break(_) => make::expr_break(expr),
445 FlowKind::Try { .. } => {
446 stdx::never!("cannot have result handler with try");
447 expr.unwrap_or_else(|| make::expr_return(None))
449 FlowKind::Continue => {
450 stdx::always!(expr.is_none(), "continue with value is not possible");
451 make::expr_continue()
456 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
458 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
459 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
461 FlowKind::Try { .. } => {
462 stdx::never!("try does not have defined expr_ty");
471 fn parent(&self) -> Option<SyntaxNode> {
473 FunctionBody::Expr(expr) => expr.syntax().parent(),
474 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
478 fn from_expr(expr: ast::Expr) -> Option<Self> {
480 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
481 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
482 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
483 expr => Some(Self::Expr(expr)),
487 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
488 let full_body = parent.syntax().children_with_tokens();
489 for st in parent.syntax().children_with_tokens() {
490 println!("Statement: {:?}", &st);
493 let mut text_range = full_body
494 .map(|stmt| stmt.text_range())
495 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
496 .reduce(|acc, stmt| acc.cover(stmt));
498 println!("from_range text_range first: {:?}", text_range);
499 if let Some(tail_range) = parent
501 .map(|it| it.syntax().text_range())
502 .filter(|&it| selected.intersect(it).is_some())
504 text_range = Some(match text_range {
505 Some(text_range) => text_range.cover(tail_range),
509 println!("from_range text_range second: {:?}", text_range);
511 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
514 fn indent_level(&self) -> IndentLevel {
516 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
517 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
521 fn tail_expr(&self) -> Option<ast::Expr> {
523 FunctionBody::Expr(expr) => Some(expr.clone()),
524 FunctionBody::Span { parent, text_range } => {
525 let tail_expr = parent.tail_expr()?;
526 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
531 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
533 FunctionBody::Expr(expr) => walk_expr(expr, cb),
534 FunctionBody::Span { parent, text_range } => {
537 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
538 .filter_map(|stmt| match stmt {
539 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
540 ast::Stmt::Item(_) => None,
541 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
543 .for_each(|expr| walk_expr(&expr, cb));
544 if let Some(expr) = parent
546 .filter(|it| text_range.contains_range(it.syntax().text_range()))
548 walk_expr(&expr, cb);
554 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
556 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
557 FunctionBody::Span { parent, text_range } => {
560 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
561 .filter_map(|stmt| match stmt {
562 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
563 ast::Stmt::Item(_) => None,
564 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
566 .for_each(|expr| preorder_expr(&expr, cb));
567 if let Some(expr) = parent
569 .filter(|it| text_range.contains_range(it.syntax().text_range()))
571 preorder_expr(&expr, cb);
577 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
579 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
580 FunctionBody::Span { parent, text_range } => {
583 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
584 .for_each(|stmt| match stmt {
585 ast::Stmt::ExprStmt(expr_stmt) => {
586 if let Some(expr) = expr_stmt.expr() {
587 walk_patterns_in_expr(&expr, cb)
590 ast::Stmt::Item(_) => (),
591 ast::Stmt::LetStmt(stmt) => {
592 if let Some(pat) = stmt.pat() {
595 if let Some(expr) = stmt.initializer() {
596 walk_patterns_in_expr(&expr, cb);
600 if let Some(expr) = parent
602 .filter(|it| text_range.contains_range(it.syntax().text_range()))
604 walk_patterns_in_expr(&expr, cb);
610 fn text_range(&self) -> TextRange {
612 FunctionBody::Expr(expr) => expr.syntax().text_range(),
613 &FunctionBody::Span { text_range, .. } => text_range,
617 fn contains_range(&self, range: TextRange) -> bool {
618 self.text_range().contains_range(range)
621 fn precedes_range(&self, range: TextRange) -> bool {
622 self.text_range().end() <= range.start()
625 fn contains_node(&self, node: &SyntaxNode) -> bool {
626 self.contains_range(node.text_range())
631 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
632 /// whether it contains an await expression.
635 sema: &Semantics<RootDatabase>,
636 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
637 let mut self_param = None;
638 let mut res = FxIndexSet::default();
639 let mut cb = |name_ref: Option<_>| {
641 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
643 NameRefClass::Definition(Definition::Local(local_ref))
644 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
648 let InFile { file_id, value } = local_ref.source(sema.db);
649 // locals defined inside macros are not relevant to us
650 if !file_id.is_macro() {
652 Either::Right(it) => {
653 self_param.replace(it);
656 res.insert(local_ref);
661 self.walk_expr(&mut |expr| match expr {
662 ast::Expr::PathExpr(path_expr) => {
663 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
665 ast::Expr::MacroCall(call) => {
666 if let Some(tt) = call.token_tree() {
668 .children_with_tokens()
669 .flat_map(SyntaxElement::into_token)
670 .filter(|it| it.kind() == SyntaxKind::IDENT)
671 .flat_map(|t| sema.descend_into_macros(t))
672 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
680 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
681 let mut ancestors = self.parent()?.ancestors();
682 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
683 let mut parent_loop = None;
684 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
687 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
689 parent_loop.get_or_insert(loop_.syntax().clone());
692 let (is_const, expr, ty) = loop {
693 let anc = ancestors.next()?;
696 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
697 ast::BlockExpr(block_expr) => {
698 let (constness, block) = match block_expr.modifier() {
699 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
700 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
701 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
704 let expr = Some(ast::Expr::BlockExpr(block));
705 (constness, expr.clone(), infer_expr_opt(expr))
708 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
710 ast::Static(statik) => {
711 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
713 ast::ConstArg(ca) => {
714 (true, ca.expr(), infer_expr_opt(ca.expr()))
716 ast::Const(konst) => {
717 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
719 ast::ConstParam(cp) => {
720 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
722 ast::ConstBlockPat(cbp) => {
723 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
724 (true, expr.clone(), infer_expr_opt(expr))
726 ast::Variant(__) => return None,
727 ast::Meta(__) => return None,
728 ast::LoopExpr(it) => {
729 set_parent_loop(&it);
732 ast::ForExpr(it) => {
733 set_parent_loop(&it);
736 ast::WhileExpr(it) => {
737 set_parent_loop(&it);
744 let container_tail = match expr? {
745 ast::Expr::BlockExpr(block) => block.tail_expr(),
749 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
750 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
752 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
755 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
756 match self.tail_expr() {
757 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
758 None => Some(RetType::Stmt),
762 /// Local variables defined inside `body` that are accessed outside of it
765 ctx: &'a AssistContext,
767 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
768 let parent = parent.clone();
769 let range = self.text_range();
770 locals_defined_in_body(&ctx.sema, self)
772 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
775 /// Analyses the function body for external control flow.
776 fn external_control_flow(
779 container_info: &ContainerInfo,
780 ) -> Option<ControlFlow> {
781 let mut ret_expr = None;
782 let mut try_expr = None;
783 let mut break_expr = None;
784 let mut continue_expr = None;
785 let mut is_async = false;
786 let mut _is_unsafe = false;
788 let mut unsafe_depth = 0;
789 let mut loop_depth = 0;
791 self.preorder_expr(&mut |expr| {
792 let expr = match expr {
793 WalkEvent::Enter(e) => e,
794 WalkEvent::Leave(expr) => {
796 ast::Expr::LoopExpr(_)
797 | ast::Expr::ForExpr(_)
798 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
799 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
808 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
811 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
814 ast::Expr::ReturnExpr(it) => {
817 ast::Expr::TryExpr(it) => {
820 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
821 break_expr = Some(it);
823 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
824 continue_expr = Some(it);
826 ast::Expr::AwaitExpr(_) => is_async = true,
827 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
828 // to just lift that out of there
829 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
835 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
836 (Some(_), _, None, None) => {
837 let ret_ty = container_info.ret_type.clone()?;
838 let kind = TryKind::of_ty(ret_ty, ctx)?;
840 Some(FlowKind::Try { kind })
842 (Some(_), _, _, _) => {
843 cov_mark::hit!(external_control_flow_try_and_bc);
846 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
847 (None, Some(_), _, _) => {
848 cov_mark::hit!(external_control_flow_return_and_bc);
851 (None, None, Some(_), Some(_)) => {
852 cov_mark::hit!(external_control_flow_break_and_continue);
855 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
856 (None, None, None, Some(_)) => Some(FlowKind::Continue),
857 (None, None, None, None) => None,
860 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
863 /// find variables that should be extracted as params
865 /// Computes additional info that affects param type and mutability
866 fn extracted_function_params(
869 container_info: &ContainerInfo,
870 locals: impl Iterator<Item = Local>,
873 .map(|local| (local, local.source(ctx.db())))
874 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
875 .filter_map(|(local, src)| match src.value {
876 Either::Left(src) => Some((local, src)),
877 Either::Right(_) => {
878 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
883 let usages = LocalUsages::find_local_usages(ctx, var);
884 let ty = var.ty(ctx.db());
886 let defined_outside_parent_loop = container_info
889 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
891 let is_copy = ty.is_copy(ctx.db());
892 let has_usages = self.has_usages_after_body(&usages);
894 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
895 // We can move the value into the function call if it's not used after the call,
896 // if the var is not used but defined outside a loop we are extracting from we can't move it either
897 // as the function will reuse it in the next iteration.
898 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
899 Param { var, ty, move_local, requires_mut, is_copy }
904 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
905 usages.iter().any(|reference| self.precedes_range(reference.range))
909 /// checks if relevant var is used with `&mut` access inside body
910 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
913 .filter(|reference| body.contains_range(reference.range))
914 .any(|reference| reference_is_exclusive(reference, body, ctx))
917 /// checks if this reference requires `&mut` access inside node
918 fn reference_is_exclusive(
919 reference: &FileReference,
920 node: &dyn HasTokenAtOffset,
923 // we directly modify variable with set: `n = 0`, `n += 1`
924 if reference.category == Some(ReferenceCategory::Write) {
928 // we take `&mut` reference to variable: `&mut v`
929 let path = match path_element_of_reference(node, reference) {
931 None => return false,
934 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
937 /// checks if this expr requires `&mut` access, recurses on field access
938 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
939 if let ast::Expr::MacroCall(_) = expr {
940 // FIXME: expand macro and check output for mutable usages of the variable?
944 let parent = expr.syntax().parent()?;
946 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
947 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
948 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
953 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
954 return Some(ref_expr.mut_token().is_some());
957 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
958 let func = ctx.sema.resolve_method_call(&method_call)?;
959 let self_param = func.self_param(ctx.db())?;
960 let access = self_param.access(ctx.db());
962 return Some(matches!(access, hir::Access::Exclusive));
965 if let Some(field) = ast::FieldExpr::cast(parent) {
966 return expr_require_exclusive_access(ctx, &field.into());
972 trait HasTokenAtOffset {
973 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
976 impl HasTokenAtOffset for SyntaxNode {
977 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
978 SyntaxNode::token_at_offset(self, offset)
982 impl HasTokenAtOffset for FunctionBody {
983 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
985 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
986 FunctionBody::Span { parent, text_range } => {
987 match parent.syntax().token_at_offset(offset) {
988 TokenAtOffset::None => TokenAtOffset::None,
989 TokenAtOffset::Single(t) => {
990 if text_range.contains_range(t.text_range()) {
991 TokenAtOffset::Single(t)
996 TokenAtOffset::Between(a, b) => {
998 text_range.contains_range(a.text_range()),
999 text_range.contains_range(b.text_range()),
1001 (true, true) => TokenAtOffset::Between(a, b),
1002 (true, false) => TokenAtOffset::Single(a),
1003 (false, true) => TokenAtOffset::Single(b),
1004 (false, false) => TokenAtOffset::None,
1013 /// find relevant `ast::Expr` for reference
1017 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1018 fn path_element_of_reference(
1019 node: &dyn HasTokenAtOffset,
1020 reference: &FileReference,
1021 ) -> Option<ast::Expr> {
1022 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1023 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1026 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1027 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1031 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1032 "unexpected expression type for variable usage: {:?}",
1038 /// list local variables defined inside `body`
1039 fn locals_defined_in_body(
1040 sema: &Semantics<RootDatabase>,
1041 body: &FunctionBody,
1042 ) -> FxIndexSet<Local> {
1043 // FIXME: this doesn't work well with macros
1044 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1045 let mut res = FxIndexSet::default();
1046 body.walk_pat(&mut |pat| {
1047 if let ast::Pat::IdentPat(pat) = pat {
1048 if let Some(local) = sema.to_def(&pat) {
1056 /// Returns usage details if local variable is used after(outside of) body
1057 fn local_outlives_body(
1058 ctx: &AssistContext,
1059 body_range: TextRange,
1061 parent: &SyntaxNode,
1062 ) -> Option<OutlivedLocal> {
1063 let usages = LocalUsages::find_local_usages(ctx, local);
1064 let mut has_mut_usages = false;
1065 let mut any_outlives = false;
1066 for usage in usages.iter() {
1067 if body_range.end() <= usage.range.start() {
1068 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1069 any_outlives |= true;
1071 break; // no need to check more elements we have all the info we wanted
1078 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1081 /// checks if the relevant local was defined before(outside of) body
1082 fn is_defined_outside_of_body(
1083 ctx: &AssistContext,
1084 body: &FunctionBody,
1085 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1087 src.file_id.original_file(ctx.db()) == ctx.file_id()
1088 && !body.contains_node(either_syntax(&src.value))
1091 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1093 Either::Left(pat) => pat.syntax(),
1094 Either::Right(it) => it.syntax(),
1098 /// find where to put extracted function definition
1100 /// Function should be put right after returned node
1101 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1102 let node = match body {
1103 FunctionBody::Expr(e) => e.syntax(),
1104 FunctionBody::Span { parent, .. } => parent.syntax(),
1106 let mut ancestors = node.ancestors().peekable();
1107 let mut last_ancestor = None;
1108 while let Some(next_ancestor) = ancestors.next() {
1109 match next_ancestor.kind() {
1110 SyntaxKind::SOURCE_FILE => break,
1111 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1112 SyntaxKind::ITEM_LIST => {
1113 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1117 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1120 SyntaxKind::ASSOC_ITEM_LIST => {
1121 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1127 last_ancestor = Some(next_ancestor);
1132 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1133 let ret_ty = fun.return_type(ctx);
1135 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1136 let name = fun.name.clone();
1137 let mut call_expr = if fun.self_param.is_some() {
1138 let self_arg = make::expr_path(make::ext::ident_path("self"));
1139 make::expr_method_call(self_arg, name, args)
1141 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1142 make::expr_call(func, args)
1145 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1147 if fun.control_flow.is_async {
1148 call_expr = make::expr_await(call_expr);
1150 let expr = handler.make_call_expr(call_expr).indent(indent);
1152 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1154 let mut buf = String::new();
1155 match fun.outliving_locals.as_slice() {
1158 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1161 buf.push_str("let (");
1162 let bindings = vars.iter().format_with(", ", |local, f| {
1163 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1165 format_to!(buf, "{}", bindings);
1166 buf.push_str(") = ");
1170 format_to!(buf, "{}", expr);
1171 let insert_comma = fun
1174 .and_then(ast::MatchArm::cast)
1175 .map_or(false, |it| it.comma_token().is_none());
1178 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1186 Try { kind: TryKind },
1187 If { action: FlowKind },
1188 IfOption { action: FlowKind },
1189 MatchOption { none: FlowKind },
1190 MatchResult { err: FlowKind },
1194 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1195 match &fun.control_flow.kind {
1196 None => FlowHandler::None,
1197 Some(flow_kind) => {
1198 let action = flow_kind.clone();
1199 if *ret_ty == FunType::Unit {
1201 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1202 FlowHandler::If { action }
1204 FlowKind::Return(_) | FlowKind::Break(_) => {
1205 FlowHandler::IfOption { action }
1207 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1211 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1212 FlowHandler::MatchOption { none: action }
1214 FlowKind::Return(_) | FlowKind::Break(_) => {
1215 FlowHandler::MatchResult { err: action }
1217 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1224 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1226 FlowHandler::None => call_expr,
1227 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1228 FlowHandler::If { action } => {
1229 let action = action.make_result_handler(None);
1230 let stmt = make::expr_stmt(action);
1231 let block = make::block_expr(iter::once(stmt.into()), None);
1232 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1233 let condition = make::condition(
1236 make::tuple_struct_pat(
1237 controlflow_break_path,
1238 iter::once(make::wildcard_pat().into()),
1243 make::expr_if(condition, block, None)
1245 FlowHandler::IfOption { action } => {
1246 let path = make::ext::ident_path("Some");
1247 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1248 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1249 let cond = make::condition(call_expr, Some(pattern.into()));
1250 let value = make::expr_path(make::ext::ident_path("value"));
1251 let action_expr = action.make_result_handler(Some(value));
1252 let action_stmt = make::expr_stmt(action_expr);
1253 let then = make::block_expr(iter::once(action_stmt.into()), None);
1254 make::expr_if(cond, then, None)
1256 FlowHandler::MatchOption { none } => {
1257 let some_name = "value";
1260 let path = make::ext::ident_path("Some");
1261 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1262 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1263 let value = make::expr_path(make::ext::ident_path(some_name));
1264 make::match_arm(iter::once(pat.into()), None, value)
1267 let path = make::ext::ident_path("None");
1268 let pat = make::path_pat(path);
1269 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1271 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1272 make::expr_match(call_expr, arms)
1274 FlowHandler::MatchResult { err } => {
1275 let ok_name = "value";
1276 let err_name = "value";
1279 let path = make::ext::ident_path("Ok");
1280 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1281 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1282 let value = make::expr_path(make::ext::ident_path(ok_name));
1283 make::match_arm(iter::once(pat.into()), None, value)
1286 let path = make::ext::ident_path("Err");
1287 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1288 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1289 let value = make::expr_path(make::ext::ident_path(err_name));
1291 iter::once(pat.into()),
1293 err.make_result_handler(Some(value)),
1296 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1297 make::expr_match(call_expr, arms)
1303 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1304 let name = var.name(ctx.db()).unwrap().to_string();
1305 make::expr_path(make::ext::ident_path(&name))
1309 ctx: &AssistContext,
1310 module: hir::Module,
1312 old_indent: IndentLevel,
1313 new_indent: IndentLevel,
1315 let mut fn_def = String::new();
1316 let params = fun.make_param_list(ctx, module);
1317 let ret_ty = fun.make_ret_ty(ctx, module);
1318 let body = make_body(ctx, old_indent, new_indent, fun);
1319 let const_kw = if fun.mods.is_const { "const " } else { "" };
1320 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1321 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1322 match ctx.config.snippet_cap {
1323 Some(_) => format_to!(
1325 "\n\n{}{}{}{}fn $0{}{}",
1335 "\n\n{}{}{}{}fn {}{}",
1344 if let Some(ret_ty) = ret_ty {
1345 format_to!(fn_def, " {}", ret_ty);
1347 format_to!(fn_def, " {}", body);
1353 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1354 let self_param = self.self_param.clone();
1355 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1356 make::param_list(self_param, params)
1359 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1360 let fun_ty = self.return_type(ctx);
1361 let handler = if self.mods.is_in_tail {
1364 FlowHandler::from_ret_ty(self, &fun_ty)
1366 let ret_ty = match &handler {
1367 FlowHandler::None => {
1368 if matches!(fun_ty, FunType::Unit) {
1371 fun_ty.make_ty(ctx, module)
1373 FlowHandler::Try { kind: TryKind::Option } => {
1374 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1376 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1377 let handler_ty = parent_ret_ty
1380 .map(|ty| make_ty(&ty, ctx, module))
1381 .unwrap_or_else(make::ty_placeholder);
1382 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1384 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1385 FlowHandler::IfOption { action } => {
1386 let handler_ty = action
1388 .map(|ty| make_ty(&ty, ctx, module))
1389 .unwrap_or_else(make::ty_placeholder);
1390 make::ext::ty_option(handler_ty)
1392 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1393 FlowHandler::MatchResult { err } => {
1394 let handler_ty = err
1396 .map(|ty| make_ty(&ty, ctx, module))
1397 .unwrap_or_else(make::ty_placeholder);
1398 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1401 Some(make::ret_type(ret_ty))
1406 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1408 FunType::Unit => make::ty_unit(),
1409 FunType::Single(ty) => make_ty(ty, ctx, module),
1410 FunType::Tuple(types) => match types.as_slice() {
1412 stdx::never!("tuple type with 0 elements");
1416 stdx::never!("tuple type with 1 element");
1417 make_ty(ty, ctx, module)
1420 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1421 make::ty_tuple(types)
1429 ctx: &AssistContext,
1430 old_indent: IndentLevel,
1431 new_indent: IndentLevel,
1433 ) -> ast::BlockExpr {
1434 let ret_ty = fun.return_type(ctx);
1435 let handler = if fun.mods.is_in_tail {
1438 FlowHandler::from_ret_ty(fun, &ret_ty)
1441 println!("making body: {:?}", fun.body);
1442 let block = match &fun.body {
1443 FunctionBody::Expr(expr) => {
1444 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1445 let expr = ast::Expr::cast(expr).unwrap();
1447 ast::Expr::BlockExpr(block) => {
1448 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1449 let block = block.dedent(old_indent);
1450 // Recreate the block for formatting consistency with other extracted functions.
1451 make::block_expr(block.statements(), block.tail_expr())
1454 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1456 make::block_expr(Vec::new(), Some(expr))
1460 FunctionBody::Span { parent, text_range } => {
1461 let mut elements: Vec<_> = parent
1463 .children_with_tokens()
1464 .filter(|it| text_range.contains_range(it.text_range()))
1465 .map(|it| match it {
1466 syntax::NodeOrToken::Node(n) => {
1467 println!("Found node: {:?}", n);
1468 let node_rewritten = rewrite_body_segment(ctx, &fun.params, &handler, &n);
1470 syntax::NodeOrToken::Node(node_rewritten)
1472 syntax::NodeOrToken::Token(t) => {
1473 println!("Found token: {:?}", t);
1474 syntax::NodeOrToken::Token(t)
1479 let mut tail_expr = match elements.pop() {
1480 Some(element) => match element {
1481 syntax::NodeOrToken::Node(node) => {
1482 ast::Expr::cast(node.clone()).or_else(|| {
1483 elements.push(syntax::NodeOrToken::Node(node));
1487 syntax::NodeOrToken::Token(token) if token.kind() == COMMENT => {
1488 elements.push(syntax::NodeOrToken::Token(token));
1496 if tail_expr.is_none() {
1497 match fun.outliving_locals.as_slice() {
1500 tail_expr = Some(path_expr_from_local(ctx, var.local));
1503 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1504 let expr = make::expr_tuple(exprs);
1505 tail_expr = Some(expr);
1510 let body_indent = IndentLevel(1);
1511 let elements: Vec<SyntaxElement> = elements
1513 .map(|stmt| match stmt {
1514 syntax::NodeOrToken::Node(n) => {
1515 let ast_element = ast::Stmt::cast(n).unwrap();
1516 let indented = ast_element.dedent(old_indent).indent(body_indent);
1517 let ast_node = indented.syntax().clone_subtree();
1518 syntax::NodeOrToken::try_from(ast_node).unwrap()
1520 syntax::NodeOrToken::Token(t) => syntax::NodeOrToken::try_from(t).unwrap(),
1522 .collect::<Vec<SyntaxElement>>();
1523 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1525 for element in &elements {
1526 println!("element: {:?}", element);
1529 make::block_expr_full(elements, tail_expr)
1531 // make::block_expr(parent.statements().into_iter(), tail_expr)
1535 let block = match &handler {
1536 FlowHandler::None => block,
1537 FlowHandler::Try { kind } => {
1538 let block = with_default_tail_expr(block, make::expr_unit());
1539 map_tail_expr(block, |tail_expr| {
1540 let constructor = match kind {
1541 TryKind::Option => "Some",
1542 TryKind::Result { .. } => "Ok",
1544 let func = make::expr_path(make::ext::ident_path(constructor));
1545 let args = make::arg_list(iter::once(tail_expr));
1546 make::expr_call(func, args)
1549 FlowHandler::If { .. } => {
1550 let controlflow_continue = make::expr_call(
1551 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1552 make::arg_list(iter::once(make::expr_unit())),
1554 with_tail_expr(block, controlflow_continue.into())
1556 FlowHandler::IfOption { .. } => {
1557 let none = make::expr_path(make::ext::ident_path("None"));
1558 with_tail_expr(block, none)
1560 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1561 let some = make::expr_path(make::ext::ident_path("Some"));
1562 let args = make::arg_list(iter::once(tail_expr));
1563 make::expr_call(some, args)
1565 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1566 let ok = make::expr_path(make::ext::ident_path("Ok"));
1567 let args = make::arg_list(iter::once(tail_expr));
1568 make::expr_call(ok, args)
1572 block.indent(new_indent)
1575 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1576 let tail_expr = match block.tail_expr() {
1577 Some(tail_expr) => tail_expr,
1578 None => return block,
1580 make::block_expr(block.statements(), Some(f(tail_expr)))
1583 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1584 match block.tail_expr() {
1586 None => make::block_expr(block.statements(), Some(tail_expr)),
1590 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1591 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1592 let stmts = block.statements().chain(stmt_tail);
1593 make::block_expr(stmts, Some(tail_expr))
1596 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1597 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1600 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1601 let ty_str = format_type(ty, ctx, module);
1605 fn rewrite_body_segment(
1606 ctx: &AssistContext,
1608 handler: &FlowHandler,
1609 syntax: &SyntaxNode,
1611 let syntax = fix_param_usages(ctx, params, syntax);
1612 update_external_control_flow(handler, &syntax);
1616 /// change all usages to account for added `&`/`&mut` for some params
1617 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1618 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1620 let tm = TreeMutator::new(syntax);
1622 for param in params {
1623 if !param.kind().is_ref() {
1627 let usages = LocalUsages::find_local_usages(ctx, param.var);
1630 .filter(|reference| syntax.text_range().contains_range(reference.range))
1631 .filter_map(|reference| path_element_of_reference(syntax, reference))
1632 .map(|expr| tm.make_mut(&expr));
1634 usages_for_param.push((param, usages.collect()));
1637 let res = tm.make_syntax_mut(syntax);
1639 for (param, usages) in usages_for_param {
1640 for usage in usages {
1641 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1642 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1645 Some(ast::Expr::RefExpr(node))
1646 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1648 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1650 Some(ast::Expr::RefExpr(node))
1651 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1653 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1656 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1657 ted::replace(usage.syntax(), p.syntax())
1666 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1667 let mut nested_loop = None;
1668 let mut nested_scope = None;
1669 for event in syntax.preorder() {
1671 WalkEvent::Enter(e) => match e.kind() {
1672 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1673 if nested_loop.is_none() {
1674 nested_loop = Some(e.clone());
1679 | SyntaxKind::STATIC
1681 | SyntaxKind::MODULE => {
1682 if nested_scope.is_none() {
1683 nested_scope = Some(e.clone());
1688 WalkEvent::Leave(e) => {
1689 if nested_scope.is_none() {
1690 if let Some(expr) = ast::Expr::cast(e.clone()) {
1692 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1693 let expr = return_expr.expr();
1694 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1695 ted::replace(return_expr.syntax(), replacement.syntax())
1698 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1699 let expr = break_expr.expr();
1700 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1701 ted::replace(break_expr.syntax(), replacement.syntax())
1704 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1705 if let Some(replacement) = make_rewritten_flow(handler, None) {
1706 ted::replace(continue_expr.syntax(), replacement.syntax())
1716 if nested_loop.as_ref() == Some(&e) {
1719 if nested_scope.as_ref() == Some(&e) {
1720 nested_scope = None;
1727 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1728 let value = match handler {
1729 FlowHandler::None | FlowHandler::Try { .. } => return None,
1730 FlowHandler::If { .. } => make::expr_call(
1731 make::expr_path(make::path_from_text("ControlFlow::Break")),
1732 make::arg_list(iter::once(make::expr_unit())),
1734 FlowHandler::IfOption { .. } => {
1735 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1736 let args = make::arg_list(iter::once(expr));
1737 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1739 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1740 FlowHandler::MatchResult { .. } => {
1741 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1742 let args = make::arg_list(iter::once(expr));
1743 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1746 Some(make::expr_return(Some(value)).clone_for_update())
1751 use crate::tests::{check_assist, check_assist_not_applicable};
1756 fn no_args_from_binary_expr() {
1769 fn $0fun_name() -> i32 {
1777 fn no_args_from_binary_expr_in_module() {
1793 fn $0fun_name() -> i32 {
1802 fn no_args_from_binary_expr_indented() {
1815 fn $0fun_name() -> i32 {
1823 fn no_args_from_stmt_with_last_expr() {
1839 fn $0fun_name() -> i32 {
1848 fn no_args_from_stmt_unit() {
1896 fn no_args_if_else() {
1901 $0if true { 1 } else { 2 }$0
1909 fn $0fun_name() -> i32 {
1910 if true { 1 } else { 2 }
1917 fn no_args_if_let_else() {
1922 $0if let true = false { 1 } else { 2 }$0
1930 fn $0fun_name() -> i32 {
1931 if let true = false { 1 } else { 2 }
1938 fn no_args_match() {
1954 fn $0fun_name() -> i32 {
1965 fn no_args_while() {
1991 $0for v in &[0, 1] { }$0
2000 for v in &[0, 1] { }
2007 fn no_args_from_loop_unit() {
2022 fn $0fun_name() -> ! {
2032 fn no_args_from_loop_with_return() {
2048 fn $0fun_name() -> i32 {
2059 fn no_args_from_match() {
2064 let v: i32 = $0match Some(1) {
2072 let v: i32 = fun_name();
2075 fn $0fun_name() -> i32 {
2086 fn extract_partial_block_single_line() {
2092 let mut v = $0n * n;$0
2099 let mut v = fun_name(n);
2103 fn $0fun_name(n: i32) -> i32 {
2112 fn extract_partial_block() {
2119 let mut v = m $0* n;
2129 let (mut v, mut w) = fun_name(m, n);
2134 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2144 fn argument_form_expr() {
2159 fn $0fun_name(n: u32) -> u32 {
2167 fn argument_used_twice_form_expr() {
2182 fn $0fun_name(n: u32) -> u32 {
2190 fn two_arguments_form_expr() {
2207 fn $0fun_name(n: u32, m: u32) -> u32 {
2215 fn argument_and_locals() {
2231 fn $0fun_name(n: u32) -> u32 {
2240 fn in_comment_is_not_applicable() {
2241 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2242 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2246 fn part_of_expr_stmt() {
2259 fn $0fun_name() -> i32 {
2267 fn function_expr() {
2288 fn extract_from_nested() {
2294 let tuple = match x {
2295 true => ($02 + 2$0, true)
2303 let tuple = match x {
2304 true => (fun_name(), true)
2309 fn $0fun_name() -> i32 {
2317 fn param_from_closure() {
2322 let lambda = |x: u32| $0x * 2$0;
2327 let lambda = |x: u32| fun_name(x);
2330 fn $0fun_name(x: u32) -> u32 {
2338 fn extract_return_stmt() {
2351 fn $0fun_name() -> u32 {
2359 fn does_not_add_extra_whitespace() {
2376 fn $0fun_name() -> u32 {
2401 fn $0fun_name() -> i32 {
2414 let v = $00f32 as u32$0;
2422 fn $0fun_name() -> u32 {
2430 fn return_not_applicable() {
2431 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2435 fn method_to_freestanding() {
2442 fn foo(&self) -> i32 {
2451 fn foo(&self) -> i32 {
2456 fn $0fun_name() -> i32 {
2464 fn method_with_reference() {
2468 struct S { f: i32 };
2471 fn foo(&self) -> i32 {
2477 struct S { f: i32 };
2480 fn foo(&self) -> i32 {
2484 fn $0fun_name(&self) -> i32 {
2493 fn method_with_mut() {
2497 struct S { f: i32 };
2506 struct S { f: i32 };
2513 fn $0fun_name(&mut self) {
2522 fn variable_defined_inside_and_used_after_no_ret() {
2535 let k = fun_name(n);
2539 fn $0fun_name(n: i32) -> i32 {
2548 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2554 $0let mut k = n * n;$0
2561 let mut k = fun_name(n);
2565 fn $0fun_name(n: i32) -> i32 {
2574 fn two_variables_defined_inside_and_used_after_no_ret() {
2588 let (k, m) = fun_name(n);
2592 fn $0fun_name(n: i32) -> (i32, i32) {
2602 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2608 $0let mut k = n * n;
2619 let (mut k, mut m, o) = fun_name(n);
2624 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2636 fn nontrivial_patterns_define_variables() {
2640 struct Counter(i32);
2642 $0let Counter(n) = Counter(0);$0
2647 struct Counter(i32);
2653 fn $0fun_name() -> i32 {
2654 let Counter(n) = Counter(0);
2662 fn struct_with_two_fields_pattern_define_variables() {
2666 struct Counter { n: i32, m: i32 };
2668 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2673 struct Counter { n: i32, m: i32 };
2675 let (n, k) = fun_name();
2679 fn $0fun_name() -> (i32, i32) {
2680 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2688 fn mut_var_from_outer_scope() {
2705 fn $0fun_name(n: &mut i32) {
2713 fn mut_field_from_outer_scope() {
2719 let mut c = C { n: 0 };
2727 let mut c = C { n: 0 };
2732 fn $0fun_name(c: &mut C) {
2740 fn mut_nested_field_from_outer_scope() {
2747 let mut c = C { p: P { n: 0 } };
2748 let mut v = C { p: P { n: 0 } };
2749 let u = C { p: P { n: 0 } };
2751 let r = &mut v.p.n;$0
2752 let m = c.p.n + v.p.n + u.p.n;
2759 let mut c = C { p: P { n: 0 } };
2760 let mut v = C { p: P { n: 0 } };
2761 let u = C { p: P { n: 0 } };
2762 fun_name(&mut c, &u, &mut v);
2763 let m = c.p.n + v.p.n + u.p.n;
2766 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2775 fn mut_param_many_usages_stmt() {
2781 fn succ(&self) -> Self;
2782 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2785 fn succ(&self) -> Self { *self + 1 }
2804 fn succ(&self) -> Self;
2805 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2808 fn succ(&self) -> Self { *self + 1 }
2816 fn $0fun_name(n: &mut i32) {
2832 fn mut_param_many_usages_expr() {
2838 fn succ(&self) -> Self;
2839 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2842 fn succ(&self) -> Self { *self + 1 }
2863 fn succ(&self) -> Self;
2864 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2867 fn succ(&self) -> Self { *self + 1 }
2875 fn $0fun_name(n: &mut i32) {
2891 fn mut_param_by_value() {
2906 fn $0fun_name(mut n: i32) {
2914 fn mut_param_because_of_mut_ref() {
2932 fn $0fun_name(n: &mut i32) {
2941 fn mut_param_by_value_because_of_mut_ref() {
2957 fn $0fun_name(mut n: i32) {
2966 fn mut_method_call() {
2974 fn inc(&mut self) { *self += 1 }
2986 fn inc(&mut self) { *self += 1 }
2993 fn $0fun_name(mut n: i32) {
3001 fn shared_method_call() {
3009 fn succ(&self) { *self + 1 }
3021 fn succ(&self) { *self + 1 }
3028 fn $0fun_name(n: i32) {
3036 fn mut_method_call_with_other_receiver() {
3041 fn inc(&mut self, n: i32);
3044 fn inc(&mut self, n: i32) { *self += n }
3054 fn inc(&mut self, n: i32);
3057 fn inc(&mut self, n: i32) { *self += n }
3064 fn $0fun_name(n: i32) {
3073 fn non_copy_without_usages_after() {
3077 struct Counter(i32);
3084 struct Counter(i32);
3090 fn $0fun_name(c: Counter) {
3098 fn non_copy_used_after() {
3102 struct Counter(i32);
3110 struct Counter(i32);
3117 fn $0fun_name(c: &Counter) {
3125 fn copy_used_after() {
3143 fn $0fun_name(n: i32) {
3151 fn copy_custom_used_after() {
3155 //- minicore: copy, derive
3156 #[derive(Clone, Copy)]
3157 struct Counter(i32);
3165 #[derive(Clone, Copy)]
3166 struct Counter(i32);
3173 fn $0fun_name(c: Counter) {
3181 fn indented_stmts() {
3212 fn indented_stmts_inside_mod() {
3251 //- minicore: option
3266 let k = match fun_name(n) {
3267 Some(value) => value,
3274 fn $0fun_name(n: i32) -> Option<i32> {
3285 fn return_to_parent() {
3289 //- minicore: copy, result
3301 let k = match fun_name(n) {
3303 Err(value) => return value,
3308 fn $0fun_name(n: i32) -> Result<i32, i64> {
3319 fn break_and_continue() {
3320 cov_mark::check!(external_control_flow_break_and_continue);
3321 check_assist_not_applicable(
3340 fn return_and_break() {
3341 cov_mark::check!(external_control_flow_return_and_bc);
3342 check_assist_not_applicable(
3361 fn break_loop_with_if() {
3377 use core::ops::ControlFlow;
3382 if let ControlFlow::Break(_) = fun_name(&mut n) {
3389 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3391 return ControlFlow::Break(());
3393 ControlFlow::Continue(())
3400 fn break_loop_nested() {
3417 use core::ops::ControlFlow;
3422 if let ControlFlow::Break(_) = fun_name(n) {
3429 fn $0fun_name(n: i32) -> ControlFlow<()> {
3432 return ControlFlow::Break(());
3434 ControlFlow::Continue(())
3441 fn return_from_nested_loop() {
3461 let m = match fun_name() {
3462 Some(value) => value,
3469 fn $0fun_name() -> Option<i32> {
3482 fn break_from_nested_loop() {
3507 fn $0fun_name() -> i32 {
3520 fn break_from_nested_and_outer_loops() {
3543 let m = match fun_name() {
3544 Some(value) => value,
3551 fn $0fun_name() -> Option<i32> {
3567 fn return_from_nested_fn() {
3592 fn $0fun_name() -> i32 {
3605 fn break_with_value() {
3625 if let Some(value) = fun_name() {
3632 fn $0fun_name() -> Option<i32> {
3645 fn break_with_value_and_return() {
3665 let m = match fun_name() {
3667 Err(value) => break value,
3673 fn $0fun_name() -> Result<i32, i64> {
3690 //- minicore: option
3691 fn bar() -> Option<i32> { None }
3692 fn foo() -> Option<()> {
3701 fn bar() -> Option<i32> { None }
3702 fn foo() -> Option<()> {
3704 let m = fun_name()?;
3709 fn $0fun_name() -> Option<i32> {
3719 fn try_option_unit() {
3723 //- minicore: option
3724 fn foo() -> Option<()> {
3733 fn foo() -> Option<()> {
3740 fn $0fun_name() -> Option<()> {
3754 //- minicore: result
3755 fn foo() -> Result<(), i64> {
3764 fn foo() -> Result<(), i64> {
3766 let m = fun_name()?;
3771 fn $0fun_name() -> Result<i32, i64> {
3781 fn try_option_with_return() {
3785 //- minicore: option
3786 fn foo() -> Option<()> {
3798 fn foo() -> Option<()> {
3800 let m = fun_name()?;
3805 fn $0fun_name() -> Option<i32> {
3818 fn try_result_with_return() {
3822 //- minicore: result
3823 fn foo() -> Result<(), i64> {
3835 fn foo() -> Result<(), i64> {
3837 let m = fun_name()?;
3842 fn $0fun_name() -> Result<i32, i64> {
3855 fn try_and_break() {
3856 cov_mark::check!(external_control_flow_try_and_bc);
3857 check_assist_not_applicable(
3860 //- minicore: option
3861 fn foo() -> Option<()> {
3877 fn try_and_return_ok() {
3881 //- minicore: result
3882 fn foo() -> Result<(), i64> {
3894 fn foo() -> Result<(), i64> {
3896 let m = fun_name()?;
3901 fn $0fun_name() -> Result<i32, i64> {
3914 fn param_usage_in_macro() {
3919 ($val:expr) => { $val };
3924 $0let k = n * m!(n);$0
3930 ($val:expr) => { $val };
3935 let k = fun_name(n);
3939 fn $0fun_name(n: i32) -> i32 {
3948 fn extract_with_await() {
3953 $0some_function().await;$0
3956 async fn some_function() {
3965 async fn $0fun_name() {
3966 some_function().await;
3969 async fn some_function() {
3977 fn extract_with_await_and_result_not_producing_match_expr() {
3981 async fn foo() -> Result<(), ()> {
3987 async fn foo() -> Result<(), ()> {
3991 async fn $0fun_name() -> _ {
4000 fn extract_with_await_and_result_producing_match_expr() {
4004 async fn foo() -> i32 {
4007 let k = async { 1 }.await;
4017 async fn foo() -> i32 {
4020 let m = match fun_name().await {
4022 Err(value) => break value,
4028 async fn $0fun_name() -> Result<i32, i32> {
4029 let k = async { 1 }.await;
4041 fn extract_with_await_in_args() {
4046 $0function_call("a", some_function().await);$0
4049 async fn some_function() {
4058 async fn $0fun_name() {
4059 function_call("a", some_function().await);
4062 async fn some_function() {
4070 fn extract_does_not_extract_standalone_blocks() {
4071 check_assist_not_applicable(
4080 fn extract_adds_comma_for_match_arm() {
4099 fn $0fun_name() -> i32 {
4122 fn $0fun_name() -> i32 {
4130 fn extract_does_not_tear_comments_apart() {
4157 fn extract_does_not_wrap_res_in_res() {
4161 //- minicore: result
4162 fn foo() -> Result<(), i64> {
4163 $0Result::<i32, i64>::Ok(0)?;
4168 fn foo() -> Result<(), i64> {
4172 fn $0fun_name() -> Result<(), i64> {
4173 Result::<i32, i64>::Ok(0)?;
4181 fn extract_knows_const() {
4194 const fn $0fun_name() {
4211 const fn $0fun_name() {
4219 fn extract_does_not_move_outer_loop_vars() {
4238 fn $0fun_name(x: &mut i32) {
4261 fn $0fun_name(mut x: i32) {
4288 fn $0fun_name(x: &mut i32) {
4295 // regression test for #9822
4297 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4303 fn foo(&mut self) {}
4317 fn foo(&mut self) {}
4328 fn $0fun_name(y: &mut Foo) {
4336 fn extract_with_macro_arg() {
4341 ($val:expr) => { $val };
4350 ($val:expr) => { $val };
4357 fn $0fun_name(bar: &str) {
4365 fn unresolveable_types_default_to_placeholder() {
4370 let a = __unresolved;
4376 let a = __unresolved;
4377 let _ = fun_name(a);
4380 fn $0fun_name(a: _) -> _ {
4388 fn reference_mutable_param_with_further_usages() {
4396 pub fn testfn(arg: &mut Foo) {
4398 // Simulating access after the extracted portion
4407 pub fn testfn(arg: &mut Foo) {
4409 // Simulating access after the extracted portion
4413 fn $0fun_name(arg: &mut Foo) {
4421 fn reference_mutable_param_without_further_usages() {
4429 pub fn testfn(arg: &mut Foo) {
4438 pub fn testfn(arg: &mut Foo) {
4442 fn $0fun_name(arg: &mut Foo) {
4450 fn extract_function_copies_comment_at_start() {
4475 fn extract_function_copies_comment_in_between() {
4504 fn extract_function_copies_comment_at_end() {
4529 fn extract_function_copies_comment_indented() {
4558 fn extract_function_does_not_preserve_whitespace() {
4584 fn extract_function_long_form_comment() {