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 and comments into new function.
56 // fn $0fun_name(n: i32) {
62 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
63 let range = ctx.selection_trimmed();
68 let node = ctx.covering_element();
69 if node.kind() == COMMENT {
70 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
74 let node = match node {
75 syntax::NodeOrToken::Node(n) => n,
76 syntax::NodeOrToken::Token(t) => t.parent()?,
79 let body = extraction_target(&node, range)?;
80 let container_info = body.analyze_container(&ctx.sema)?;
82 let (locals_used, self_param) = body.analyze(&ctx.sema);
84 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
85 let insert_after = node_to_insert_after(&body, anchor)?;
86 let module = ctx.sema.scope(&insert_after).module()?;
88 let ret_ty = body.return_ty(ctx)?;
89 let control_flow = body.external_control_flow(ctx, &container_info)?;
90 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
92 let target_range = body.text_range();
94 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
97 AssistId("extract_function", crate::AssistKind::RefactorExtract),
98 "Extract into function",
101 let outliving_locals: Vec<_> = ret_values.collect();
102 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
103 // We should not have variables that outlive body if we have expression block
108 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
111 name: make::name_ref("fun_name"),
118 mods: container_info,
121 let new_indent = IndentLevel::from_node(&insert_after);
122 let old_indent = fun.body.indent_level();
124 builder.replace(target_range, make_call(ctx, &fun, old_indent));
126 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
127 let insert_offset = insert_after.text_range().end();
129 if fn_def.contains("ControlFlow") {
130 let scope = match scope {
131 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
132 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
133 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
136 let control_flow_enum =
137 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
139 if let Some(control_flow_enum) = control_flow_enum {
140 let mod_path = module.find_use_path_prefixed(
142 ModuleDef::from(control_flow_enum),
143 ctx.config.insert_use.prefix_kind,
146 if let Some(mod_path) = mod_path {
147 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
152 match ctx.config.snippet_cap {
153 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
154 None => builder.insert(insert_offset, fn_def),
160 /// Try to guess what user wants to extract
162 /// We have basically have two cases:
163 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
164 /// Then we can use `ast::Expr`
165 /// * We want a few statements for a block. E.g.
167 /// fn foo() -> i32 {
177 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
178 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
180 ast::Stmt::Item(_) => None,
181 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
182 node.parent().and_then(ast::StmtList::cast)?,
188 // Covering element returned the parent block of one or multiple statements that have been selected
189 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
190 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
191 if block_expr.syntax().text_range() == selection_range {
192 return FunctionBody::from_expr(block_expr.into());
196 // Extract the full statements.
197 return Some(FunctionBody::from_range(stmt_list, selection_range));
200 let expr = ast::Expr::cast(node.clone())?;
201 // A node got selected fully
202 if node.text_range() == selection_range {
203 return FunctionBody::from_expr(expr);
206 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
212 self_param: Option<ast::SelfParam>,
214 control_flow: ControlFlow,
217 outliving_locals: Vec<OutlivedLocal>,
230 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
238 #[derive(Debug, Eq, PartialEq)]
242 Tuple(Vec<hir::Type>),
245 /// Where to put extracted function definition
248 /// Extract free function and put right after current top-level function
250 /// Extract method and put right after current function in the impl-block
254 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
255 // probably be merged somehow.
258 kind: Option<FlowKind>,
263 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
264 #[derive(Clone, Debug)]
265 struct ContainerInfo {
268 parent_loop: Option<SyntaxNode>,
269 /// The function's return type, const's type etc.
270 ret_type: Option<hir::Type>,
273 /// Control flow that is exported from extracted function
285 #[derive(Debug, Clone)]
287 /// Return with value (`return $expr;`)
288 Return(Option<ast::Expr>),
292 /// Break with value (`break $expr;`)
293 Break(Option<ast::Expr>),
298 #[derive(Debug, Clone)]
301 Result { ty: hir::Type },
311 fn is_unit(&self) -> bool {
313 RetType::Expr(ty) => ty.is_unit(),
314 RetType::Stmt => true,
319 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
320 /// This is the future function body, the part that is being extracted.
324 Span { parent: ast::StmtList, text_range: TextRange },
328 struct OutlivedLocal {
330 mut_usage_outside_body: bool,
333 /// Container of local variable usages
335 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
336 struct LocalUsages(ide_db::search::UsageSearchResult);
339 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
341 Definition::Local(var)
343 .in_scope(SearchScope::single_file(ctx.file_id()))
348 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
349 self.0.iter().flat_map(|(_, rs)| rs)
354 fn return_type(&self, ctx: &AssistContext) -> FunType {
356 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
357 RetType::Expr(ty) => FunType::Single(ty.clone()),
358 RetType::Stmt => match self.outliving_locals.as_slice() {
360 [var] => FunType::Single(var.local.ty(ctx.db())),
362 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
363 FunType::Tuple(types)
371 fn is_ref(&self) -> bool {
372 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
377 fn kind(&self) -> ParamKind {
378 match (self.move_local, self.requires_mut, self.is_copy) {
379 (false, true, _) => ParamKind::MutRef,
380 (false, false, false) => ParamKind::SharedRef,
381 (true, true, _) => ParamKind::MutValue,
382 (_, false, _) => ParamKind::Value,
386 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
387 let var = path_expr_from_local(ctx, self.var);
389 ParamKind::Value | ParamKind::MutValue => var,
390 ParamKind::SharedRef => make::expr_ref(var, false),
391 ParamKind::MutRef => make::expr_ref(var, true),
395 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
396 let var = self.var.name(ctx.db()).unwrap().to_string();
397 let var_name = make::name(&var);
398 let pat = match self.kind() {
399 ParamKind::MutValue => make::ident_pat(false, true, var_name),
400 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
401 make::ext::simple_ident_pat(var_name)
405 let ty = make_ty(&self.ty, ctx, module);
406 let ty = match self.kind() {
407 ParamKind::Value | ParamKind::MutValue => ty,
408 ParamKind::SharedRef => make::ty_ref(ty, false),
409 ParamKind::MutRef => make::ty_ref(ty, true),
412 make::param(pat.into(), ty)
417 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
419 // We favour Result for `expr?`
420 return Some(TryKind::Result { ty });
422 let adt = ty.as_adt()?;
423 let name = adt.name(ctx.db());
424 // FIXME: use lang items to determine if it is std type or user defined
425 // E.g. if user happens to define type named `Option`, we would have false positive
426 match name.to_string().as_str() {
427 "Option" => Some(TryKind::Option),
428 "Result" => Some(TryKind::Result { ty }),
435 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
437 FlowKind::Return(_) => make::expr_return(expr),
438 FlowKind::Break(_) => make::expr_break(expr),
439 FlowKind::Try { .. } => {
440 stdx::never!("cannot have result handler with try");
441 expr.unwrap_or_else(|| make::expr_return(None))
443 FlowKind::Continue => {
444 stdx::always!(expr.is_none(), "continue with value is not possible");
445 make::expr_continue()
450 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
452 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
453 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
455 FlowKind::Try { .. } => {
456 stdx::never!("try does not have defined expr_ty");
465 fn parent(&self) -> Option<SyntaxNode> {
467 FunctionBody::Expr(expr) => expr.syntax().parent(),
468 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
472 fn from_expr(expr: ast::Expr) -> Option<Self> {
474 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
475 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
476 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
477 expr => Some(Self::Expr(expr)),
481 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
482 let full_body = parent.syntax().children_with_tokens();
484 let mut text_range = full_body
485 .filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
486 .map(|element| element.text_range())
487 .filter(|&range| selected.intersect(range).filter(|it| !it.is_empty()).is_some())
488 .reduce(|acc, stmt| acc.cover(stmt));
490 if let Some(tail_range) = parent
492 .map(|it| it.syntax().text_range())
493 .filter(|&it| selected.intersect(it).is_some())
495 text_range = Some(match text_range {
496 Some(text_range) => text_range.cover(tail_range),
500 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
503 fn indent_level(&self) -> IndentLevel {
505 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
506 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
510 fn tail_expr(&self) -> Option<ast::Expr> {
512 FunctionBody::Expr(expr) => Some(expr.clone()),
513 FunctionBody::Span { parent, text_range } => {
514 let tail_expr = parent.tail_expr()?;
515 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
520 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
522 FunctionBody::Expr(expr) => walk_expr(expr, cb),
523 FunctionBody::Span { parent, text_range } => {
526 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
527 .filter_map(|stmt| match stmt {
528 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
529 ast::Stmt::Item(_) => None,
530 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
532 .for_each(|expr| walk_expr(&expr, cb));
533 if let Some(expr) = parent
535 .filter(|it| text_range.contains_range(it.syntax().text_range()))
537 walk_expr(&expr, cb);
543 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
545 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
546 FunctionBody::Span { parent, text_range } => {
549 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
550 .filter_map(|stmt| match stmt {
551 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
552 ast::Stmt::Item(_) => None,
553 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
555 .for_each(|expr| preorder_expr(&expr, cb));
556 if let Some(expr) = parent
558 .filter(|it| text_range.contains_range(it.syntax().text_range()))
560 preorder_expr(&expr, cb);
566 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
568 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
569 FunctionBody::Span { parent, text_range } => {
572 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
573 .for_each(|stmt| match stmt {
574 ast::Stmt::ExprStmt(expr_stmt) => {
575 if let Some(expr) = expr_stmt.expr() {
576 walk_patterns_in_expr(&expr, cb)
579 ast::Stmt::Item(_) => (),
580 ast::Stmt::LetStmt(stmt) => {
581 if let Some(pat) = stmt.pat() {
584 if let Some(expr) = stmt.initializer() {
585 walk_patterns_in_expr(&expr, cb);
589 if let Some(expr) = parent
591 .filter(|it| text_range.contains_range(it.syntax().text_range()))
593 walk_patterns_in_expr(&expr, cb);
599 fn text_range(&self) -> TextRange {
601 FunctionBody::Expr(expr) => expr.syntax().text_range(),
602 &FunctionBody::Span { text_range, .. } => text_range,
606 fn contains_range(&self, range: TextRange) -> bool {
607 self.text_range().contains_range(range)
610 fn precedes_range(&self, range: TextRange) -> bool {
611 self.text_range().end() <= range.start()
614 fn contains_node(&self, node: &SyntaxNode) -> bool {
615 self.contains_range(node.text_range())
620 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
621 /// whether it contains an await expression.
624 sema: &Semantics<RootDatabase>,
625 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
626 let mut self_param = None;
627 let mut res = FxIndexSet::default();
628 let mut cb = |name_ref: Option<_>| {
630 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
632 NameRefClass::Definition(Definition::Local(local_ref))
633 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
637 let InFile { file_id, value } = local_ref.source(sema.db);
638 // locals defined inside macros are not relevant to us
639 if !file_id.is_macro() {
641 Either::Right(it) => {
642 self_param.replace(it);
645 res.insert(local_ref);
650 self.walk_expr(&mut |expr| match expr {
651 ast::Expr::PathExpr(path_expr) => {
652 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
654 ast::Expr::MacroCall(call) => {
655 if let Some(tt) = call.token_tree() {
657 .children_with_tokens()
658 .flat_map(SyntaxElement::into_token)
659 .filter(|it| it.kind() == SyntaxKind::IDENT)
660 .flat_map(|t| sema.descend_into_macros(t))
661 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
669 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
670 let mut ancestors = self.parent()?.ancestors();
671 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
672 let mut parent_loop = None;
673 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
676 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
678 parent_loop.get_or_insert(loop_.syntax().clone());
681 let (is_const, expr, ty) = loop {
682 let anc = ancestors.next()?;
685 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
686 ast::BlockExpr(block_expr) => {
687 let (constness, block) = match block_expr.modifier() {
688 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
689 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
690 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
693 let expr = Some(ast::Expr::BlockExpr(block));
694 (constness, expr.clone(), infer_expr_opt(expr))
697 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
699 ast::Static(statik) => {
700 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
702 ast::ConstArg(ca) => {
703 (true, ca.expr(), infer_expr_opt(ca.expr()))
705 ast::Const(konst) => {
706 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
708 ast::ConstParam(cp) => {
709 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
711 ast::ConstBlockPat(cbp) => {
712 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
713 (true, expr.clone(), infer_expr_opt(expr))
715 ast::Variant(__) => return None,
716 ast::Meta(__) => return None,
717 ast::LoopExpr(it) => {
718 set_parent_loop(&it);
721 ast::ForExpr(it) => {
722 set_parent_loop(&it);
725 ast::WhileExpr(it) => {
726 set_parent_loop(&it);
733 let container_tail = match expr? {
734 ast::Expr::BlockExpr(block) => block.tail_expr(),
738 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
739 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
741 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
744 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
745 match self.tail_expr() {
746 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
747 None => Some(RetType::Stmt),
751 /// Local variables defined inside `body` that are accessed outside of it
754 ctx: &'a AssistContext,
756 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
757 let parent = parent.clone();
758 let range = self.text_range();
759 locals_defined_in_body(&ctx.sema, self)
761 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
764 /// Analyses the function body for external control flow.
765 fn external_control_flow(
768 container_info: &ContainerInfo,
769 ) -> Option<ControlFlow> {
770 let mut ret_expr = None;
771 let mut try_expr = None;
772 let mut break_expr = None;
773 let mut continue_expr = None;
774 let mut is_async = false;
775 let mut _is_unsafe = false;
777 let mut unsafe_depth = 0;
778 let mut loop_depth = 0;
780 self.preorder_expr(&mut |expr| {
781 let expr = match expr {
782 WalkEvent::Enter(e) => e,
783 WalkEvent::Leave(expr) => {
785 ast::Expr::LoopExpr(_)
786 | ast::Expr::ForExpr(_)
787 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
788 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
797 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
800 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
803 ast::Expr::ReturnExpr(it) => {
806 ast::Expr::TryExpr(it) => {
809 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
810 break_expr = Some(it);
812 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
813 continue_expr = Some(it);
815 ast::Expr::AwaitExpr(_) => is_async = true,
816 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
817 // to just lift that out of there
818 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
824 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
825 (Some(_), _, None, None) => {
826 let ret_ty = container_info.ret_type.clone()?;
827 let kind = TryKind::of_ty(ret_ty, ctx)?;
829 Some(FlowKind::Try { kind })
831 (Some(_), _, _, _) => {
832 cov_mark::hit!(external_control_flow_try_and_bc);
835 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
836 (None, Some(_), _, _) => {
837 cov_mark::hit!(external_control_flow_return_and_bc);
840 (None, None, Some(_), Some(_)) => {
841 cov_mark::hit!(external_control_flow_break_and_continue);
844 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
845 (None, None, None, Some(_)) => Some(FlowKind::Continue),
846 (None, None, None, None) => None,
849 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
852 /// find variables that should be extracted as params
854 /// Computes additional info that affects param type and mutability
855 fn extracted_function_params(
858 container_info: &ContainerInfo,
859 locals: impl Iterator<Item = Local>,
862 .map(|local| (local, local.source(ctx.db())))
863 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
864 .filter_map(|(local, src)| match src.value {
865 Either::Left(src) => Some((local, src)),
866 Either::Right(_) => {
867 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
872 let usages = LocalUsages::find_local_usages(ctx, var);
873 let ty = var.ty(ctx.db());
875 let defined_outside_parent_loop = container_info
878 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
880 let is_copy = ty.is_copy(ctx.db());
881 let has_usages = self.has_usages_after_body(&usages);
883 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
884 // We can move the value into the function call if it's not used after the call,
885 // if the var is not used but defined outside a loop we are extracting from we can't move it either
886 // as the function will reuse it in the next iteration.
887 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
888 Param { var, ty, move_local, requires_mut, is_copy }
893 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
894 usages.iter().any(|reference| self.precedes_range(reference.range))
898 /// checks if relevant var is used with `&mut` access inside body
899 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
902 .filter(|reference| body.contains_range(reference.range))
903 .any(|reference| reference_is_exclusive(reference, body, ctx))
906 /// checks if this reference requires `&mut` access inside node
907 fn reference_is_exclusive(
908 reference: &FileReference,
909 node: &dyn HasTokenAtOffset,
912 // we directly modify variable with set: `n = 0`, `n += 1`
913 if reference.category == Some(ReferenceCategory::Write) {
917 // we take `&mut` reference to variable: `&mut v`
918 let path = match path_element_of_reference(node, reference) {
920 None => return false,
923 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
926 /// checks if this expr requires `&mut` access, recurses on field access
927 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
928 if let ast::Expr::MacroCall(_) = expr {
929 // FIXME: expand macro and check output for mutable usages of the variable?
933 let parent = expr.syntax().parent()?;
935 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
936 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
937 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
942 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
943 return Some(ref_expr.mut_token().is_some());
946 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
947 let func = ctx.sema.resolve_method_call(&method_call)?;
948 let self_param = func.self_param(ctx.db())?;
949 let access = self_param.access(ctx.db());
951 return Some(matches!(access, hir::Access::Exclusive));
954 if let Some(field) = ast::FieldExpr::cast(parent) {
955 return expr_require_exclusive_access(ctx, &field.into());
961 trait HasTokenAtOffset {
962 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
965 impl HasTokenAtOffset for SyntaxNode {
966 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
967 SyntaxNode::token_at_offset(self, offset)
971 impl HasTokenAtOffset for FunctionBody {
972 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
974 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
975 FunctionBody::Span { parent, text_range } => {
976 match parent.syntax().token_at_offset(offset) {
977 TokenAtOffset::None => TokenAtOffset::None,
978 TokenAtOffset::Single(t) => {
979 if text_range.contains_range(t.text_range()) {
980 TokenAtOffset::Single(t)
985 TokenAtOffset::Between(a, b) => {
987 text_range.contains_range(a.text_range()),
988 text_range.contains_range(b.text_range()),
990 (true, true) => TokenAtOffset::Between(a, b),
991 (true, false) => TokenAtOffset::Single(a),
992 (false, true) => TokenAtOffset::Single(b),
993 (false, false) => TokenAtOffset::None,
1002 /// find relevant `ast::Expr` for reference
1006 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1007 fn path_element_of_reference(
1008 node: &dyn HasTokenAtOffset,
1009 reference: &FileReference,
1010 ) -> Option<ast::Expr> {
1011 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1012 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1015 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1016 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1020 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1021 "unexpected expression type for variable usage: {:?}",
1027 /// list local variables defined inside `body`
1028 fn locals_defined_in_body(
1029 sema: &Semantics<RootDatabase>,
1030 body: &FunctionBody,
1031 ) -> FxIndexSet<Local> {
1032 // FIXME: this doesn't work well with macros
1033 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1034 let mut res = FxIndexSet::default();
1035 body.walk_pat(&mut |pat| {
1036 if let ast::Pat::IdentPat(pat) = pat {
1037 if let Some(local) = sema.to_def(&pat) {
1045 /// Returns usage details if local variable is used after(outside of) body
1046 fn local_outlives_body(
1047 ctx: &AssistContext,
1048 body_range: TextRange,
1050 parent: &SyntaxNode,
1051 ) -> Option<OutlivedLocal> {
1052 let usages = LocalUsages::find_local_usages(ctx, local);
1053 let mut has_mut_usages = false;
1054 let mut any_outlives = false;
1055 for usage in usages.iter() {
1056 if body_range.end() <= usage.range.start() {
1057 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1058 any_outlives |= true;
1060 break; // no need to check more elements we have all the info we wanted
1067 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1070 /// checks if the relevant local was defined before(outside of) body
1071 fn is_defined_outside_of_body(
1072 ctx: &AssistContext,
1073 body: &FunctionBody,
1074 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1076 src.file_id.original_file(ctx.db()) == ctx.file_id()
1077 && !body.contains_node(either_syntax(&src.value))
1080 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1082 Either::Left(pat) => pat.syntax(),
1083 Either::Right(it) => it.syntax(),
1087 /// find where to put extracted function definition
1089 /// Function should be put right after returned node
1090 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1091 let node = match body {
1092 FunctionBody::Expr(e) => e.syntax(),
1093 FunctionBody::Span { parent, .. } => parent.syntax(),
1095 let mut ancestors = node.ancestors().peekable();
1096 let mut last_ancestor = None;
1097 while let Some(next_ancestor) = ancestors.next() {
1098 match next_ancestor.kind() {
1099 SyntaxKind::SOURCE_FILE => break,
1100 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1101 SyntaxKind::ITEM_LIST => {
1102 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1106 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1109 SyntaxKind::ASSOC_ITEM_LIST => {
1110 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1116 last_ancestor = Some(next_ancestor);
1121 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1122 let ret_ty = fun.return_type(ctx);
1124 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1125 let name = fun.name.clone();
1126 let mut call_expr = if fun.self_param.is_some() {
1127 let self_arg = make::expr_path(make::ext::ident_path("self"));
1128 make::expr_method_call(self_arg, name, args)
1130 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1131 make::expr_call(func, args)
1134 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1136 if fun.control_flow.is_async {
1137 call_expr = make::expr_await(call_expr);
1139 let expr = handler.make_call_expr(call_expr).indent(indent);
1141 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1143 let mut buf = String::new();
1144 match fun.outliving_locals.as_slice() {
1147 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1150 buf.push_str("let (");
1151 let bindings = vars.iter().format_with(", ", |local, f| {
1152 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1154 format_to!(buf, "{}", bindings);
1155 buf.push_str(") = ");
1159 format_to!(buf, "{}", expr);
1160 let insert_comma = fun
1163 .and_then(ast::MatchArm::cast)
1164 .map_or(false, |it| it.comma_token().is_none());
1167 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1175 Try { kind: TryKind },
1176 If { action: FlowKind },
1177 IfOption { action: FlowKind },
1178 MatchOption { none: FlowKind },
1179 MatchResult { err: FlowKind },
1183 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1184 match &fun.control_flow.kind {
1185 None => FlowHandler::None,
1186 Some(flow_kind) => {
1187 let action = flow_kind.clone();
1188 if *ret_ty == FunType::Unit {
1190 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1191 FlowHandler::If { action }
1193 FlowKind::Return(_) | FlowKind::Break(_) => {
1194 FlowHandler::IfOption { action }
1196 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1200 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1201 FlowHandler::MatchOption { none: action }
1203 FlowKind::Return(_) | FlowKind::Break(_) => {
1204 FlowHandler::MatchResult { err: action }
1206 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1213 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1215 FlowHandler::None => call_expr,
1216 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1217 FlowHandler::If { action } => {
1218 let action = action.make_result_handler(None);
1219 let stmt = make::expr_stmt(action);
1220 let block = make::block_expr(iter::once(stmt.into()), None);
1221 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1222 let condition = make::expr_let(
1223 make::tuple_struct_pat(
1224 controlflow_break_path,
1225 iter::once(make::wildcard_pat().into()),
1230 make::expr_if(condition.into(), block, None)
1232 FlowHandler::IfOption { action } => {
1233 let path = make::ext::ident_path("Some");
1234 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1235 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1236 let cond = make::expr_let(pattern.into(), call_expr);
1237 let value = make::expr_path(make::ext::ident_path("value"));
1238 let action_expr = action.make_result_handler(Some(value));
1239 let action_stmt = make::expr_stmt(action_expr);
1240 let then = make::block_expr(iter::once(action_stmt.into()), None);
1241 make::expr_if(cond.into(), then, None)
1243 FlowHandler::MatchOption { none } => {
1244 let some_name = "value";
1247 let path = make::ext::ident_path("Some");
1248 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1249 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1250 let value = make::expr_path(make::ext::ident_path(some_name));
1251 make::match_arm(iter::once(pat.into()), None, value)
1254 let path = make::ext::ident_path("None");
1255 let pat = make::path_pat(path);
1256 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1258 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1259 make::expr_match(call_expr, arms)
1261 FlowHandler::MatchResult { err } => {
1262 let ok_name = "value";
1263 let err_name = "value";
1266 let path = make::ext::ident_path("Ok");
1267 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1268 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1269 let value = make::expr_path(make::ext::ident_path(ok_name));
1270 make::match_arm(iter::once(pat.into()), None, value)
1273 let path = make::ext::ident_path("Err");
1274 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1275 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1276 let value = make::expr_path(make::ext::ident_path(err_name));
1278 iter::once(pat.into()),
1280 err.make_result_handler(Some(value)),
1283 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1284 make::expr_match(call_expr, arms)
1290 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1291 let name = var.name(ctx.db()).unwrap().to_string();
1292 make::expr_path(make::ext::ident_path(&name))
1296 ctx: &AssistContext,
1297 module: hir::Module,
1299 old_indent: IndentLevel,
1300 new_indent: IndentLevel,
1302 let mut fn_def = String::new();
1303 let params = fun.make_param_list(ctx, module);
1304 let ret_ty = fun.make_ret_ty(ctx, module);
1305 let body = make_body(ctx, old_indent, new_indent, fun);
1306 let const_kw = if fun.mods.is_const { "const " } else { "" };
1307 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1308 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1309 match ctx.config.snippet_cap {
1310 Some(_) => format_to!(
1312 "\n\n{}{}{}{}fn $0{}{}",
1322 "\n\n{}{}{}{}fn {}{}",
1331 if let Some(ret_ty) = ret_ty {
1332 format_to!(fn_def, " {}", ret_ty);
1334 format_to!(fn_def, " {}", body);
1340 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1341 let self_param = self.self_param.clone();
1342 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1343 make::param_list(self_param, params)
1346 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1347 let fun_ty = self.return_type(ctx);
1348 let handler = if self.mods.is_in_tail {
1351 FlowHandler::from_ret_ty(self, &fun_ty)
1353 let ret_ty = match &handler {
1354 FlowHandler::None => {
1355 if matches!(fun_ty, FunType::Unit) {
1358 fun_ty.make_ty(ctx, module)
1360 FlowHandler::Try { kind: TryKind::Option } => {
1361 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1363 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1364 let handler_ty = parent_ret_ty
1367 .map(|ty| make_ty(&ty, ctx, module))
1368 .unwrap_or_else(make::ty_placeholder);
1369 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1371 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1372 FlowHandler::IfOption { action } => {
1373 let handler_ty = action
1375 .map(|ty| make_ty(&ty, ctx, module))
1376 .unwrap_or_else(make::ty_placeholder);
1377 make::ext::ty_option(handler_ty)
1379 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1380 FlowHandler::MatchResult { err } => {
1381 let handler_ty = err
1383 .map(|ty| make_ty(&ty, ctx, module))
1384 .unwrap_or_else(make::ty_placeholder);
1385 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1388 Some(make::ret_type(ret_ty))
1393 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1395 FunType::Unit => make::ty_unit(),
1396 FunType::Single(ty) => make_ty(ty, ctx, module),
1397 FunType::Tuple(types) => match types.as_slice() {
1399 stdx::never!("tuple type with 0 elements");
1403 stdx::never!("tuple type with 1 element");
1404 make_ty(ty, ctx, module)
1407 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1408 make::ty_tuple(types)
1416 ctx: &AssistContext,
1417 old_indent: IndentLevel,
1418 new_indent: IndentLevel,
1420 ) -> ast::BlockExpr {
1421 let ret_ty = fun.return_type(ctx);
1422 let handler = if fun.mods.is_in_tail {
1425 FlowHandler::from_ret_ty(fun, &ret_ty)
1428 let block = match &fun.body {
1429 FunctionBody::Expr(expr) => {
1430 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1431 let expr = ast::Expr::cast(expr).unwrap();
1433 ast::Expr::BlockExpr(block) => {
1434 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1435 let block = block.dedent(old_indent);
1436 // Recreate the block for formatting consistency with other extracted functions.
1437 make::block_expr(block.statements(), block.tail_expr())
1440 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1442 make::block_expr(Vec::new(), Some(expr))
1446 FunctionBody::Span { parent, text_range } => {
1447 let mut elements: Vec<_> = parent
1449 .children_with_tokens()
1450 .filter(|it| text_range.contains_range(it.text_range()))
1451 .map(|it| match &it {
1452 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1453 rewrite_body_segment(ctx, &fun.params, &handler, &n),
1459 let mut tail_expr = match &elements.last() {
1460 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1461 ast::Expr::cast(node.clone())
1470 None => match fun.outliving_locals.as_slice() {
1473 tail_expr = Some(path_expr_from_local(ctx, var.local));
1476 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1477 let expr = make::expr_tuple(exprs);
1478 tail_expr = Some(expr);
1483 let body_indent = IndentLevel(1);
1484 let elements = elements
1486 .map(|node_or_token| match &node_or_token {
1487 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1489 let indented = stmt.dedent(old_indent).indent(body_indent);
1490 let ast_node = indented.syntax().clone_subtree();
1491 syntax::NodeOrToken::Node(ast_node)
1497 .collect::<Vec<SyntaxElement>>();
1498 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1500 make::hacky_block_expr_with_comments(elements, tail_expr)
1504 let block = match &handler {
1505 FlowHandler::None => block,
1506 FlowHandler::Try { kind } => {
1507 let block = with_default_tail_expr(block, make::expr_unit());
1508 map_tail_expr(block, |tail_expr| {
1509 let constructor = match kind {
1510 TryKind::Option => "Some",
1511 TryKind::Result { .. } => "Ok",
1513 let func = make::expr_path(make::ext::ident_path(constructor));
1514 let args = make::arg_list(iter::once(tail_expr));
1515 make::expr_call(func, args)
1518 FlowHandler::If { .. } => {
1519 let controlflow_continue = make::expr_call(
1520 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1521 make::arg_list(iter::once(make::expr_unit())),
1523 with_tail_expr(block, controlflow_continue.into())
1525 FlowHandler::IfOption { .. } => {
1526 let none = make::expr_path(make::ext::ident_path("None"));
1527 with_tail_expr(block, none)
1529 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1530 let some = make::expr_path(make::ext::ident_path("Some"));
1531 let args = make::arg_list(iter::once(tail_expr));
1532 make::expr_call(some, args)
1534 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1535 let ok = make::expr_path(make::ext::ident_path("Ok"));
1536 let args = make::arg_list(iter::once(tail_expr));
1537 make::expr_call(ok, args)
1541 block.indent(new_indent)
1544 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1545 let tail_expr = match block.tail_expr() {
1546 Some(tail_expr) => tail_expr,
1547 None => return block,
1549 make::block_expr(block.statements(), Some(f(tail_expr)))
1552 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1553 match block.tail_expr() {
1555 None => make::block_expr(block.statements(), Some(tail_expr)),
1559 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1560 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1561 let stmts = block.statements().chain(stmt_tail);
1562 make::block_expr(stmts, Some(tail_expr))
1565 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1566 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1569 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1570 let ty_str = format_type(ty, ctx, module);
1574 fn rewrite_body_segment(
1575 ctx: &AssistContext,
1577 handler: &FlowHandler,
1578 syntax: &SyntaxNode,
1580 let syntax = fix_param_usages(ctx, params, syntax);
1581 update_external_control_flow(handler, &syntax);
1585 /// change all usages to account for added `&`/`&mut` for some params
1586 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1587 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1589 let tm = TreeMutator::new(syntax);
1591 for param in params {
1592 if !param.kind().is_ref() {
1596 let usages = LocalUsages::find_local_usages(ctx, param.var);
1599 .filter(|reference| syntax.text_range().contains_range(reference.range))
1600 .filter_map(|reference| path_element_of_reference(syntax, reference))
1601 .map(|expr| tm.make_mut(&expr));
1603 usages_for_param.push((param, usages.collect()));
1606 let res = tm.make_syntax_mut(syntax);
1608 for (param, usages) in usages_for_param {
1609 for usage in usages {
1610 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1611 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1614 Some(ast::Expr::RefExpr(node))
1615 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1617 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1619 Some(ast::Expr::RefExpr(node))
1620 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1622 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1625 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1626 ted::replace(usage.syntax(), p.syntax())
1635 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1636 let mut nested_loop = None;
1637 let mut nested_scope = None;
1638 for event in syntax.preorder() {
1640 WalkEvent::Enter(e) => match e.kind() {
1641 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1642 if nested_loop.is_none() {
1643 nested_loop = Some(e.clone());
1648 | SyntaxKind::STATIC
1650 | SyntaxKind::MODULE => {
1651 if nested_scope.is_none() {
1652 nested_scope = Some(e.clone());
1657 WalkEvent::Leave(e) => {
1658 if nested_scope.is_none() {
1659 if let Some(expr) = ast::Expr::cast(e.clone()) {
1661 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1662 let expr = return_expr.expr();
1663 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1664 ted::replace(return_expr.syntax(), replacement.syntax())
1667 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1668 let expr = break_expr.expr();
1669 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1670 ted::replace(break_expr.syntax(), replacement.syntax())
1673 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1674 if let Some(replacement) = make_rewritten_flow(handler, None) {
1675 ted::replace(continue_expr.syntax(), replacement.syntax())
1685 if nested_loop.as_ref() == Some(&e) {
1688 if nested_scope.as_ref() == Some(&e) {
1689 nested_scope = None;
1696 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1697 let value = match handler {
1698 FlowHandler::None | FlowHandler::Try { .. } => return None,
1699 FlowHandler::If { .. } => make::expr_call(
1700 make::expr_path(make::path_from_text("ControlFlow::Break")),
1701 make::arg_list(iter::once(make::expr_unit())),
1703 FlowHandler::IfOption { .. } => {
1704 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1705 let args = make::arg_list(iter::once(expr));
1706 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1708 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1709 FlowHandler::MatchResult { .. } => {
1710 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1711 let args = make::arg_list(iter::once(expr));
1712 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1715 Some(make::expr_return(Some(value)).clone_for_update())
1720 use crate::tests::{check_assist, check_assist_not_applicable};
1725 fn no_args_from_binary_expr() {
1738 fn $0fun_name() -> i32 {
1746 fn no_args_from_binary_expr_in_module() {
1762 fn $0fun_name() -> i32 {
1771 fn no_args_from_binary_expr_indented() {
1784 fn $0fun_name() -> i32 {
1792 fn no_args_from_stmt_with_last_expr() {
1808 fn $0fun_name() -> i32 {
1817 fn no_args_from_stmt_unit() {
1865 fn no_args_if_else() {
1870 $0if true { 1 } else { 2 }$0
1878 fn $0fun_name() -> i32 {
1879 if true { 1 } else { 2 }
1886 fn no_args_if_let_else() {
1891 $0if let true = false { 1 } else { 2 }$0
1899 fn $0fun_name() -> i32 {
1900 if let true = false { 1 } else { 2 }
1907 fn no_args_match() {
1923 fn $0fun_name() -> i32 {
1934 fn no_args_while() {
1960 $0for v in &[0, 1] { }$0
1969 for v in &[0, 1] { }
1976 fn no_args_from_loop_unit() {
1991 fn $0fun_name() -> ! {
2001 fn no_args_from_loop_with_return() {
2017 fn $0fun_name() -> i32 {
2028 fn no_args_from_match() {
2033 let v: i32 = $0match Some(1) {
2041 let v: i32 = fun_name();
2044 fn $0fun_name() -> i32 {
2055 fn extract_partial_block_single_line() {
2061 let mut v = $0n * n;$0
2068 let mut v = fun_name(n);
2072 fn $0fun_name(n: i32) -> i32 {
2081 fn extract_partial_block() {
2088 let mut v = m $0* n;
2098 let (mut v, mut w) = fun_name(m, n);
2103 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2113 fn argument_form_expr() {
2128 fn $0fun_name(n: u32) -> u32 {
2136 fn argument_used_twice_form_expr() {
2151 fn $0fun_name(n: u32) -> u32 {
2159 fn two_arguments_form_expr() {
2176 fn $0fun_name(n: u32, m: u32) -> u32 {
2184 fn argument_and_locals() {
2200 fn $0fun_name(n: u32) -> u32 {
2209 fn in_comment_is_not_applicable() {
2210 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2211 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2215 fn part_of_expr_stmt() {
2228 fn $0fun_name() -> i32 {
2236 fn function_expr() {
2257 fn extract_from_nested() {
2263 let tuple = match x {
2264 true => ($02 + 2$0, true)
2272 let tuple = match x {
2273 true => (fun_name(), true)
2278 fn $0fun_name() -> i32 {
2286 fn param_from_closure() {
2291 let lambda = |x: u32| $0x * 2$0;
2296 let lambda = |x: u32| fun_name(x);
2299 fn $0fun_name(x: u32) -> u32 {
2307 fn extract_return_stmt() {
2320 fn $0fun_name() -> u32 {
2328 fn does_not_add_extra_whitespace() {
2345 fn $0fun_name() -> u32 {
2370 fn $0fun_name() -> i32 {
2383 let v = $00f32 as u32$0;
2391 fn $0fun_name() -> u32 {
2399 fn return_not_applicable() {
2400 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2404 fn method_to_freestanding() {
2411 fn foo(&self) -> i32 {
2420 fn foo(&self) -> i32 {
2425 fn $0fun_name() -> i32 {
2433 fn method_with_reference() {
2437 struct S { f: i32 };
2440 fn foo(&self) -> i32 {
2446 struct S { f: i32 };
2449 fn foo(&self) -> i32 {
2453 fn $0fun_name(&self) -> i32 {
2462 fn method_with_mut() {
2466 struct S { f: i32 };
2475 struct S { f: i32 };
2482 fn $0fun_name(&mut self) {
2491 fn variable_defined_inside_and_used_after_no_ret() {
2504 let k = fun_name(n);
2508 fn $0fun_name(n: i32) -> i32 {
2517 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2523 $0let mut k = n * n;$0
2530 let mut k = fun_name(n);
2534 fn $0fun_name(n: i32) -> i32 {
2543 fn two_variables_defined_inside_and_used_after_no_ret() {
2557 let (k, m) = fun_name(n);
2561 fn $0fun_name(n: i32) -> (i32, i32) {
2571 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2577 $0let mut k = n * n;
2588 let (mut k, mut m, o) = fun_name(n);
2593 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2605 fn nontrivial_patterns_define_variables() {
2609 struct Counter(i32);
2611 $0let Counter(n) = Counter(0);$0
2616 struct Counter(i32);
2622 fn $0fun_name() -> i32 {
2623 let Counter(n) = Counter(0);
2631 fn struct_with_two_fields_pattern_define_variables() {
2635 struct Counter { n: i32, m: i32 };
2637 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2642 struct Counter { n: i32, m: i32 };
2644 let (n, k) = fun_name();
2648 fn $0fun_name() -> (i32, i32) {
2649 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2657 fn mut_var_from_outer_scope() {
2674 fn $0fun_name(n: &mut i32) {
2682 fn mut_field_from_outer_scope() {
2688 let mut c = C { n: 0 };
2696 let mut c = C { n: 0 };
2701 fn $0fun_name(c: &mut C) {
2709 fn mut_nested_field_from_outer_scope() {
2716 let mut c = C { p: P { n: 0 } };
2717 let mut v = C { p: P { n: 0 } };
2718 let u = C { p: P { n: 0 } };
2720 let r = &mut v.p.n;$0
2721 let m = c.p.n + v.p.n + u.p.n;
2728 let mut c = C { p: P { n: 0 } };
2729 let mut v = C { p: P { n: 0 } };
2730 let u = C { p: P { n: 0 } };
2731 fun_name(&mut c, &u, &mut v);
2732 let m = c.p.n + v.p.n + u.p.n;
2735 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2744 fn mut_param_many_usages_stmt() {
2750 fn succ(&self) -> Self;
2751 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2754 fn succ(&self) -> Self { *self + 1 }
2773 fn succ(&self) -> Self;
2774 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2777 fn succ(&self) -> Self { *self + 1 }
2785 fn $0fun_name(n: &mut i32) {
2801 fn mut_param_many_usages_expr() {
2807 fn succ(&self) -> Self;
2808 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2811 fn succ(&self) -> Self { *self + 1 }
2832 fn succ(&self) -> Self;
2833 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2836 fn succ(&self) -> Self { *self + 1 }
2844 fn $0fun_name(n: &mut i32) {
2860 fn mut_param_by_value() {
2875 fn $0fun_name(mut n: i32) {
2883 fn mut_param_because_of_mut_ref() {
2901 fn $0fun_name(n: &mut i32) {
2910 fn mut_param_by_value_because_of_mut_ref() {
2926 fn $0fun_name(mut n: i32) {
2935 fn mut_method_call() {
2943 fn inc(&mut self) { *self += 1 }
2955 fn inc(&mut self) { *self += 1 }
2962 fn $0fun_name(mut n: i32) {
2970 fn shared_method_call() {
2978 fn succ(&self) { *self + 1 }
2990 fn succ(&self) { *self + 1 }
2997 fn $0fun_name(n: i32) {
3005 fn mut_method_call_with_other_receiver() {
3010 fn inc(&mut self, n: i32);
3013 fn inc(&mut self, n: i32) { *self += n }
3023 fn inc(&mut self, n: i32);
3026 fn inc(&mut self, n: i32) { *self += n }
3033 fn $0fun_name(n: i32) {
3042 fn non_copy_without_usages_after() {
3046 struct Counter(i32);
3053 struct Counter(i32);
3059 fn $0fun_name(c: Counter) {
3067 fn non_copy_used_after() {
3071 struct Counter(i32);
3079 struct Counter(i32);
3086 fn $0fun_name(c: &Counter) {
3094 fn copy_used_after() {
3112 fn $0fun_name(n: i32) {
3120 fn copy_custom_used_after() {
3124 //- minicore: copy, derive
3125 #[derive(Clone, Copy)]
3126 struct Counter(i32);
3134 #[derive(Clone, Copy)]
3135 struct Counter(i32);
3142 fn $0fun_name(c: Counter) {
3150 fn indented_stmts() {
3181 fn indented_stmts_inside_mod() {
3220 //- minicore: option
3235 let k = match fun_name(n) {
3236 Some(value) => value,
3243 fn $0fun_name(n: i32) -> Option<i32> {
3254 fn return_to_parent() {
3258 //- minicore: copy, result
3270 let k = match fun_name(n) {
3272 Err(value) => return value,
3277 fn $0fun_name(n: i32) -> Result<i32, i64> {
3288 fn break_and_continue() {
3289 cov_mark::check!(external_control_flow_break_and_continue);
3290 check_assist_not_applicable(
3309 fn return_and_break() {
3310 cov_mark::check!(external_control_flow_return_and_bc);
3311 check_assist_not_applicable(
3330 fn break_loop_with_if() {
3346 use core::ops::ControlFlow;
3351 if let ControlFlow::Break(_) = fun_name(&mut n) {
3358 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3360 return ControlFlow::Break(());
3362 ControlFlow::Continue(())
3369 fn break_loop_nested() {
3386 use core::ops::ControlFlow;
3391 if let ControlFlow::Break(_) = fun_name(n) {
3398 fn $0fun_name(n: i32) -> ControlFlow<()> {
3401 return ControlFlow::Break(());
3403 ControlFlow::Continue(())
3410 fn return_from_nested_loop() {
3430 let m = match fun_name() {
3431 Some(value) => value,
3438 fn $0fun_name() -> Option<i32> {
3451 fn break_from_nested_loop() {
3476 fn $0fun_name() -> i32 {
3489 fn break_from_nested_and_outer_loops() {
3512 let m = match fun_name() {
3513 Some(value) => value,
3520 fn $0fun_name() -> Option<i32> {
3536 fn return_from_nested_fn() {
3561 fn $0fun_name() -> i32 {
3574 fn break_with_value() {
3594 if let Some(value) = fun_name() {
3601 fn $0fun_name() -> Option<i32> {
3614 fn break_with_value_and_return() {
3634 let m = match fun_name() {
3636 Err(value) => break value,
3642 fn $0fun_name() -> Result<i32, i64> {
3659 //- minicore: option
3660 fn bar() -> Option<i32> { None }
3661 fn foo() -> Option<()> {
3670 fn bar() -> Option<i32> { None }
3671 fn foo() -> Option<()> {
3673 let m = fun_name()?;
3678 fn $0fun_name() -> Option<i32> {
3688 fn try_option_unit() {
3692 //- minicore: option
3693 fn foo() -> Option<()> {
3702 fn foo() -> Option<()> {
3709 fn $0fun_name() -> Option<()> {
3723 //- minicore: result
3724 fn foo() -> Result<(), i64> {
3733 fn foo() -> Result<(), i64> {
3735 let m = fun_name()?;
3740 fn $0fun_name() -> Result<i32, i64> {
3750 fn try_option_with_return() {
3754 //- minicore: option
3755 fn foo() -> Option<()> {
3767 fn foo() -> Option<()> {
3769 let m = fun_name()?;
3774 fn $0fun_name() -> Option<i32> {
3787 fn try_result_with_return() {
3791 //- minicore: result
3792 fn foo() -> Result<(), i64> {
3804 fn foo() -> Result<(), i64> {
3806 let m = fun_name()?;
3811 fn $0fun_name() -> Result<i32, i64> {
3824 fn try_and_break() {
3825 cov_mark::check!(external_control_flow_try_and_bc);
3826 check_assist_not_applicable(
3829 //- minicore: option
3830 fn foo() -> Option<()> {
3846 fn try_and_return_ok() {
3850 //- minicore: result
3851 fn foo() -> Result<(), i64> {
3863 fn foo() -> Result<(), i64> {
3865 let m = fun_name()?;
3870 fn $0fun_name() -> Result<i32, i64> {
3883 fn param_usage_in_macro() {
3888 ($val:expr) => { $val };
3893 $0let k = n * m!(n);$0
3899 ($val:expr) => { $val };
3904 let k = fun_name(n);
3908 fn $0fun_name(n: i32) -> i32 {
3917 fn extract_with_await() {
3922 $0some_function().await;$0
3925 async fn some_function() {
3934 async fn $0fun_name() {
3935 some_function().await;
3938 async fn some_function() {
3946 fn extract_with_await_and_result_not_producing_match_expr() {
3950 async fn foo() -> Result<(), ()> {
3956 async fn foo() -> Result<(), ()> {
3960 async fn $0fun_name() -> _ {
3969 fn extract_with_await_and_result_producing_match_expr() {
3973 async fn foo() -> i32 {
3976 let k = async { 1 }.await;
3986 async fn foo() -> i32 {
3989 let m = match fun_name().await {
3991 Err(value) => break value,
3997 async fn $0fun_name() -> Result<i32, i32> {
3998 let k = async { 1 }.await;
4010 fn extract_with_await_in_args() {
4015 $0function_call("a", some_function().await);$0
4018 async fn some_function() {
4027 async fn $0fun_name() {
4028 function_call("a", some_function().await);
4031 async fn some_function() {
4039 fn extract_does_not_extract_standalone_blocks() {
4040 check_assist_not_applicable(
4049 fn extract_adds_comma_for_match_arm() {
4068 fn $0fun_name() -> i32 {
4091 fn $0fun_name() -> i32 {
4099 fn extract_does_not_tear_comments_apart() {
4126 fn extract_does_not_tear_body_apart() {
4147 fn extract_does_not_wrap_res_in_res() {
4151 //- minicore: result
4152 fn foo() -> Result<(), i64> {
4153 $0Result::<i32, i64>::Ok(0)?;
4158 fn foo() -> Result<(), i64> {
4162 fn $0fun_name() -> Result<(), i64> {
4163 Result::<i32, i64>::Ok(0)?;
4171 fn extract_knows_const() {
4184 const fn $0fun_name() {
4201 const fn $0fun_name() {
4209 fn extract_does_not_move_outer_loop_vars() {
4228 fn $0fun_name(x: &mut i32) {
4251 fn $0fun_name(mut x: i32) {
4278 fn $0fun_name(x: &mut i32) {
4285 // regression test for #9822
4287 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4293 fn foo(&mut self) {}
4307 fn foo(&mut self) {}
4318 fn $0fun_name(y: &mut Foo) {
4326 fn extract_with_macro_arg() {
4331 ($val:expr) => { $val };
4340 ($val:expr) => { $val };
4347 fn $0fun_name(bar: &str) {
4355 fn unresolveable_types_default_to_placeholder() {
4360 let a = __unresolved;
4366 let a = __unresolved;
4367 let _ = fun_name(a);
4370 fn $0fun_name(a: _) -> _ {
4378 fn reference_mutable_param_with_further_usages() {
4386 pub fn testfn(arg: &mut Foo) {
4388 // Simulating access after the extracted portion
4397 pub fn testfn(arg: &mut Foo) {
4399 // Simulating access after the extracted portion
4403 fn $0fun_name(arg: &mut Foo) {
4411 fn reference_mutable_param_without_further_usages() {
4419 pub fn testfn(arg: &mut Foo) {
4428 pub fn testfn(arg: &mut Foo) {
4432 fn $0fun_name(arg: &mut Foo) {
4440 fn extract_function_copies_comment_at_start() {
4465 fn extract_function_copies_comment_in_between() {
4492 fn extract_function_copies_comment_at_end() {
4517 fn extract_function_copies_comment_indented() {
4545 // FIXME: we do want to preserve whitespace
4547 fn extract_function_does_not_preserve_whitespace() {
4573 fn extract_function_long_form_comment() {