5 use hir::{HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
8 famous_defs::FamousDefs,
9 helpers::mod_path_to_ast,
10 imports::insert_use::{insert_use, ImportScope},
11 search::{FileReference, ReferenceCategory, SearchScope},
12 syntax_helpers::node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
13 FxIndexSet, RootDatabase,
15 use itertools::Itertools;
20 edit::{AstNodeEdit, IndentLevel},
23 match_ast, ted, SyntaxElement,
24 SyntaxKind::{self, COMMENT},
25 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
29 assist_context::{AssistContext, Assists, TreeMutator},
33 // Assist: extract_function
35 // Extracts selected statements and comments into new function.
54 // fn $0fun_name(n: i32) {
60 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
61 let range = ctx.selection_trimmed();
66 let node = ctx.covering_element();
67 if node.kind() == COMMENT {
68 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
72 let node = match node {
73 syntax::NodeOrToken::Node(n) => n,
74 syntax::NodeOrToken::Token(t) => t.parent()?,
77 let body = extraction_target(&node, range)?;
78 let container_info = body.analyze_container(&ctx.sema)?;
80 let (locals_used, self_param) = body.analyze(&ctx.sema);
82 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
83 let insert_after = node_to_insert_after(&body, anchor)?;
84 let module = ctx.sema.scope(&insert_after).module()?;
86 let ret_ty = body.return_ty(ctx)?;
87 let control_flow = body.external_control_flow(ctx, &container_info)?;
88 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
90 let target_range = body.text_range();
92 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
95 AssistId("extract_function", crate::AssistKind::RefactorExtract),
96 "Extract into function",
99 let outliving_locals: Vec<_> = ret_values.collect();
100 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
101 // We should not have variables that outlive body if we have expression block
106 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
109 name: make::name_ref("fun_name"),
116 mods: container_info,
119 let new_indent = IndentLevel::from_node(&insert_after);
120 let old_indent = fun.body.indent_level();
122 builder.replace(target_range, make_call(ctx, &fun, old_indent));
124 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
125 let insert_offset = insert_after.text_range().end();
127 if fn_def.contains("ControlFlow") {
128 let scope = match scope {
129 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
130 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
131 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
134 let control_flow_enum =
135 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
137 if let Some(control_flow_enum) = control_flow_enum {
138 let mod_path = module.find_use_path_prefixed(
140 ModuleDef::from(control_flow_enum),
141 ctx.config.insert_use.prefix_kind,
144 if let Some(mod_path) = mod_path {
145 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
150 match ctx.config.snippet_cap {
151 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
152 None => builder.insert(insert_offset, fn_def),
158 /// Try to guess what user wants to extract
160 /// We have basically have two cases:
161 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
162 /// Then we can use `ast::Expr`
163 /// * We want a few statements for a block. E.g.
165 /// fn foo() -> i32 {
175 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
176 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
178 ast::Stmt::Item(_) => None,
179 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
180 node.parent().and_then(ast::StmtList::cast)?,
186 // Covering element returned the parent block of one or multiple statements that have been selected
187 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
188 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
189 if block_expr.syntax().text_range() == selection_range {
190 return FunctionBody::from_expr(block_expr.into());
194 // Extract the full statements.
195 return Some(FunctionBody::from_range(stmt_list, selection_range));
198 let expr = ast::Expr::cast(node.clone())?;
199 // A node got selected fully
200 if node.text_range() == selection_range {
201 return FunctionBody::from_expr(expr);
204 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
210 self_param: Option<ast::SelfParam>,
212 control_flow: ControlFlow,
215 outliving_locals: Vec<OutlivedLocal>,
228 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
236 #[derive(Debug, Eq, PartialEq)]
240 Tuple(Vec<hir::Type>),
243 /// Where to put extracted function definition
246 /// Extract free function and put right after current top-level function
248 /// Extract method and put right after current function in the impl-block
252 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
253 // probably be merged somehow.
256 kind: Option<FlowKind>,
261 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
262 #[derive(Clone, Debug)]
263 struct ContainerInfo {
266 parent_loop: Option<SyntaxNode>,
267 /// The function's return type, const's type etc.
268 ret_type: Option<hir::Type>,
271 /// Control flow that is exported from extracted function
283 #[derive(Debug, Clone)]
285 /// Return with value (`return $expr;`)
286 Return(Option<ast::Expr>),
290 /// Break with value (`break $expr;`)
291 Break(Option<ast::Expr>),
296 #[derive(Debug, Clone)]
299 Result { ty: hir::Type },
309 fn is_unit(&self) -> bool {
311 RetType::Expr(ty) => ty.is_unit(),
312 RetType::Stmt => true,
317 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
318 /// This is the future function body, the part that is being extracted.
322 Span { parent: ast::StmtList, text_range: TextRange },
326 struct OutlivedLocal {
328 mut_usage_outside_body: bool,
331 /// Container of local variable usages
333 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
334 struct LocalUsages(ide_db::search::UsageSearchResult);
337 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
339 Definition::Local(var)
341 .in_scope(SearchScope::single_file(ctx.file_id()))
346 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
347 self.0.iter().flat_map(|(_, rs)| rs)
352 fn return_type(&self, ctx: &AssistContext) -> FunType {
354 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
355 RetType::Expr(ty) => FunType::Single(ty.clone()),
356 RetType::Stmt => match self.outliving_locals.as_slice() {
358 [var] => FunType::Single(var.local.ty(ctx.db())),
360 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
361 FunType::Tuple(types)
369 fn is_ref(&self) -> bool {
370 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
375 fn kind(&self) -> ParamKind {
376 match (self.move_local, self.requires_mut, self.is_copy) {
377 (false, true, _) => ParamKind::MutRef,
378 (false, false, false) => ParamKind::SharedRef,
379 (true, true, _) => ParamKind::MutValue,
380 (_, false, _) => ParamKind::Value,
384 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
385 let var = path_expr_from_local(ctx, self.var);
387 ParamKind::Value | ParamKind::MutValue => var,
388 ParamKind::SharedRef => make::expr_ref(var, false),
389 ParamKind::MutRef => make::expr_ref(var, true),
393 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
394 let var = self.var.name(ctx.db()).to_string();
395 let var_name = make::name(&var);
396 let pat = match self.kind() {
397 ParamKind::MutValue => make::ident_pat(false, true, var_name),
398 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
399 make::ext::simple_ident_pat(var_name)
403 let ty = make_ty(&self.ty, ctx, module);
404 let ty = match self.kind() {
405 ParamKind::Value | ParamKind::MutValue => ty,
406 ParamKind::SharedRef => make::ty_ref(ty, false),
407 ParamKind::MutRef => make::ty_ref(ty, true),
410 make::param(pat.into(), ty)
415 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
417 // We favour Result for `expr?`
418 return Some(TryKind::Result { ty });
420 let adt = ty.as_adt()?;
421 let name = adt.name(ctx.db());
422 // FIXME: use lang items to determine if it is std type or user defined
423 // E.g. if user happens to define type named `Option`, we would have false positive
424 match name.to_string().as_str() {
425 "Option" => Some(TryKind::Option),
426 "Result" => Some(TryKind::Result { ty }),
433 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
435 FlowKind::Return(_) => make::expr_return(expr),
436 FlowKind::Break(_) => make::expr_break(expr),
437 FlowKind::Try { .. } => {
438 stdx::never!("cannot have result handler with try");
439 expr.unwrap_or_else(|| make::expr_return(None))
441 FlowKind::Continue => {
442 stdx::always!(expr.is_none(), "continue with value is not possible");
443 make::expr_continue()
448 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
450 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
451 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
453 FlowKind::Try { .. } => {
454 stdx::never!("try does not have defined expr_ty");
463 fn parent(&self) -> Option<SyntaxNode> {
465 FunctionBody::Expr(expr) => expr.syntax().parent(),
466 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
470 fn from_expr(expr: ast::Expr) -> Option<Self> {
472 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
473 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
474 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
475 expr => Some(Self::Expr(expr)),
479 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
480 let full_body = parent.syntax().children_with_tokens();
482 let mut text_range = full_body
483 .filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
484 .map(|element| element.text_range())
485 .filter(|&range| selected.intersect(range).filter(|it| !it.is_empty()).is_some())
486 .reduce(|acc, stmt| acc.cover(stmt));
488 if let Some(tail_range) = parent
490 .map(|it| it.syntax().text_range())
491 .filter(|&it| selected.intersect(it).is_some())
493 text_range = Some(match text_range {
494 Some(text_range) => text_range.cover(tail_range),
498 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
501 fn indent_level(&self) -> IndentLevel {
503 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
504 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
508 fn tail_expr(&self) -> Option<ast::Expr> {
510 FunctionBody::Expr(expr) => Some(expr.clone()),
511 FunctionBody::Span { parent, text_range } => {
512 let tail_expr = parent.tail_expr()?;
513 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
518 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
520 FunctionBody::Expr(expr) => walk_expr(expr, cb),
521 FunctionBody::Span { parent, text_range } => {
524 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
525 .filter_map(|stmt| match stmt {
526 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
527 ast::Stmt::Item(_) => None,
528 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
530 .for_each(|expr| walk_expr(&expr, cb));
531 if let Some(expr) = parent
533 .filter(|it| text_range.contains_range(it.syntax().text_range()))
535 walk_expr(&expr, cb);
541 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
543 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
544 FunctionBody::Span { parent, text_range } => {
547 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
548 .filter_map(|stmt| match stmt {
549 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
550 ast::Stmt::Item(_) => None,
551 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
553 .for_each(|expr| preorder_expr(&expr, cb));
554 if let Some(expr) = parent
556 .filter(|it| text_range.contains_range(it.syntax().text_range()))
558 preorder_expr(&expr, cb);
564 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
566 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
567 FunctionBody::Span { parent, text_range } => {
570 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
571 .for_each(|stmt| match stmt {
572 ast::Stmt::ExprStmt(expr_stmt) => {
573 if let Some(expr) = expr_stmt.expr() {
574 walk_patterns_in_expr(&expr, cb)
577 ast::Stmt::Item(_) => (),
578 ast::Stmt::LetStmt(stmt) => {
579 if let Some(pat) = stmt.pat() {
582 if let Some(expr) = stmt.initializer() {
583 walk_patterns_in_expr(&expr, cb);
587 if let Some(expr) = parent
589 .filter(|it| text_range.contains_range(it.syntax().text_range()))
591 walk_patterns_in_expr(&expr, cb);
597 fn text_range(&self) -> TextRange {
599 FunctionBody::Expr(expr) => expr.syntax().text_range(),
600 &FunctionBody::Span { text_range, .. } => text_range,
604 fn contains_range(&self, range: TextRange) -> bool {
605 self.text_range().contains_range(range)
608 fn precedes_range(&self, range: TextRange) -> bool {
609 self.text_range().end() <= range.start()
612 fn contains_node(&self, node: &SyntaxNode) -> bool {
613 self.contains_range(node.text_range())
618 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
619 /// whether it contains an await expression.
622 sema: &Semantics<RootDatabase>,
623 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
624 let mut self_param = None;
625 let mut res = FxIndexSet::default();
626 let mut cb = |name_ref: Option<_>| {
628 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
630 NameRefClass::Definition(Definition::Local(local_ref))
631 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
635 let InFile { file_id, value } = local_ref.source(sema.db);
636 // locals defined inside macros are not relevant to us
637 if !file_id.is_macro() {
639 Either::Right(it) => {
640 self_param.replace(it);
643 res.insert(local_ref);
648 self.walk_expr(&mut |expr| match expr {
649 ast::Expr::PathExpr(path_expr) => {
650 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
652 ast::Expr::MacroCall(call) => {
653 if let Some(tt) = call.token_tree() {
655 .children_with_tokens()
656 .flat_map(SyntaxElement::into_token)
657 .filter(|it| it.kind() == SyntaxKind::IDENT)
658 .flat_map(|t| sema.descend_into_macros(t))
659 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
667 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
668 let mut ancestors = self.parent()?.ancestors();
669 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
670 let mut parent_loop = None;
671 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
674 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
676 parent_loop.get_or_insert(loop_.syntax().clone());
679 let (is_const, expr, ty) = loop {
680 let anc = ancestors.next()?;
683 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
684 ast::BlockExpr(block_expr) => {
685 let (constness, block) = match block_expr.modifier() {
686 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
687 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
688 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
691 let expr = Some(ast::Expr::BlockExpr(block));
692 (constness, expr.clone(), infer_expr_opt(expr))
695 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
697 ast::Static(statik) => {
698 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
700 ast::ConstArg(ca) => {
701 (true, ca.expr(), infer_expr_opt(ca.expr()))
703 ast::Const(konst) => {
704 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
706 ast::ConstParam(cp) => {
707 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
709 ast::ConstBlockPat(cbp) => {
710 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
711 (true, expr.clone(), infer_expr_opt(expr))
713 ast::Variant(__) => return None,
714 ast::Meta(__) => return None,
715 ast::LoopExpr(it) => {
716 set_parent_loop(&it);
719 ast::ForExpr(it) => {
720 set_parent_loop(&it);
723 ast::WhileExpr(it) => {
724 set_parent_loop(&it);
731 let container_tail = match expr? {
732 ast::Expr::BlockExpr(block) => block.tail_expr(),
736 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
737 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
739 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
742 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
743 match self.tail_expr() {
744 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
745 None => Some(RetType::Stmt),
749 /// Local variables defined inside `body` that are accessed outside of it
752 ctx: &'a AssistContext,
754 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
755 let parent = parent.clone();
756 let range = self.text_range();
757 locals_defined_in_body(&ctx.sema, self)
759 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
762 /// Analyses the function body for external control flow.
763 fn external_control_flow(
766 container_info: &ContainerInfo,
767 ) -> Option<ControlFlow> {
768 let mut ret_expr = None;
769 let mut try_expr = None;
770 let mut break_expr = None;
771 let mut continue_expr = None;
772 let mut is_async = false;
773 let mut _is_unsafe = false;
775 let mut unsafe_depth = 0;
776 let mut loop_depth = 0;
778 self.preorder_expr(&mut |expr| {
779 let expr = match expr {
780 WalkEvent::Enter(e) => e,
781 WalkEvent::Leave(expr) => {
783 ast::Expr::LoopExpr(_)
784 | ast::Expr::ForExpr(_)
785 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
786 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
795 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
798 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
801 ast::Expr::ReturnExpr(it) => {
804 ast::Expr::TryExpr(it) => {
807 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
808 break_expr = Some(it);
810 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
811 continue_expr = Some(it);
813 ast::Expr::AwaitExpr(_) => is_async = true,
814 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
815 // to just lift that out of there
816 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
822 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
823 (Some(_), _, None, None) => {
824 let ret_ty = container_info.ret_type.clone()?;
825 let kind = TryKind::of_ty(ret_ty, ctx)?;
827 Some(FlowKind::Try { kind })
829 (Some(_), _, _, _) => {
830 cov_mark::hit!(external_control_flow_try_and_bc);
833 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
834 (None, Some(_), _, _) => {
835 cov_mark::hit!(external_control_flow_return_and_bc);
838 (None, None, Some(_), Some(_)) => {
839 cov_mark::hit!(external_control_flow_break_and_continue);
842 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
843 (None, None, None, Some(_)) => Some(FlowKind::Continue),
844 (None, None, None, None) => None,
847 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
850 /// find variables that should be extracted as params
852 /// Computes additional info that affects param type and mutability
853 fn extracted_function_params(
856 container_info: &ContainerInfo,
857 locals: impl Iterator<Item = Local>,
860 .map(|local| (local, local.source(ctx.db())))
861 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
862 .filter_map(|(local, src)| match src.value {
863 Either::Left(src) => Some((local, src)),
864 Either::Right(_) => {
865 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
870 let usages = LocalUsages::find_local_usages(ctx, var);
871 let ty = var.ty(ctx.db());
873 let defined_outside_parent_loop = container_info
876 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
878 let is_copy = ty.is_copy(ctx.db());
879 let has_usages = self.has_usages_after_body(&usages);
881 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
882 // We can move the value into the function call if it's not used after the call,
883 // if the var is not used but defined outside a loop we are extracting from we can't move it either
884 // as the function will reuse it in the next iteration.
885 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
886 Param { var, ty, move_local, requires_mut, is_copy }
891 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
892 usages.iter().any(|reference| self.precedes_range(reference.range))
896 /// checks if relevant var is used with `&mut` access inside body
897 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
900 .filter(|reference| body.contains_range(reference.range))
901 .any(|reference| reference_is_exclusive(reference, body, ctx))
904 /// checks if this reference requires `&mut` access inside node
905 fn reference_is_exclusive(
906 reference: &FileReference,
907 node: &dyn HasTokenAtOffset,
910 // we directly modify variable with set: `n = 0`, `n += 1`
911 if reference.category == Some(ReferenceCategory::Write) {
915 // we take `&mut` reference to variable: `&mut v`
916 let path = match path_element_of_reference(node, reference) {
918 None => return false,
921 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
924 /// checks if this expr requires `&mut` access, recurses on field access
925 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
926 if let ast::Expr::MacroCall(_) = expr {
927 // FIXME: expand macro and check output for mutable usages of the variable?
931 let parent = expr.syntax().parent()?;
933 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
934 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
935 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
940 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
941 return Some(ref_expr.mut_token().is_some());
944 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
945 let func = ctx.sema.resolve_method_call(&method_call)?;
946 let self_param = func.self_param(ctx.db())?;
947 let access = self_param.access(ctx.db());
949 return Some(matches!(access, hir::Access::Exclusive));
952 if let Some(field) = ast::FieldExpr::cast(parent) {
953 return expr_require_exclusive_access(ctx, &field.into());
959 trait HasTokenAtOffset {
960 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
963 impl HasTokenAtOffset for SyntaxNode {
964 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
965 SyntaxNode::token_at_offset(self, offset)
969 impl HasTokenAtOffset for FunctionBody {
970 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
972 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
973 FunctionBody::Span { parent, text_range } => {
974 match parent.syntax().token_at_offset(offset) {
975 TokenAtOffset::None => TokenAtOffset::None,
976 TokenAtOffset::Single(t) => {
977 if text_range.contains_range(t.text_range()) {
978 TokenAtOffset::Single(t)
983 TokenAtOffset::Between(a, b) => {
985 text_range.contains_range(a.text_range()),
986 text_range.contains_range(b.text_range()),
988 (true, true) => TokenAtOffset::Between(a, b),
989 (true, false) => TokenAtOffset::Single(a),
990 (false, true) => TokenAtOffset::Single(b),
991 (false, false) => TokenAtOffset::None,
1000 /// find relevant `ast::Expr` for reference
1004 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1005 fn path_element_of_reference(
1006 node: &dyn HasTokenAtOffset,
1007 reference: &FileReference,
1008 ) -> Option<ast::Expr> {
1009 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1010 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1013 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1014 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1018 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1019 "unexpected expression type for variable usage: {:?}",
1025 /// list local variables defined inside `body`
1026 fn locals_defined_in_body(
1027 sema: &Semantics<RootDatabase>,
1028 body: &FunctionBody,
1029 ) -> FxIndexSet<Local> {
1030 // FIXME: this doesn't work well with macros
1031 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1032 let mut res = FxIndexSet::default();
1033 body.walk_pat(&mut |pat| {
1034 if let ast::Pat::IdentPat(pat) = pat {
1035 if let Some(local) = sema.to_def(&pat) {
1043 /// Returns usage details if local variable is used after(outside of) body
1044 fn local_outlives_body(
1045 ctx: &AssistContext,
1046 body_range: TextRange,
1048 parent: &SyntaxNode,
1049 ) -> Option<OutlivedLocal> {
1050 let usages = LocalUsages::find_local_usages(ctx, local);
1051 let mut has_mut_usages = false;
1052 let mut any_outlives = false;
1053 for usage in usages.iter() {
1054 if body_range.end() <= usage.range.start() {
1055 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1056 any_outlives |= true;
1058 break; // no need to check more elements we have all the info we wanted
1065 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1068 /// checks if the relevant local was defined before(outside of) body
1069 fn is_defined_outside_of_body(
1070 ctx: &AssistContext,
1071 body: &FunctionBody,
1072 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1074 src.file_id.original_file(ctx.db()) == ctx.file_id()
1075 && !body.contains_node(either_syntax(&src.value))
1078 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1080 Either::Left(pat) => pat.syntax(),
1081 Either::Right(it) => it.syntax(),
1085 /// find where to put extracted function definition
1087 /// Function should be put right after returned node
1088 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1089 let node = match body {
1090 FunctionBody::Expr(e) => e.syntax(),
1091 FunctionBody::Span { parent, .. } => parent.syntax(),
1093 let mut ancestors = node.ancestors().peekable();
1094 let mut last_ancestor = None;
1095 while let Some(next_ancestor) = ancestors.next() {
1096 match next_ancestor.kind() {
1097 SyntaxKind::SOURCE_FILE => break,
1098 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1099 SyntaxKind::ITEM_LIST => {
1100 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1104 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1107 SyntaxKind::ASSOC_ITEM_LIST => {
1108 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1114 last_ancestor = Some(next_ancestor);
1119 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1120 let ret_ty = fun.return_type(ctx);
1122 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1123 let name = fun.name.clone();
1124 let mut call_expr = if fun.self_param.is_some() {
1125 let self_arg = make::expr_path(make::ext::ident_path("self"));
1126 make::expr_method_call(self_arg, name, args)
1128 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1129 make::expr_call(func, args)
1132 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1134 if fun.control_flow.is_async {
1135 call_expr = make::expr_await(call_expr);
1137 let expr = handler.make_call_expr(call_expr).indent(indent);
1139 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1141 let mut buf = String::new();
1142 match fun.outliving_locals.as_slice() {
1145 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()))
1148 buf.push_str("let (");
1149 let bindings = vars.iter().format_with(", ", |local, f| {
1150 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db())))
1152 format_to!(buf, "{}", bindings);
1153 buf.push_str(") = ");
1157 format_to!(buf, "{}", expr);
1158 let insert_comma = fun
1161 .and_then(ast::MatchArm::cast)
1162 .map_or(false, |it| it.comma_token().is_none());
1165 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1173 Try { kind: TryKind },
1174 If { action: FlowKind },
1175 IfOption { action: FlowKind },
1176 MatchOption { none: FlowKind },
1177 MatchResult { err: FlowKind },
1181 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1182 match &fun.control_flow.kind {
1183 None => FlowHandler::None,
1184 Some(flow_kind) => {
1185 let action = flow_kind.clone();
1186 if *ret_ty == FunType::Unit {
1188 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1189 FlowHandler::If { action }
1191 FlowKind::Return(_) | FlowKind::Break(_) => {
1192 FlowHandler::IfOption { action }
1194 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1198 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1199 FlowHandler::MatchOption { none: action }
1201 FlowKind::Return(_) | FlowKind::Break(_) => {
1202 FlowHandler::MatchResult { err: action }
1204 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1211 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1213 FlowHandler::None => call_expr,
1214 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1215 FlowHandler::If { action } => {
1216 let action = action.make_result_handler(None);
1217 let stmt = make::expr_stmt(action);
1218 let block = make::block_expr(iter::once(stmt.into()), None);
1219 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1220 let condition = make::expr_let(
1221 make::tuple_struct_pat(
1222 controlflow_break_path,
1223 iter::once(make::wildcard_pat().into()),
1228 make::expr_if(condition.into(), block, None)
1230 FlowHandler::IfOption { action } => {
1231 let path = make::ext::ident_path("Some");
1232 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1233 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1234 let cond = make::expr_let(pattern.into(), call_expr);
1235 let value = make::expr_path(make::ext::ident_path("value"));
1236 let action_expr = action.make_result_handler(Some(value));
1237 let action_stmt = make::expr_stmt(action_expr);
1238 let then = make::block_expr(iter::once(action_stmt.into()), None);
1239 make::expr_if(cond.into(), then, None)
1241 FlowHandler::MatchOption { none } => {
1242 let some_name = "value";
1245 let path = make::ext::ident_path("Some");
1246 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1247 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1248 let value = make::expr_path(make::ext::ident_path(some_name));
1249 make::match_arm(iter::once(pat.into()), None, value)
1252 let path = make::ext::ident_path("None");
1253 let pat = make::path_pat(path);
1254 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1256 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1257 make::expr_match(call_expr, arms)
1259 FlowHandler::MatchResult { err } => {
1260 let ok_name = "value";
1261 let err_name = "value";
1264 let path = make::ext::ident_path("Ok");
1265 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1266 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1267 let value = make::expr_path(make::ext::ident_path(ok_name));
1268 make::match_arm(iter::once(pat.into()), None, value)
1271 let path = make::ext::ident_path("Err");
1272 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1273 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1274 let value = make::expr_path(make::ext::ident_path(err_name));
1276 iter::once(pat.into()),
1278 err.make_result_handler(Some(value)),
1281 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1282 make::expr_match(call_expr, arms)
1288 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1289 let name = var.name(ctx.db()).to_string();
1290 make::expr_path(make::ext::ident_path(&name))
1294 ctx: &AssistContext,
1295 module: hir::Module,
1297 old_indent: IndentLevel,
1298 new_indent: IndentLevel,
1300 let mut fn_def = String::new();
1301 let params = fun.make_param_list(ctx, module);
1302 let ret_ty = fun.make_ret_ty(ctx, module);
1303 let body = make_body(ctx, old_indent, new_indent, fun);
1304 let const_kw = if fun.mods.is_const { "const " } else { "" };
1305 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1306 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1307 match ctx.config.snippet_cap {
1308 Some(_) => format_to!(
1310 "\n\n{}{}{}{}fn $0{}{}",
1320 "\n\n{}{}{}{}fn {}{}",
1329 if let Some(ret_ty) = ret_ty {
1330 format_to!(fn_def, " {}", ret_ty);
1332 format_to!(fn_def, " {}", body);
1338 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1339 let self_param = self.self_param.clone();
1340 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1341 make::param_list(self_param, params)
1344 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1345 let fun_ty = self.return_type(ctx);
1346 let handler = if self.mods.is_in_tail {
1349 FlowHandler::from_ret_ty(self, &fun_ty)
1351 let ret_ty = match &handler {
1352 FlowHandler::None => {
1353 if matches!(fun_ty, FunType::Unit) {
1356 fun_ty.make_ty(ctx, module)
1358 FlowHandler::Try { kind: TryKind::Option } => {
1359 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1361 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1362 let handler_ty = parent_ret_ty
1365 .map(|ty| make_ty(&ty, ctx, module))
1366 .unwrap_or_else(make::ty_placeholder);
1367 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1369 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1370 FlowHandler::IfOption { action } => {
1371 let handler_ty = action
1373 .map(|ty| make_ty(&ty, ctx, module))
1374 .unwrap_or_else(make::ty_placeholder);
1375 make::ext::ty_option(handler_ty)
1377 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1378 FlowHandler::MatchResult { err } => {
1379 let handler_ty = err
1381 .map(|ty| make_ty(&ty, ctx, module))
1382 .unwrap_or_else(make::ty_placeholder);
1383 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1386 Some(make::ret_type(ret_ty))
1391 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1393 FunType::Unit => make::ty_unit(),
1394 FunType::Single(ty) => make_ty(ty, ctx, module),
1395 FunType::Tuple(types) => match types.as_slice() {
1397 stdx::never!("tuple type with 0 elements");
1401 stdx::never!("tuple type with 1 element");
1402 make_ty(ty, ctx, module)
1405 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1406 make::ty_tuple(types)
1414 ctx: &AssistContext,
1415 old_indent: IndentLevel,
1416 new_indent: IndentLevel,
1418 ) -> ast::BlockExpr {
1419 let ret_ty = fun.return_type(ctx);
1420 let handler = if fun.mods.is_in_tail {
1423 FlowHandler::from_ret_ty(fun, &ret_ty)
1426 let block = match &fun.body {
1427 FunctionBody::Expr(expr) => {
1428 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1429 let expr = ast::Expr::cast(expr).unwrap();
1431 ast::Expr::BlockExpr(block) => {
1432 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1433 let block = block.dedent(old_indent);
1434 // Recreate the block for formatting consistency with other extracted functions.
1435 make::block_expr(block.statements(), block.tail_expr())
1438 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1440 make::block_expr(Vec::new(), Some(expr))
1444 FunctionBody::Span { parent, text_range } => {
1445 let mut elements: Vec<_> = parent
1447 .children_with_tokens()
1448 .filter(|it| text_range.contains_range(it.text_range()))
1449 .map(|it| match &it {
1450 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1451 rewrite_body_segment(ctx, &fun.params, &handler, &n),
1457 let mut tail_expr = match &elements.last() {
1458 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1459 ast::Expr::cast(node.clone())
1468 None => match fun.outliving_locals.as_slice() {
1471 tail_expr = Some(path_expr_from_local(ctx, var.local));
1474 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1475 let expr = make::expr_tuple(exprs);
1476 tail_expr = Some(expr);
1481 let body_indent = IndentLevel(1);
1482 let elements = elements
1484 .map(|node_or_token| match &node_or_token {
1485 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1487 let indented = stmt.dedent(old_indent).indent(body_indent);
1488 let ast_node = indented.syntax().clone_subtree();
1489 syntax::NodeOrToken::Node(ast_node)
1495 .collect::<Vec<SyntaxElement>>();
1496 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1498 make::hacky_block_expr_with_comments(elements, tail_expr)
1502 let block = match &handler {
1503 FlowHandler::None => block,
1504 FlowHandler::Try { kind } => {
1505 let block = with_default_tail_expr(block, make::expr_unit());
1506 map_tail_expr(block, |tail_expr| {
1507 let constructor = match kind {
1508 TryKind::Option => "Some",
1509 TryKind::Result { .. } => "Ok",
1511 let func = make::expr_path(make::ext::ident_path(constructor));
1512 let args = make::arg_list(iter::once(tail_expr));
1513 make::expr_call(func, args)
1516 FlowHandler::If { .. } => {
1517 let controlflow_continue = make::expr_call(
1518 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1519 make::arg_list(iter::once(make::expr_unit())),
1521 with_tail_expr(block, controlflow_continue.into())
1523 FlowHandler::IfOption { .. } => {
1524 let none = make::expr_path(make::ext::ident_path("None"));
1525 with_tail_expr(block, none)
1527 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1528 let some = make::expr_path(make::ext::ident_path("Some"));
1529 let args = make::arg_list(iter::once(tail_expr));
1530 make::expr_call(some, args)
1532 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1533 let ok = make::expr_path(make::ext::ident_path("Ok"));
1534 let args = make::arg_list(iter::once(tail_expr));
1535 make::expr_call(ok, args)
1539 block.indent(new_indent)
1542 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1543 let tail_expr = match block.tail_expr() {
1544 Some(tail_expr) => tail_expr,
1545 None => return block,
1547 make::block_expr(block.statements(), Some(f(tail_expr)))
1550 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1551 match block.tail_expr() {
1553 None => make::block_expr(block.statements(), Some(tail_expr)),
1557 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1558 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1559 let stmts = block.statements().chain(stmt_tail);
1560 make::block_expr(stmts, Some(tail_expr))
1563 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1564 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1567 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1568 let ty_str = format_type(ty, ctx, module);
1572 fn rewrite_body_segment(
1573 ctx: &AssistContext,
1575 handler: &FlowHandler,
1576 syntax: &SyntaxNode,
1578 let syntax = fix_param_usages(ctx, params, syntax);
1579 update_external_control_flow(handler, &syntax);
1583 /// change all usages to account for added `&`/`&mut` for some params
1584 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1585 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1587 let tm = TreeMutator::new(syntax);
1589 for param in params {
1590 if !param.kind().is_ref() {
1594 let usages = LocalUsages::find_local_usages(ctx, param.var);
1597 .filter(|reference| syntax.text_range().contains_range(reference.range))
1598 .filter_map(|reference| path_element_of_reference(syntax, reference))
1599 .map(|expr| tm.make_mut(&expr));
1601 usages_for_param.push((param, usages.collect()));
1604 let res = tm.make_syntax_mut(syntax);
1606 for (param, usages) in usages_for_param {
1607 for usage in usages {
1608 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1609 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1612 Some(ast::Expr::RefExpr(node))
1613 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1615 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1617 Some(ast::Expr::RefExpr(node))
1618 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1620 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1623 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1624 ted::replace(usage.syntax(), p.syntax())
1633 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1634 let mut nested_loop = None;
1635 let mut nested_scope = None;
1636 for event in syntax.preorder() {
1638 WalkEvent::Enter(e) => match e.kind() {
1639 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1640 if nested_loop.is_none() {
1641 nested_loop = Some(e.clone());
1646 | SyntaxKind::STATIC
1648 | SyntaxKind::MODULE => {
1649 if nested_scope.is_none() {
1650 nested_scope = Some(e.clone());
1655 WalkEvent::Leave(e) => {
1656 if nested_scope.is_none() {
1657 if let Some(expr) = ast::Expr::cast(e.clone()) {
1659 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1660 let expr = return_expr.expr();
1661 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1662 ted::replace(return_expr.syntax(), replacement.syntax())
1665 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1666 let expr = break_expr.expr();
1667 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1668 ted::replace(break_expr.syntax(), replacement.syntax())
1671 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1672 if let Some(replacement) = make_rewritten_flow(handler, None) {
1673 ted::replace(continue_expr.syntax(), replacement.syntax())
1683 if nested_loop.as_ref() == Some(&e) {
1686 if nested_scope.as_ref() == Some(&e) {
1687 nested_scope = None;
1694 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1695 let value = match handler {
1696 FlowHandler::None | FlowHandler::Try { .. } => return None,
1697 FlowHandler::If { .. } => make::expr_call(
1698 make::expr_path(make::path_from_text("ControlFlow::Break")),
1699 make::arg_list(iter::once(make::expr_unit())),
1701 FlowHandler::IfOption { .. } => {
1702 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1703 let args = make::arg_list(iter::once(expr));
1704 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1706 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1707 FlowHandler::MatchResult { .. } => {
1708 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1709 let args = make::arg_list(iter::once(expr));
1710 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1713 Some(make::expr_return(Some(value)).clone_for_update())
1718 use crate::tests::{check_assist, check_assist_not_applicable};
1723 fn no_args_from_binary_expr() {
1736 fn $0fun_name() -> i32 {
1744 fn no_args_from_binary_expr_in_module() {
1760 fn $0fun_name() -> i32 {
1769 fn no_args_from_binary_expr_indented() {
1782 fn $0fun_name() -> i32 {
1790 fn no_args_from_stmt_with_last_expr() {
1806 fn $0fun_name() -> i32 {
1815 fn no_args_from_stmt_unit() {
1863 fn no_args_if_else() {
1868 $0if true { 1 } else { 2 }$0
1876 fn $0fun_name() -> i32 {
1877 if true { 1 } else { 2 }
1884 fn no_args_if_let_else() {
1889 $0if let true = false { 1 } else { 2 }$0
1897 fn $0fun_name() -> i32 {
1898 if let true = false { 1 } else { 2 }
1905 fn no_args_match() {
1921 fn $0fun_name() -> i32 {
1932 fn no_args_while() {
1958 $0for v in &[0, 1] { }$0
1967 for v in &[0, 1] { }
1974 fn no_args_from_loop_unit() {
1989 fn $0fun_name() -> ! {
1999 fn no_args_from_loop_with_return() {
2015 fn $0fun_name() -> i32 {
2026 fn no_args_from_match() {
2031 let v: i32 = $0match Some(1) {
2039 let v: i32 = fun_name();
2042 fn $0fun_name() -> i32 {
2053 fn extract_partial_block_single_line() {
2059 let mut v = $0n * n;$0
2066 let mut v = fun_name(n);
2070 fn $0fun_name(n: i32) -> i32 {
2079 fn extract_partial_block() {
2086 let mut v = m $0* n;
2096 let (mut v, mut w) = fun_name(m, n);
2101 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2111 fn argument_form_expr() {
2126 fn $0fun_name(n: u32) -> u32 {
2134 fn argument_used_twice_form_expr() {
2149 fn $0fun_name(n: u32) -> u32 {
2157 fn two_arguments_form_expr() {
2174 fn $0fun_name(n: u32, m: u32) -> u32 {
2182 fn argument_and_locals() {
2198 fn $0fun_name(n: u32) -> u32 {
2207 fn in_comment_is_not_applicable() {
2208 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2209 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2213 fn part_of_expr_stmt() {
2226 fn $0fun_name() -> i32 {
2234 fn function_expr() {
2255 fn extract_from_nested() {
2261 let tuple = match x {
2262 true => ($02 + 2$0, true)
2270 let tuple = match x {
2271 true => (fun_name(), true)
2276 fn $0fun_name() -> i32 {
2284 fn param_from_closure() {
2289 let lambda = |x: u32| $0x * 2$0;
2294 let lambda = |x: u32| fun_name(x);
2297 fn $0fun_name(x: u32) -> u32 {
2305 fn extract_return_stmt() {
2318 fn $0fun_name() -> u32 {
2326 fn does_not_add_extra_whitespace() {
2343 fn $0fun_name() -> u32 {
2368 fn $0fun_name() -> i32 {
2381 let v = $00f32 as u32$0;
2389 fn $0fun_name() -> u32 {
2397 fn return_not_applicable() {
2398 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2402 fn method_to_freestanding() {
2409 fn foo(&self) -> i32 {
2418 fn foo(&self) -> i32 {
2423 fn $0fun_name() -> i32 {
2431 fn method_with_reference() {
2435 struct S { f: i32 };
2438 fn foo(&self) -> i32 {
2444 struct S { f: i32 };
2447 fn foo(&self) -> i32 {
2451 fn $0fun_name(&self) -> i32 {
2460 fn method_with_mut() {
2464 struct S { f: i32 };
2473 struct S { f: i32 };
2480 fn $0fun_name(&mut self) {
2489 fn variable_defined_inside_and_used_after_no_ret() {
2502 let k = fun_name(n);
2506 fn $0fun_name(n: i32) -> i32 {
2515 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2521 $0let mut k = n * n;$0
2528 let mut k = fun_name(n);
2532 fn $0fun_name(n: i32) -> i32 {
2541 fn two_variables_defined_inside_and_used_after_no_ret() {
2555 let (k, m) = fun_name(n);
2559 fn $0fun_name(n: i32) -> (i32, i32) {
2569 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2575 $0let mut k = n * n;
2586 let (mut k, mut m, o) = fun_name(n);
2591 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2603 fn nontrivial_patterns_define_variables() {
2607 struct Counter(i32);
2609 $0let Counter(n) = Counter(0);$0
2614 struct Counter(i32);
2620 fn $0fun_name() -> i32 {
2621 let Counter(n) = Counter(0);
2629 fn struct_with_two_fields_pattern_define_variables() {
2633 struct Counter { n: i32, m: i32 };
2635 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2640 struct Counter { n: i32, m: i32 };
2642 let (n, k) = fun_name();
2646 fn $0fun_name() -> (i32, i32) {
2647 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2655 fn mut_var_from_outer_scope() {
2672 fn $0fun_name(n: &mut i32) {
2680 fn mut_field_from_outer_scope() {
2686 let mut c = C { n: 0 };
2694 let mut c = C { n: 0 };
2699 fn $0fun_name(c: &mut C) {
2707 fn mut_nested_field_from_outer_scope() {
2714 let mut c = C { p: P { n: 0 } };
2715 let mut v = C { p: P { n: 0 } };
2716 let u = C { p: P { n: 0 } };
2718 let r = &mut v.p.n;$0
2719 let m = c.p.n + v.p.n + u.p.n;
2726 let mut c = C { p: P { n: 0 } };
2727 let mut v = C { p: P { n: 0 } };
2728 let u = C { p: P { n: 0 } };
2729 fun_name(&mut c, &u, &mut v);
2730 let m = c.p.n + v.p.n + u.p.n;
2733 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2742 fn mut_param_many_usages_stmt() {
2748 fn succ(&self) -> Self;
2749 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2752 fn succ(&self) -> Self { *self + 1 }
2771 fn succ(&self) -> Self;
2772 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2775 fn succ(&self) -> Self { *self + 1 }
2783 fn $0fun_name(n: &mut i32) {
2799 fn mut_param_many_usages_expr() {
2805 fn succ(&self) -> Self;
2806 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2809 fn succ(&self) -> Self { *self + 1 }
2830 fn succ(&self) -> Self;
2831 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2834 fn succ(&self) -> Self { *self + 1 }
2842 fn $0fun_name(n: &mut i32) {
2858 fn mut_param_by_value() {
2873 fn $0fun_name(mut n: i32) {
2881 fn mut_param_because_of_mut_ref() {
2899 fn $0fun_name(n: &mut i32) {
2908 fn mut_param_by_value_because_of_mut_ref() {
2924 fn $0fun_name(mut n: i32) {
2933 fn mut_method_call() {
2941 fn inc(&mut self) { *self += 1 }
2953 fn inc(&mut self) { *self += 1 }
2960 fn $0fun_name(mut n: i32) {
2968 fn shared_method_call() {
2976 fn succ(&self) { *self + 1 }
2988 fn succ(&self) { *self + 1 }
2995 fn $0fun_name(n: i32) {
3003 fn mut_method_call_with_other_receiver() {
3008 fn inc(&mut self, n: i32);
3011 fn inc(&mut self, n: i32) { *self += n }
3021 fn inc(&mut self, n: i32);
3024 fn inc(&mut self, n: i32) { *self += n }
3031 fn $0fun_name(n: i32) {
3040 fn non_copy_without_usages_after() {
3044 struct Counter(i32);
3051 struct Counter(i32);
3057 fn $0fun_name(c: Counter) {
3065 fn non_copy_used_after() {
3069 struct Counter(i32);
3077 struct Counter(i32);
3084 fn $0fun_name(c: &Counter) {
3092 fn copy_used_after() {
3110 fn $0fun_name(n: i32) {
3118 fn copy_custom_used_after() {
3122 //- minicore: copy, derive
3123 #[derive(Clone, Copy)]
3124 struct Counter(i32);
3132 #[derive(Clone, Copy)]
3133 struct Counter(i32);
3140 fn $0fun_name(c: Counter) {
3148 fn indented_stmts() {
3179 fn indented_stmts_inside_mod() {
3218 //- minicore: option
3233 let k = match fun_name(n) {
3234 Some(value) => value,
3241 fn $0fun_name(n: i32) -> Option<i32> {
3252 fn return_to_parent() {
3256 //- minicore: copy, result
3268 let k = match fun_name(n) {
3270 Err(value) => return value,
3275 fn $0fun_name(n: i32) -> Result<i32, i64> {
3286 fn break_and_continue() {
3287 cov_mark::check!(external_control_flow_break_and_continue);
3288 check_assist_not_applicable(
3307 fn return_and_break() {
3308 cov_mark::check!(external_control_flow_return_and_bc);
3309 check_assist_not_applicable(
3328 fn break_loop_with_if() {
3344 use core::ops::ControlFlow;
3349 if let ControlFlow::Break(_) = fun_name(&mut n) {
3356 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3358 return ControlFlow::Break(());
3360 ControlFlow::Continue(())
3367 fn break_loop_nested() {
3384 use core::ops::ControlFlow;
3389 if let ControlFlow::Break(_) = fun_name(n) {
3396 fn $0fun_name(n: i32) -> ControlFlow<()> {
3399 return ControlFlow::Break(());
3401 ControlFlow::Continue(())
3408 fn return_from_nested_loop() {
3428 let m = match fun_name() {
3429 Some(value) => value,
3436 fn $0fun_name() -> Option<i32> {
3449 fn break_from_nested_loop() {
3474 fn $0fun_name() -> i32 {
3487 fn break_from_nested_and_outer_loops() {
3510 let m = match fun_name() {
3511 Some(value) => value,
3518 fn $0fun_name() -> Option<i32> {
3534 fn return_from_nested_fn() {
3559 fn $0fun_name() -> i32 {
3572 fn break_with_value() {
3592 if let Some(value) = fun_name() {
3599 fn $0fun_name() -> Option<i32> {
3612 fn break_with_value_and_return() {
3632 let m = match fun_name() {
3634 Err(value) => break value,
3640 fn $0fun_name() -> Result<i32, i64> {
3657 //- minicore: option
3658 fn bar() -> Option<i32> { None }
3659 fn foo() -> Option<()> {
3668 fn bar() -> Option<i32> { None }
3669 fn foo() -> Option<()> {
3671 let m = fun_name()?;
3676 fn $0fun_name() -> Option<i32> {
3686 fn try_option_unit() {
3690 //- minicore: option
3691 fn foo() -> Option<()> {
3700 fn foo() -> Option<()> {
3707 fn $0fun_name() -> Option<()> {
3721 //- minicore: result
3722 fn foo() -> Result<(), i64> {
3731 fn foo() -> Result<(), i64> {
3733 let m = fun_name()?;
3738 fn $0fun_name() -> Result<i32, i64> {
3748 fn try_option_with_return() {
3752 //- minicore: option
3753 fn foo() -> Option<()> {
3765 fn foo() -> Option<()> {
3767 let m = fun_name()?;
3772 fn $0fun_name() -> Option<i32> {
3785 fn try_result_with_return() {
3789 //- minicore: result
3790 fn foo() -> Result<(), i64> {
3802 fn foo() -> Result<(), i64> {
3804 let m = fun_name()?;
3809 fn $0fun_name() -> Result<i32, i64> {
3822 fn try_and_break() {
3823 cov_mark::check!(external_control_flow_try_and_bc);
3824 check_assist_not_applicable(
3827 //- minicore: option
3828 fn foo() -> Option<()> {
3844 fn try_and_return_ok() {
3848 //- minicore: result
3849 fn foo() -> Result<(), i64> {
3861 fn foo() -> Result<(), i64> {
3863 let m = fun_name()?;
3868 fn $0fun_name() -> Result<i32, i64> {
3881 fn param_usage_in_macro() {
3886 ($val:expr) => { $val };
3891 $0let k = n * m!(n);$0
3897 ($val:expr) => { $val };
3902 let k = fun_name(n);
3906 fn $0fun_name(n: i32) -> i32 {
3915 fn extract_with_await() {
3920 $0some_function().await;$0
3923 async fn some_function() {
3932 async fn $0fun_name() {
3933 some_function().await;
3936 async fn some_function() {
3944 fn extract_with_await_and_result_not_producing_match_expr() {
3948 async fn foo() -> Result<(), ()> {
3954 async fn foo() -> Result<(), ()> {
3958 async fn $0fun_name() -> _ {
3967 fn extract_with_await_and_result_producing_match_expr() {
3971 async fn foo() -> i32 {
3974 let k = async { 1 }.await;
3984 async fn foo() -> i32 {
3987 let m = match fun_name().await {
3989 Err(value) => break value,
3995 async fn $0fun_name() -> Result<i32, i32> {
3996 let k = async { 1 }.await;
4008 fn extract_with_await_in_args() {
4013 $0function_call("a", some_function().await);$0
4016 async fn some_function() {
4025 async fn $0fun_name() {
4026 function_call("a", some_function().await);
4029 async fn some_function() {
4037 fn extract_does_not_extract_standalone_blocks() {
4038 check_assist_not_applicable(
4047 fn extract_adds_comma_for_match_arm() {
4066 fn $0fun_name() -> i32 {
4089 fn $0fun_name() -> i32 {
4097 fn extract_does_not_tear_comments_apart() {
4124 fn extract_does_not_tear_body_apart() {
4145 fn extract_does_not_wrap_res_in_res() {
4149 //- minicore: result
4150 fn foo() -> Result<(), i64> {
4151 $0Result::<i32, i64>::Ok(0)?;
4156 fn foo() -> Result<(), i64> {
4160 fn $0fun_name() -> Result<(), i64> {
4161 Result::<i32, i64>::Ok(0)?;
4169 fn extract_knows_const() {
4182 const fn $0fun_name() {
4199 const fn $0fun_name() {
4207 fn extract_does_not_move_outer_loop_vars() {
4226 fn $0fun_name(x: &mut i32) {
4249 fn $0fun_name(mut x: i32) {
4276 fn $0fun_name(x: &mut i32) {
4283 // regression test for #9822
4285 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4291 fn foo(&mut self) {}
4305 fn foo(&mut self) {}
4316 fn $0fun_name(y: &mut Foo) {
4324 fn extract_with_macro_arg() {
4329 ($val:expr) => { $val };
4338 ($val:expr) => { $val };
4345 fn $0fun_name(bar: &str) {
4353 fn unresolveable_types_default_to_placeholder() {
4358 let a = __unresolved;
4364 let a = __unresolved;
4365 let _ = fun_name(a);
4368 fn $0fun_name(a: _) -> _ {
4376 fn reference_mutable_param_with_further_usages() {
4384 pub fn testfn(arg: &mut Foo) {
4386 // Simulating access after the extracted portion
4395 pub fn testfn(arg: &mut Foo) {
4397 // Simulating access after the extracted portion
4401 fn $0fun_name(arg: &mut Foo) {
4409 fn reference_mutable_param_without_further_usages() {
4417 pub fn testfn(arg: &mut Foo) {
4426 pub fn testfn(arg: &mut Foo) {
4430 fn $0fun_name(arg: &mut Foo) {
4438 fn extract_function_copies_comment_at_start() {
4463 fn extract_function_copies_comment_in_between() {
4490 fn extract_function_copies_comment_at_end() {
4515 fn extract_function_copies_comment_indented() {
4543 // FIXME: we do want to preserve whitespace
4545 fn extract_function_does_not_preserve_whitespace() {
4571 fn extract_function_long_form_comment() {