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, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
26 TokenAtOffset, WalkEvent, T,
30 assist_context::{AssistContext, Assists, TreeMutator},
34 // Assist: extract_function
36 // Extracts selected statements into new function.
54 // fn $0fun_name(n: i32) {
59 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
60 let range = ctx.selection_trimmed();
65 let node = match ctx.covering_element() {
66 syntax::NodeOrToken::Node(n) => n,
67 syntax::NodeOrToken::Token(t) => t.parent()?,
70 let body = extraction_target(&node, range)?;
71 let container_info = body.analyze_container(&ctx.sema)?;
73 let (locals_used, self_param) = body.analyze(&ctx.sema);
75 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
76 let insert_after = node_to_insert_after(&body, anchor)?;
77 let module = ctx.sema.scope(&insert_after).module()?;
79 let ret_ty = body.return_ty(ctx)?;
80 let control_flow = body.external_control_flow(ctx, &container_info)?;
81 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
83 let target_range = body.text_range();
85 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
88 AssistId("extract_function", crate::AssistKind::RefactorExtract),
89 "Extract into function",
92 let outliving_locals: Vec<_> = ret_values.collect();
93 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
94 // We should not have variables that outlive body if we have expression block
99 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
102 name: make::name_ref("fun_name"),
109 mods: container_info,
112 let new_indent = IndentLevel::from_node(&insert_after);
113 let old_indent = fun.body.indent_level();
115 builder.replace(target_range, make_call(ctx, &fun, old_indent));
117 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
118 let insert_offset = insert_after.text_range().end();
120 if fn_def.contains("ControlFlow") {
121 let scope = match scope {
122 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
123 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
124 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
127 let control_flow_enum =
128 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
130 if let Some(control_flow_enum) = control_flow_enum {
131 let mod_path = module.find_use_path_prefixed(
133 ModuleDef::from(control_flow_enum),
134 ctx.config.insert_use.prefix_kind,
137 if let Some(mod_path) = mod_path {
138 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
143 match ctx.config.snippet_cap {
144 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
145 None => builder.insert(insert_offset, fn_def),
151 /// Try to guess what user wants to extract
153 /// We have basically have two cases:
154 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
155 /// Then we can use `ast::Expr`
156 /// * We want a few statements for a block. E.g.
158 /// fn foo() -> i32 {
168 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
169 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
171 ast::Stmt::Item(_) => None,
172 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
173 node.parent().and_then(ast::StmtList::cast)?,
179 // Covering element returned the parent block of one or multiple statements that have been selected
180 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
181 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
182 if block_expr.syntax().text_range() == selection_range {
183 return FunctionBody::from_expr(block_expr.into());
187 // Extract the full statements.
188 return Some(FunctionBody::from_range(stmt_list, selection_range));
191 let expr = ast::Expr::cast(node.clone())?;
192 // A node got selected fully
193 if node.text_range() == selection_range {
194 return FunctionBody::from_expr(expr);
197 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
203 self_param: Option<ast::SelfParam>,
205 control_flow: ControlFlow,
208 outliving_locals: Vec<OutlivedLocal>,
221 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
229 #[derive(Debug, Eq, PartialEq)]
233 Tuple(Vec<hir::Type>),
236 /// Where to put extracted function definition
239 /// Extract free function and put right after current top-level function
241 /// Extract method and put right after current function in the impl-block
245 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
246 // probably be merged somehow.
249 kind: Option<FlowKind>,
254 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
255 #[derive(Clone, Debug)]
256 struct ContainerInfo {
259 parent_loop: Option<SyntaxNode>,
260 /// The function's return type, const's type etc.
261 ret_type: Option<hir::Type>,
264 /// Control flow that is exported from extracted function
276 #[derive(Debug, Clone)]
278 /// Return with value (`return $expr;`)
279 Return(Option<ast::Expr>),
283 /// Break with value (`break $expr;`)
284 Break(Option<ast::Expr>),
289 #[derive(Debug, Clone)]
292 Result { ty: hir::Type },
302 fn is_unit(&self) -> bool {
304 RetType::Expr(ty) => ty.is_unit(),
305 RetType::Stmt => true,
310 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
311 /// This is the future function body, the part that is being extracted.
315 Span { parent: ast::StmtList, text_range: TextRange },
319 struct OutlivedLocal {
321 mut_usage_outside_body: bool,
324 /// Container of local variable usages
326 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
327 struct LocalUsages(ide_db::search::UsageSearchResult);
330 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
332 Definition::Local(var)
334 .in_scope(SearchScope::single_file(ctx.file_id()))
339 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
340 self.0.iter().flat_map(|(_, rs)| rs)
345 fn return_type(&self, ctx: &AssistContext) -> FunType {
347 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
348 RetType::Expr(ty) => FunType::Single(ty.clone()),
349 RetType::Stmt => match self.outliving_locals.as_slice() {
351 [var] => FunType::Single(var.local.ty(ctx.db())),
353 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
354 FunType::Tuple(types)
362 fn is_ref(&self) -> bool {
363 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
368 fn kind(&self) -> ParamKind {
369 match (self.move_local, self.requires_mut, self.is_copy) {
370 (false, true, _) => ParamKind::MutRef,
371 (false, false, false) => ParamKind::SharedRef,
372 (true, true, _) => ParamKind::MutValue,
373 (_, false, _) => ParamKind::Value,
377 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
378 let var = path_expr_from_local(ctx, self.var);
380 ParamKind::Value | ParamKind::MutValue => var,
381 ParamKind::SharedRef => make::expr_ref(var, false),
382 ParamKind::MutRef => make::expr_ref(var, true),
386 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
387 let var = self.var.name(ctx.db()).unwrap().to_string();
388 let var_name = make::name(&var);
389 let pat = match self.kind() {
390 ParamKind::MutValue => make::ident_pat(false, true, var_name),
391 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
392 make::ext::simple_ident_pat(var_name)
396 let ty = make_ty(&self.ty, ctx, module);
397 let ty = match self.kind() {
398 ParamKind::Value | ParamKind::MutValue => ty,
399 ParamKind::SharedRef => make::ty_ref(ty, false),
400 ParamKind::MutRef => make::ty_ref(ty, true),
403 make::param(pat.into(), ty)
408 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
410 // We favour Result for `expr?`
411 return Some(TryKind::Result { ty });
413 let adt = ty.as_adt()?;
414 let name = adt.name(ctx.db());
415 // FIXME: use lang items to determine if it is std type or user defined
416 // E.g. if user happens to define type named `Option`, we would have false positive
417 match name.to_string().as_str() {
418 "Option" => Some(TryKind::Option),
419 "Result" => Some(TryKind::Result { ty }),
426 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
428 FlowKind::Return(_) => make::expr_return(expr),
429 FlowKind::Break(_) => make::expr_break(expr),
430 FlowKind::Try { .. } => {
431 stdx::never!("cannot have result handler with try");
432 expr.unwrap_or_else(|| make::expr_return(None))
434 FlowKind::Continue => {
435 stdx::always!(expr.is_none(), "continue with value is not possible");
436 make::expr_continue()
441 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
443 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
444 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
446 FlowKind::Try { .. } => {
447 stdx::never!("try does not have defined expr_ty");
456 fn parent(&self) -> Option<SyntaxNode> {
458 FunctionBody::Expr(expr) => expr.syntax().parent(),
459 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
463 fn from_expr(expr: ast::Expr) -> Option<Self> {
465 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
466 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
467 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
468 expr => Some(Self::Expr(expr)),
472 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
473 let full_body = parent.syntax().children_with_tokens();
475 let mut text_range = full_body
476 .map(|stmt| stmt.text_range())
477 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
478 .reduce(|acc, stmt| acc.cover(stmt));
480 if let Some(tail_range) = parent
482 .map(|it| it.syntax().text_range())
483 .filter(|&it| selected.intersect(it).is_some())
485 text_range = Some(match text_range {
486 Some(text_range) => text_range.cover(tail_range),
490 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
493 fn indent_level(&self) -> IndentLevel {
495 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
496 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
500 fn tail_expr(&self) -> Option<ast::Expr> {
502 FunctionBody::Expr(expr) => Some(expr.clone()),
503 FunctionBody::Span { parent, text_range } => {
504 let tail_expr = parent.tail_expr()?;
505 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
510 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
512 FunctionBody::Expr(expr) => walk_expr(expr, cb),
513 FunctionBody::Span { parent, text_range } => {
516 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
517 .filter_map(|stmt| match stmt {
518 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
519 ast::Stmt::Item(_) => None,
520 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
522 .for_each(|expr| walk_expr(&expr, cb));
523 if let Some(expr) = parent
525 .filter(|it| text_range.contains_range(it.syntax().text_range()))
527 walk_expr(&expr, cb);
533 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
535 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
536 FunctionBody::Span { parent, text_range } => {
539 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
540 .filter_map(|stmt| match stmt {
541 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
542 ast::Stmt::Item(_) => None,
543 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
545 .for_each(|expr| preorder_expr(&expr, cb));
546 if let Some(expr) = parent
548 .filter(|it| text_range.contains_range(it.syntax().text_range()))
550 preorder_expr(&expr, cb);
556 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
558 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
559 FunctionBody::Span { parent, text_range } => {
562 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
563 .for_each(|stmt| match stmt {
564 ast::Stmt::ExprStmt(expr_stmt) => {
565 if let Some(expr) = expr_stmt.expr() {
566 walk_patterns_in_expr(&expr, cb)
569 ast::Stmt::Item(_) => (),
570 ast::Stmt::LetStmt(stmt) => {
571 if let Some(pat) = stmt.pat() {
574 if let Some(expr) = stmt.initializer() {
575 walk_patterns_in_expr(&expr, cb);
579 if let Some(expr) = parent
581 .filter(|it| text_range.contains_range(it.syntax().text_range()))
583 walk_patterns_in_expr(&expr, cb);
589 fn text_range(&self) -> TextRange {
591 FunctionBody::Expr(expr) => expr.syntax().text_range(),
592 &FunctionBody::Span { text_range, .. } => text_range,
596 fn contains_range(&self, range: TextRange) -> bool {
597 self.text_range().contains_range(range)
600 fn precedes_range(&self, range: TextRange) -> bool {
601 self.text_range().end() <= range.start()
604 fn contains_node(&self, node: &SyntaxNode) -> bool {
605 self.contains_range(node.text_range())
610 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
611 /// whether it contains an await expression.
614 sema: &Semantics<RootDatabase>,
615 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
616 let mut self_param = None;
617 let mut res = FxIndexSet::default();
618 let mut cb = |name_ref: Option<_>| {
620 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
622 NameRefClass::Definition(Definition::Local(local_ref))
623 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
627 let InFile { file_id, value } = local_ref.source(sema.db);
628 // locals defined inside macros are not relevant to us
629 if !file_id.is_macro() {
631 Either::Right(it) => {
632 self_param.replace(it);
635 res.insert(local_ref);
640 self.walk_expr(&mut |expr| match expr {
641 ast::Expr::PathExpr(path_expr) => {
642 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
644 ast::Expr::MacroCall(call) => {
645 if let Some(tt) = call.token_tree() {
647 .children_with_tokens()
648 .flat_map(SyntaxElement::into_token)
649 .filter(|it| it.kind() == SyntaxKind::IDENT)
650 .flat_map(|t| sema.descend_into_macros(t))
651 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
659 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
660 let mut ancestors = self.parent()?.ancestors();
661 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
662 let mut parent_loop = None;
663 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
666 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
668 parent_loop.get_or_insert(loop_.syntax().clone());
671 let (is_const, expr, ty) = loop {
672 let anc = ancestors.next()?;
675 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
676 ast::BlockExpr(block_expr) => {
677 let (constness, block) = match block_expr.modifier() {
678 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
679 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
680 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
683 let expr = Some(ast::Expr::BlockExpr(block));
684 (constness, expr.clone(), infer_expr_opt(expr))
687 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
689 ast::Static(statik) => {
690 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
692 ast::ConstArg(ca) => {
693 (true, ca.expr(), infer_expr_opt(ca.expr()))
695 ast::Const(konst) => {
696 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
698 ast::ConstParam(cp) => {
699 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
701 ast::ConstBlockPat(cbp) => {
702 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
703 (true, expr.clone(), infer_expr_opt(expr))
705 ast::Variant(__) => return None,
706 ast::Meta(__) => return None,
707 ast::LoopExpr(it) => {
708 set_parent_loop(&it);
711 ast::ForExpr(it) => {
712 set_parent_loop(&it);
715 ast::WhileExpr(it) => {
716 set_parent_loop(&it);
723 let container_tail = match expr? {
724 ast::Expr::BlockExpr(block) => block.tail_expr(),
728 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
729 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
731 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
734 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
735 match self.tail_expr() {
736 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
737 None => Some(RetType::Stmt),
741 /// Local variables defined inside `body` that are accessed outside of it
744 ctx: &'a AssistContext,
746 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
747 let parent = parent.clone();
748 let range = self.text_range();
749 locals_defined_in_body(&ctx.sema, self)
751 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
754 /// Analyses the function body for external control flow.
755 fn external_control_flow(
758 container_info: &ContainerInfo,
759 ) -> Option<ControlFlow> {
760 let mut ret_expr = None;
761 let mut try_expr = None;
762 let mut break_expr = None;
763 let mut continue_expr = None;
764 let mut is_async = false;
765 let mut _is_unsafe = false;
767 let mut unsafe_depth = 0;
768 let mut loop_depth = 0;
770 self.preorder_expr(&mut |expr| {
771 let expr = match expr {
772 WalkEvent::Enter(e) => e,
773 WalkEvent::Leave(expr) => {
775 ast::Expr::LoopExpr(_)
776 | ast::Expr::ForExpr(_)
777 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
778 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
787 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
790 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
793 ast::Expr::ReturnExpr(it) => {
796 ast::Expr::TryExpr(it) => {
799 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
800 break_expr = Some(it);
802 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
803 continue_expr = Some(it);
805 ast::Expr::AwaitExpr(_) => is_async = true,
806 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
807 // to just lift that out of there
808 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
814 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
815 (Some(_), _, None, None) => {
816 let ret_ty = container_info.ret_type.clone()?;
817 let kind = TryKind::of_ty(ret_ty, ctx)?;
819 Some(FlowKind::Try { kind })
821 (Some(_), _, _, _) => {
822 cov_mark::hit!(external_control_flow_try_and_bc);
825 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
826 (None, Some(_), _, _) => {
827 cov_mark::hit!(external_control_flow_return_and_bc);
830 (None, None, Some(_), Some(_)) => {
831 cov_mark::hit!(external_control_flow_break_and_continue);
834 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
835 (None, None, None, Some(_)) => Some(FlowKind::Continue),
836 (None, None, None, None) => None,
839 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
842 /// find variables that should be extracted as params
844 /// Computes additional info that affects param type and mutability
845 fn extracted_function_params(
848 container_info: &ContainerInfo,
849 locals: impl Iterator<Item = Local>,
852 .map(|local| (local, local.source(ctx.db())))
853 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
854 .filter_map(|(local, src)| match src.value {
855 Either::Left(src) => Some((local, src)),
856 Either::Right(_) => {
857 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
862 let usages = LocalUsages::find_local_usages(ctx, var);
863 let ty = var.ty(ctx.db());
865 let defined_outside_parent_loop = container_info
868 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
870 let is_copy = ty.is_copy(ctx.db());
871 let has_usages = self.has_usages_after_body(&usages);
873 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
874 // We can move the value into the function call if it's not used after the call,
875 // if the var is not used but defined outside a loop we are extracting from we can't move it either
876 // as the function will reuse it in the next iteration.
877 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
878 Param { var, ty, move_local, requires_mut, is_copy }
883 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
884 usages.iter().any(|reference| self.precedes_range(reference.range))
888 /// checks if relevant var is used with `&mut` access inside body
889 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
892 .filter(|reference| body.contains_range(reference.range))
893 .any(|reference| reference_is_exclusive(reference, body, ctx))
896 /// checks if this reference requires `&mut` access inside node
897 fn reference_is_exclusive(
898 reference: &FileReference,
899 node: &dyn HasTokenAtOffset,
902 // we directly modify variable with set: `n = 0`, `n += 1`
903 if reference.category == Some(ReferenceCategory::Write) {
907 // we take `&mut` reference to variable: `&mut v`
908 let path = match path_element_of_reference(node, reference) {
910 None => return false,
913 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
916 /// checks if this expr requires `&mut` access, recurses on field access
917 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
918 if let ast::Expr::MacroCall(_) = expr {
919 // FIXME: expand macro and check output for mutable usages of the variable?
923 let parent = expr.syntax().parent()?;
925 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
926 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
927 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
932 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
933 return Some(ref_expr.mut_token().is_some());
936 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
937 let func = ctx.sema.resolve_method_call(&method_call)?;
938 let self_param = func.self_param(ctx.db())?;
939 let access = self_param.access(ctx.db());
941 return Some(matches!(access, hir::Access::Exclusive));
944 if let Some(field) = ast::FieldExpr::cast(parent) {
945 return expr_require_exclusive_access(ctx, &field.into());
951 trait HasTokenAtOffset {
952 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
955 impl HasTokenAtOffset for SyntaxNode {
956 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
957 SyntaxNode::token_at_offset(self, offset)
961 impl HasTokenAtOffset for FunctionBody {
962 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
964 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
965 FunctionBody::Span { parent, text_range } => {
966 match parent.syntax().token_at_offset(offset) {
967 TokenAtOffset::None => TokenAtOffset::None,
968 TokenAtOffset::Single(t) => {
969 if text_range.contains_range(t.text_range()) {
970 TokenAtOffset::Single(t)
975 TokenAtOffset::Between(a, b) => {
977 text_range.contains_range(a.text_range()),
978 text_range.contains_range(b.text_range()),
980 (true, true) => TokenAtOffset::Between(a, b),
981 (true, false) => TokenAtOffset::Single(a),
982 (false, true) => TokenAtOffset::Single(b),
983 (false, false) => TokenAtOffset::None,
992 /// find relevant `ast::Expr` for reference
996 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
997 fn path_element_of_reference(
998 node: &dyn HasTokenAtOffset,
999 reference: &FileReference,
1000 ) -> Option<ast::Expr> {
1001 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1002 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1005 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1006 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1010 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1011 "unexpected expression type for variable usage: {:?}",
1017 /// list local variables defined inside `body`
1018 fn locals_defined_in_body(
1019 sema: &Semantics<RootDatabase>,
1020 body: &FunctionBody,
1021 ) -> FxIndexSet<Local> {
1022 // FIXME: this doesn't work well with macros
1023 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1024 let mut res = FxIndexSet::default();
1025 body.walk_pat(&mut |pat| {
1026 if let ast::Pat::IdentPat(pat) = pat {
1027 if let Some(local) = sema.to_def(&pat) {
1035 /// Returns usage details if local variable is used after(outside of) body
1036 fn local_outlives_body(
1037 ctx: &AssistContext,
1038 body_range: TextRange,
1040 parent: &SyntaxNode,
1041 ) -> Option<OutlivedLocal> {
1042 let usages = LocalUsages::find_local_usages(ctx, local);
1043 let mut has_mut_usages = false;
1044 let mut any_outlives = false;
1045 for usage in usages.iter() {
1046 if body_range.end() <= usage.range.start() {
1047 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1048 any_outlives |= true;
1050 break; // no need to check more elements we have all the info we wanted
1057 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1060 /// checks if the relevant local was defined before(outside of) body
1061 fn is_defined_outside_of_body(
1062 ctx: &AssistContext,
1063 body: &FunctionBody,
1064 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1066 src.file_id.original_file(ctx.db()) == ctx.file_id()
1067 && !body.contains_node(either_syntax(&src.value))
1070 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1072 Either::Left(pat) => pat.syntax(),
1073 Either::Right(it) => it.syntax(),
1077 /// find where to put extracted function definition
1079 /// Function should be put right after returned node
1080 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1081 let node = match body {
1082 FunctionBody::Expr(e) => e.syntax(),
1083 FunctionBody::Span { parent, .. } => parent.syntax(),
1085 let mut ancestors = node.ancestors().peekable();
1086 let mut last_ancestor = None;
1087 while let Some(next_ancestor) = ancestors.next() {
1088 match next_ancestor.kind() {
1089 SyntaxKind::SOURCE_FILE => break,
1090 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1091 SyntaxKind::ITEM_LIST => {
1092 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1096 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1099 SyntaxKind::ASSOC_ITEM_LIST => {
1100 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1106 last_ancestor = Some(next_ancestor);
1111 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1112 let ret_ty = fun.return_type(ctx);
1114 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1115 let name = fun.name.clone();
1116 let mut call_expr = if fun.self_param.is_some() {
1117 let self_arg = make::expr_path(make::ext::ident_path("self"));
1118 make::expr_method_call(self_arg, name, args)
1120 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1121 make::expr_call(func, args)
1124 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1126 if fun.control_flow.is_async {
1127 call_expr = make::expr_await(call_expr);
1129 let expr = handler.make_call_expr(call_expr).indent(indent);
1131 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1133 let mut buf = String::new();
1134 match fun.outliving_locals.as_slice() {
1137 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1140 buf.push_str("let (");
1141 let bindings = vars.iter().format_with(", ", |local, f| {
1142 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1144 format_to!(buf, "{}", bindings);
1145 buf.push_str(") = ");
1149 format_to!(buf, "{}", expr);
1150 let insert_comma = fun
1153 .and_then(ast::MatchArm::cast)
1154 .map_or(false, |it| it.comma_token().is_none());
1157 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1165 Try { kind: TryKind },
1166 If { action: FlowKind },
1167 IfOption { action: FlowKind },
1168 MatchOption { none: FlowKind },
1169 MatchResult { err: FlowKind },
1173 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1174 match &fun.control_flow.kind {
1175 None => FlowHandler::None,
1176 Some(flow_kind) => {
1177 let action = flow_kind.clone();
1178 if *ret_ty == FunType::Unit {
1180 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1181 FlowHandler::If { action }
1183 FlowKind::Return(_) | FlowKind::Break(_) => {
1184 FlowHandler::IfOption { action }
1186 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1190 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1191 FlowHandler::MatchOption { none: action }
1193 FlowKind::Return(_) | FlowKind::Break(_) => {
1194 FlowHandler::MatchResult { err: action }
1196 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1203 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1205 FlowHandler::None => call_expr,
1206 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1207 FlowHandler::If { action } => {
1208 let action = action.make_result_handler(None);
1209 let stmt = make::expr_stmt(action);
1210 let block = make::block_expr(iter::once(stmt.into()), None);
1211 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1212 let condition = make::condition(
1215 make::tuple_struct_pat(
1216 controlflow_break_path,
1217 iter::once(make::wildcard_pat().into()),
1222 make::expr_if(condition, block, None)
1224 FlowHandler::IfOption { action } => {
1225 let path = make::ext::ident_path("Some");
1226 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1227 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1228 let cond = make::condition(call_expr, Some(pattern.into()));
1229 let value = make::expr_path(make::ext::ident_path("value"));
1230 let action_expr = action.make_result_handler(Some(value));
1231 let action_stmt = make::expr_stmt(action_expr);
1232 let then = make::block_expr(iter::once(action_stmt.into()), None);
1233 make::expr_if(cond, then, None)
1235 FlowHandler::MatchOption { none } => {
1236 let some_name = "value";
1239 let path = make::ext::ident_path("Some");
1240 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1241 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1242 let value = make::expr_path(make::ext::ident_path(some_name));
1243 make::match_arm(iter::once(pat.into()), None, value)
1246 let path = make::ext::ident_path("None");
1247 let pat = make::path_pat(path);
1248 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1250 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1251 make::expr_match(call_expr, arms)
1253 FlowHandler::MatchResult { err } => {
1254 let ok_name = "value";
1255 let err_name = "value";
1258 let path = make::ext::ident_path("Ok");
1259 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1260 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1261 let value = make::expr_path(make::ext::ident_path(ok_name));
1262 make::match_arm(iter::once(pat.into()), None, value)
1265 let path = make::ext::ident_path("Err");
1266 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1267 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1268 let value = make::expr_path(make::ext::ident_path(err_name));
1270 iter::once(pat.into()),
1272 err.make_result_handler(Some(value)),
1275 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1276 make::expr_match(call_expr, arms)
1282 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1283 let name = var.name(ctx.db()).unwrap().to_string();
1284 make::expr_path(make::ext::ident_path(&name))
1288 ctx: &AssistContext,
1289 module: hir::Module,
1291 old_indent: IndentLevel,
1292 new_indent: IndentLevel,
1294 let mut fn_def = String::new();
1295 let params = fun.make_param_list(ctx, module);
1296 let ret_ty = fun.make_ret_ty(ctx, module);
1297 let body = make_body(ctx, old_indent, new_indent, fun);
1298 let const_kw = if fun.mods.is_const { "const " } else { "" };
1299 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1300 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1301 match ctx.config.snippet_cap {
1302 Some(_) => format_to!(
1304 "\n\n{}{}{}{}fn $0{}{}",
1314 "\n\n{}{}{}{}fn {}{}",
1323 if let Some(ret_ty) = ret_ty {
1324 format_to!(fn_def, " {}", ret_ty);
1326 format_to!(fn_def, " {}", body);
1332 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1333 let self_param = self.self_param.clone();
1334 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1335 make::param_list(self_param, params)
1338 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1339 let fun_ty = self.return_type(ctx);
1340 let handler = if self.mods.is_in_tail {
1343 FlowHandler::from_ret_ty(self, &fun_ty)
1345 let ret_ty = match &handler {
1346 FlowHandler::None => {
1347 if matches!(fun_ty, FunType::Unit) {
1350 fun_ty.make_ty(ctx, module)
1352 FlowHandler::Try { kind: TryKind::Option } => {
1353 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1355 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1356 let handler_ty = parent_ret_ty
1359 .map(|ty| make_ty(&ty, ctx, module))
1360 .unwrap_or_else(make::ty_placeholder);
1361 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1363 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1364 FlowHandler::IfOption { action } => {
1365 let handler_ty = action
1367 .map(|ty| make_ty(&ty, ctx, module))
1368 .unwrap_or_else(make::ty_placeholder);
1369 make::ext::ty_option(handler_ty)
1371 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1372 FlowHandler::MatchResult { err } => {
1373 let handler_ty = err
1375 .map(|ty| make_ty(&ty, ctx, module))
1376 .unwrap_or_else(make::ty_placeholder);
1377 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1380 Some(make::ret_type(ret_ty))
1385 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1387 FunType::Unit => make::ty_unit(),
1388 FunType::Single(ty) => make_ty(ty, ctx, module),
1389 FunType::Tuple(types) => match types.as_slice() {
1391 stdx::never!("tuple type with 0 elements");
1395 stdx::never!("tuple type with 1 element");
1396 make_ty(ty, ctx, module)
1399 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1400 make::ty_tuple(types)
1408 ctx: &AssistContext,
1409 old_indent: IndentLevel,
1410 new_indent: IndentLevel,
1412 ) -> ast::BlockExpr {
1413 let ret_ty = fun.return_type(ctx);
1414 let handler = if fun.mods.is_in_tail {
1417 FlowHandler::from_ret_ty(fun, &ret_ty)
1420 let block = match &fun.body {
1421 FunctionBody::Expr(expr) => {
1422 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1423 let expr = ast::Expr::cast(expr).unwrap();
1425 ast::Expr::BlockExpr(block) => {
1426 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1427 let block = block.dedent(old_indent);
1428 // Recreate the block for formatting consistency with other extracted functions.
1429 make::block_expr(block.statements(), block.tail_expr())
1432 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1434 make::block_expr(Vec::new(), Some(expr))
1438 FunctionBody::Span { parent, text_range } => {
1439 let mut elements: Vec<_> = parent
1441 .children_with_tokens()
1442 .filter(|it| text_range.contains_range(it.text_range()))
1443 .map(|it| match &it {
1444 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1445 rewrite_body_segment(ctx, &fun.params, &handler, &n),
1451 let mut tail_expr = match &elements.last() {
1452 Some(element) => match element {
1453 syntax::NodeOrToken::Node(node) if ast::Expr::can_cast(node.kind()) => {
1454 ast::Expr::cast(node.clone())
1465 None => match fun.outliving_locals.as_slice() {
1468 tail_expr = Some(path_expr_from_local(ctx, var.local));
1471 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1472 let expr = make::expr_tuple(exprs);
1473 tail_expr = Some(expr);
1478 let body_indent = IndentLevel(1);
1479 let elements = elements
1481 .map(|node_or_token| match &node_or_token {
1482 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1484 let indented = stmt.dedent(old_indent).indent(body_indent);
1485 let ast_node = indented.syntax().clone_subtree();
1486 syntax::NodeOrToken::Node(ast_node)
1492 .collect::<Vec<SyntaxElement>>();
1493 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1495 make::hacky_block_expr_with_comments(elements, tail_expr)
1499 let block = match &handler {
1500 FlowHandler::None => block,
1501 FlowHandler::Try { kind } => {
1502 let block = with_default_tail_expr(block, make::expr_unit());
1503 map_tail_expr(block, |tail_expr| {
1504 let constructor = match kind {
1505 TryKind::Option => "Some",
1506 TryKind::Result { .. } => "Ok",
1508 let func = make::expr_path(make::ext::ident_path(constructor));
1509 let args = make::arg_list(iter::once(tail_expr));
1510 make::expr_call(func, args)
1513 FlowHandler::If { .. } => {
1514 let controlflow_continue = make::expr_call(
1515 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1516 make::arg_list(iter::once(make::expr_unit())),
1518 with_tail_expr(block, controlflow_continue.into())
1520 FlowHandler::IfOption { .. } => {
1521 let none = make::expr_path(make::ext::ident_path("None"));
1522 with_tail_expr(block, none)
1524 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1525 let some = make::expr_path(make::ext::ident_path("Some"));
1526 let args = make::arg_list(iter::once(tail_expr));
1527 make::expr_call(some, args)
1529 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1530 let ok = make::expr_path(make::ext::ident_path("Ok"));
1531 let args = make::arg_list(iter::once(tail_expr));
1532 make::expr_call(ok, args)
1536 block.indent(new_indent)
1539 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1540 let tail_expr = match block.tail_expr() {
1541 Some(tail_expr) => tail_expr,
1542 None => return block,
1544 make::block_expr(block.statements(), Some(f(tail_expr)))
1547 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1548 match block.tail_expr() {
1550 None => make::block_expr(block.statements(), Some(tail_expr)),
1554 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1555 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1556 let stmts = block.statements().chain(stmt_tail);
1557 make::block_expr(stmts, Some(tail_expr))
1560 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1561 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1564 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1565 let ty_str = format_type(ty, ctx, module);
1569 fn rewrite_body_segment(
1570 ctx: &AssistContext,
1572 handler: &FlowHandler,
1573 syntax: &SyntaxNode,
1575 let syntax = fix_param_usages(ctx, params, syntax);
1576 update_external_control_flow(handler, &syntax);
1580 /// change all usages to account for added `&`/`&mut` for some params
1581 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1582 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1584 let tm = TreeMutator::new(syntax);
1586 for param in params {
1587 if !param.kind().is_ref() {
1591 let usages = LocalUsages::find_local_usages(ctx, param.var);
1594 .filter(|reference| syntax.text_range().contains_range(reference.range))
1595 .filter_map(|reference| path_element_of_reference(syntax, reference))
1596 .map(|expr| tm.make_mut(&expr));
1598 usages_for_param.push((param, usages.collect()));
1601 let res = tm.make_syntax_mut(syntax);
1603 for (param, usages) in usages_for_param {
1604 for usage in usages {
1605 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1606 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1609 Some(ast::Expr::RefExpr(node))
1610 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1612 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1614 Some(ast::Expr::RefExpr(node))
1615 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1617 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1620 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1621 ted::replace(usage.syntax(), p.syntax())
1630 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1631 let mut nested_loop = None;
1632 let mut nested_scope = None;
1633 for event in syntax.preorder() {
1635 WalkEvent::Enter(e) => match e.kind() {
1636 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1637 if nested_loop.is_none() {
1638 nested_loop = Some(e.clone());
1643 | SyntaxKind::STATIC
1645 | SyntaxKind::MODULE => {
1646 if nested_scope.is_none() {
1647 nested_scope = Some(e.clone());
1652 WalkEvent::Leave(e) => {
1653 if nested_scope.is_none() {
1654 if let Some(expr) = ast::Expr::cast(e.clone()) {
1656 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1657 let expr = return_expr.expr();
1658 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1659 ted::replace(return_expr.syntax(), replacement.syntax())
1662 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1663 let expr = break_expr.expr();
1664 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1665 ted::replace(break_expr.syntax(), replacement.syntax())
1668 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1669 if let Some(replacement) = make_rewritten_flow(handler, None) {
1670 ted::replace(continue_expr.syntax(), replacement.syntax())
1680 if nested_loop.as_ref() == Some(&e) {
1683 if nested_scope.as_ref() == Some(&e) {
1684 nested_scope = None;
1691 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1692 let value = match handler {
1693 FlowHandler::None | FlowHandler::Try { .. } => return None,
1694 FlowHandler::If { .. } => make::expr_call(
1695 make::expr_path(make::path_from_text("ControlFlow::Break")),
1696 make::arg_list(iter::once(make::expr_unit())),
1698 FlowHandler::IfOption { .. } => {
1699 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1700 let args = make::arg_list(iter::once(expr));
1701 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1703 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1704 FlowHandler::MatchResult { .. } => {
1705 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1706 let args = make::arg_list(iter::once(expr));
1707 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1710 Some(make::expr_return(Some(value)).clone_for_update())
1715 use crate::tests::{check_assist, check_assist_not_applicable};
1720 fn no_args_from_binary_expr() {
1733 fn $0fun_name() -> i32 {
1741 fn no_args_from_binary_expr_in_module() {
1757 fn $0fun_name() -> i32 {
1766 fn no_args_from_binary_expr_indented() {
1779 fn $0fun_name() -> i32 {
1787 fn no_args_from_stmt_with_last_expr() {
1803 fn $0fun_name() -> i32 {
1812 fn no_args_from_stmt_unit() {
1860 fn no_args_if_else() {
1865 $0if true { 1 } else { 2 }$0
1873 fn $0fun_name() -> i32 {
1874 if true { 1 } else { 2 }
1881 fn no_args_if_let_else() {
1886 $0if let true = false { 1 } else { 2 }$0
1894 fn $0fun_name() -> i32 {
1895 if let true = false { 1 } else { 2 }
1902 fn no_args_match() {
1918 fn $0fun_name() -> i32 {
1929 fn no_args_while() {
1955 $0for v in &[0, 1] { }$0
1964 for v in &[0, 1] { }
1971 fn no_args_from_loop_unit() {
1986 fn $0fun_name() -> ! {
1996 fn no_args_from_loop_with_return() {
2012 fn $0fun_name() -> i32 {
2023 fn no_args_from_match() {
2028 let v: i32 = $0match Some(1) {
2036 let v: i32 = fun_name();
2039 fn $0fun_name() -> i32 {
2050 fn extract_partial_block_single_line() {
2056 let mut v = $0n * n;$0
2063 let mut v = fun_name(n);
2067 fn $0fun_name(n: i32) -> i32 {
2076 fn extract_partial_block() {
2083 let mut v = m $0* n;
2093 let (mut v, mut w) = fun_name(m, n);
2098 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2108 fn argument_form_expr() {
2123 fn $0fun_name(n: u32) -> u32 {
2131 fn argument_used_twice_form_expr() {
2146 fn $0fun_name(n: u32) -> u32 {
2154 fn two_arguments_form_expr() {
2171 fn $0fun_name(n: u32, m: u32) -> u32 {
2179 fn argument_and_locals() {
2195 fn $0fun_name(n: u32) -> u32 {
2204 fn part_of_expr_stmt() {
2217 fn $0fun_name() -> i32 {
2225 fn function_expr() {
2246 fn extract_from_nested() {
2252 let tuple = match x {
2253 true => ($02 + 2$0, true)
2261 let tuple = match x {
2262 true => (fun_name(), true)
2267 fn $0fun_name() -> i32 {
2275 fn param_from_closure() {
2280 let lambda = |x: u32| $0x * 2$0;
2285 let lambda = |x: u32| fun_name(x);
2288 fn $0fun_name(x: u32) -> u32 {
2296 fn extract_return_stmt() {
2309 fn $0fun_name() -> u32 {
2317 fn does_not_add_extra_whitespace() {
2334 fn $0fun_name() -> u32 {
2359 fn $0fun_name() -> i32 {
2372 let v = $00f32 as u32$0;
2380 fn $0fun_name() -> u32 {
2388 fn return_not_applicable() {
2389 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2393 fn method_to_freestanding() {
2400 fn foo(&self) -> i32 {
2409 fn foo(&self) -> i32 {
2414 fn $0fun_name() -> i32 {
2422 fn method_with_reference() {
2426 struct S { f: i32 };
2429 fn foo(&self) -> i32 {
2435 struct S { f: i32 };
2438 fn foo(&self) -> i32 {
2442 fn $0fun_name(&self) -> i32 {
2451 fn method_with_mut() {
2455 struct S { f: i32 };
2464 struct S { f: i32 };
2471 fn $0fun_name(&mut self) {
2480 fn variable_defined_inside_and_used_after_no_ret() {
2493 let k = fun_name(n);
2497 fn $0fun_name(n: i32) -> i32 {
2506 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2512 $0let mut k = n * n;$0
2519 let mut k = fun_name(n);
2523 fn $0fun_name(n: i32) -> i32 {
2532 fn two_variables_defined_inside_and_used_after_no_ret() {
2546 let (k, m) = fun_name(n);
2550 fn $0fun_name(n: i32) -> (i32, i32) {
2560 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2566 $0let mut k = n * n;
2577 let (mut k, mut m, o) = fun_name(n);
2582 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2594 fn nontrivial_patterns_define_variables() {
2598 struct Counter(i32);
2600 $0let Counter(n) = Counter(0);$0
2605 struct Counter(i32);
2611 fn $0fun_name() -> i32 {
2612 let Counter(n) = Counter(0);
2620 fn struct_with_two_fields_pattern_define_variables() {
2624 struct Counter { n: i32, m: i32 };
2626 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2631 struct Counter { n: i32, m: i32 };
2633 let (n, k) = fun_name();
2637 fn $0fun_name() -> (i32, i32) {
2638 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2646 fn mut_var_from_outer_scope() {
2663 fn $0fun_name(n: &mut i32) {
2671 fn mut_field_from_outer_scope() {
2677 let mut c = C { n: 0 };
2685 let mut c = C { n: 0 };
2690 fn $0fun_name(c: &mut C) {
2698 fn mut_nested_field_from_outer_scope() {
2705 let mut c = C { p: P { n: 0 } };
2706 let mut v = C { p: P { n: 0 } };
2707 let u = C { p: P { n: 0 } };
2709 let r = &mut v.p.n;$0
2710 let m = c.p.n + v.p.n + u.p.n;
2717 let mut c = C { p: P { n: 0 } };
2718 let mut v = C { p: P { n: 0 } };
2719 let u = C { p: P { n: 0 } };
2720 fun_name(&mut c, &u, &mut v);
2721 let m = c.p.n + v.p.n + u.p.n;
2724 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2733 fn mut_param_many_usages_stmt() {
2739 fn succ(&self) -> Self;
2740 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2743 fn succ(&self) -> Self { *self + 1 }
2762 fn succ(&self) -> Self;
2763 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2766 fn succ(&self) -> Self { *self + 1 }
2774 fn $0fun_name(n: &mut i32) {
2790 fn mut_param_many_usages_expr() {
2796 fn succ(&self) -> Self;
2797 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2800 fn succ(&self) -> Self { *self + 1 }
2821 fn succ(&self) -> Self;
2822 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2825 fn succ(&self) -> Self { *self + 1 }
2833 fn $0fun_name(n: &mut i32) {
2849 fn mut_param_by_value() {
2864 fn $0fun_name(mut n: i32) {
2872 fn mut_param_because_of_mut_ref() {
2890 fn $0fun_name(n: &mut i32) {
2899 fn mut_param_by_value_because_of_mut_ref() {
2915 fn $0fun_name(mut n: i32) {
2924 fn mut_method_call() {
2932 fn inc(&mut self) { *self += 1 }
2944 fn inc(&mut self) { *self += 1 }
2951 fn $0fun_name(mut n: i32) {
2959 fn shared_method_call() {
2967 fn succ(&self) { *self + 1 }
2979 fn succ(&self) { *self + 1 }
2986 fn $0fun_name(n: i32) {
2994 fn mut_method_call_with_other_receiver() {
2999 fn inc(&mut self, n: i32);
3002 fn inc(&mut self, n: i32) { *self += n }
3012 fn inc(&mut self, n: i32);
3015 fn inc(&mut self, n: i32) { *self += n }
3022 fn $0fun_name(n: i32) {
3031 fn non_copy_without_usages_after() {
3035 struct Counter(i32);
3042 struct Counter(i32);
3048 fn $0fun_name(c: Counter) {
3056 fn non_copy_used_after() {
3060 struct Counter(i32);
3068 struct Counter(i32);
3075 fn $0fun_name(c: &Counter) {
3083 fn copy_used_after() {
3101 fn $0fun_name(n: i32) {
3109 fn copy_custom_used_after() {
3113 //- minicore: copy, derive
3114 #[derive(Clone, Copy)]
3115 struct Counter(i32);
3123 #[derive(Clone, Copy)]
3124 struct Counter(i32);
3131 fn $0fun_name(c: Counter) {
3139 fn indented_stmts() {
3170 fn indented_stmts_inside_mod() {
3209 //- minicore: option
3224 let k = match fun_name(n) {
3225 Some(value) => value,
3232 fn $0fun_name(n: i32) -> Option<i32> {
3243 fn return_to_parent() {
3247 //- minicore: copy, result
3259 let k = match fun_name(n) {
3261 Err(value) => return value,
3266 fn $0fun_name(n: i32) -> Result<i32, i64> {
3277 fn break_and_continue() {
3278 cov_mark::check!(external_control_flow_break_and_continue);
3279 check_assist_not_applicable(
3298 fn return_and_break() {
3299 cov_mark::check!(external_control_flow_return_and_bc);
3300 check_assist_not_applicable(
3319 fn break_loop_with_if() {
3335 use core::ops::ControlFlow;
3340 if let ControlFlow::Break(_) = fun_name(&mut n) {
3347 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3349 return ControlFlow::Break(());
3351 ControlFlow::Continue(())
3358 fn break_loop_nested() {
3375 use core::ops::ControlFlow;
3380 if let ControlFlow::Break(_) = fun_name(n) {
3387 fn $0fun_name(n: i32) -> ControlFlow<()> {
3390 return ControlFlow::Break(());
3392 ControlFlow::Continue(())
3399 fn return_from_nested_loop() {
3419 let m = match fun_name() {
3420 Some(value) => value,
3427 fn $0fun_name() -> Option<i32> {
3440 fn break_from_nested_loop() {
3465 fn $0fun_name() -> i32 {
3478 fn break_from_nested_and_outer_loops() {
3501 let m = match fun_name() {
3502 Some(value) => value,
3509 fn $0fun_name() -> Option<i32> {
3525 fn return_from_nested_fn() {
3550 fn $0fun_name() -> i32 {
3563 fn break_with_value() {
3583 if let Some(value) = fun_name() {
3590 fn $0fun_name() -> Option<i32> {
3603 fn break_with_value_and_return() {
3623 let m = match fun_name() {
3625 Err(value) => break value,
3631 fn $0fun_name() -> Result<i32, i64> {
3648 //- minicore: option
3649 fn bar() -> Option<i32> { None }
3650 fn foo() -> Option<()> {
3659 fn bar() -> Option<i32> { None }
3660 fn foo() -> Option<()> {
3662 let m = fun_name()?;
3667 fn $0fun_name() -> Option<i32> {
3677 fn try_option_unit() {
3681 //- minicore: option
3682 fn foo() -> Option<()> {
3691 fn foo() -> Option<()> {
3698 fn $0fun_name() -> Option<()> {
3712 //- minicore: result
3713 fn foo() -> Result<(), i64> {
3722 fn foo() -> Result<(), i64> {
3724 let m = fun_name()?;
3729 fn $0fun_name() -> Result<i32, i64> {
3739 fn try_option_with_return() {
3743 //- minicore: option
3744 fn foo() -> Option<()> {
3756 fn foo() -> Option<()> {
3758 let m = fun_name()?;
3763 fn $0fun_name() -> Option<i32> {
3776 fn try_result_with_return() {
3780 //- minicore: result
3781 fn foo() -> Result<(), i64> {
3793 fn foo() -> Result<(), i64> {
3795 let m = fun_name()?;
3800 fn $0fun_name() -> Result<i32, i64> {
3813 fn try_and_break() {
3814 cov_mark::check!(external_control_flow_try_and_bc);
3815 check_assist_not_applicable(
3818 //- minicore: option
3819 fn foo() -> Option<()> {
3835 fn try_and_return_ok() {
3839 //- minicore: result
3840 fn foo() -> Result<(), i64> {
3852 fn foo() -> Result<(), i64> {
3854 let m = fun_name()?;
3859 fn $0fun_name() -> Result<i32, i64> {
3872 fn param_usage_in_macro() {
3877 ($val:expr) => { $val };
3882 $0let k = n * m!(n);$0
3888 ($val:expr) => { $val };
3893 let k = fun_name(n);
3897 fn $0fun_name(n: i32) -> i32 {
3906 fn extract_with_await() {
3911 $0some_function().await;$0
3914 async fn some_function() {
3923 async fn $0fun_name() {
3924 some_function().await;
3927 async fn some_function() {
3935 fn extract_with_await_and_result_not_producing_match_expr() {
3939 async fn foo() -> Result<(), ()> {
3945 async fn foo() -> Result<(), ()> {
3949 async fn $0fun_name() -> _ {
3958 fn extract_with_await_and_result_producing_match_expr() {
3962 async fn foo() -> i32 {
3965 let k = async { 1 }.await;
3975 async fn foo() -> i32 {
3978 let m = match fun_name().await {
3980 Err(value) => break value,
3986 async fn $0fun_name() -> Result<i32, i32> {
3987 let k = async { 1 }.await;
3999 fn extract_with_await_in_args() {
4004 $0function_call("a", some_function().await);$0
4007 async fn some_function() {
4016 async fn $0fun_name() {
4017 function_call("a", some_function().await);
4020 async fn some_function() {
4028 fn extract_does_not_extract_standalone_blocks() {
4029 check_assist_not_applicable(
4038 fn extract_adds_comma_for_match_arm() {
4057 fn $0fun_name() -> i32 {
4080 fn $0fun_name() -> i32 {
4088 fn extract_does_not_tear_comments_apart() {
4115 fn extract_does_not_wrap_res_in_res() {
4119 //- minicore: result
4120 fn foo() -> Result<(), i64> {
4121 $0Result::<i32, i64>::Ok(0)?;
4126 fn foo() -> Result<(), i64> {
4130 fn $0fun_name() -> Result<(), i64> {
4131 Result::<i32, i64>::Ok(0)?;
4139 fn extract_knows_const() {
4152 const fn $0fun_name() {
4169 const fn $0fun_name() {
4177 fn extract_does_not_move_outer_loop_vars() {
4196 fn $0fun_name(x: &mut i32) {
4219 fn $0fun_name(mut x: i32) {
4246 fn $0fun_name(x: &mut i32) {
4253 // regression test for #9822
4255 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4261 fn foo(&mut self) {}
4275 fn foo(&mut self) {}
4286 fn $0fun_name(y: &mut Foo) {
4294 fn extract_with_macro_arg() {
4299 ($val:expr) => { $val };
4308 ($val:expr) => { $val };
4315 fn $0fun_name(bar: &str) {
4323 fn unresolveable_types_default_to_placeholder() {
4328 let a = __unresolved;
4334 let a = __unresolved;
4335 let _ = fun_name(a);
4338 fn $0fun_name(a: _) -> _ {
4346 fn reference_mutable_param_with_further_usages() {
4354 pub fn testfn(arg: &mut Foo) {
4356 // Simulating access after the extracted portion
4365 pub fn testfn(arg: &mut Foo) {
4367 // Simulating access after the extracted portion
4371 fn $0fun_name(arg: &mut Foo) {
4379 fn reference_mutable_param_without_further_usages() {
4387 pub fn testfn(arg: &mut Foo) {
4396 pub fn testfn(arg: &mut Foo) {
4400 fn $0fun_name(arg: &mut Foo) {
4408 fn extract_function_copies_comment_at_start() {
4433 fn extract_function_copies_comment_in_between() {
4462 fn extract_function_copies_comment_at_end() {
4487 fn extract_function_copies_comment_indented() {
4516 fn extract_function_does_not_preserve_whitespace() {
4542 fn extract_function_long_form_comment() {
4567 fn extract_function_long_form_comment_multiline() {
4598 fn extract_function_long_form_comment_multiline_alone() {