1 use std::{hash::BuildHasherDefault, iter};
5 use hir::{HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
9 insert_use::{insert_use, ImportScope},
14 node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
16 search::{FileReference, ReferenceCategory, SearchScope},
19 use itertools::Itertools;
20 use rustc_hash::FxHasher;
25 edit::{AstNodeEdit, IndentLevel},
28 match_ast, ted, SyntaxElement,
29 SyntaxKind::{self, COMMENT},
30 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
34 assist_context::{AssistContext, Assists, TreeMutator},
38 type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>;
40 // Assist: extract_function
42 // Extracts selected statements into new function.
60 // fn $0fun_name(n: i32) {
65 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
66 let range = ctx.selection_trimmed();
71 let node = ctx.covering_element();
72 if node.kind() == COMMENT {
73 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
77 let node = match node {
78 syntax::NodeOrToken::Node(n) => n,
79 syntax::NodeOrToken::Token(t) => t.parent()?,
81 let body = extraction_target(&node, range)?;
82 let container_info = body.analyze_container(&ctx.sema)?;
84 let (locals_used, self_param) = body.analyze(&ctx.sema);
86 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
87 let insert_after = node_to_insert_after(&body, anchor)?;
88 let module = ctx.sema.scope(&insert_after).module()?;
90 let ret_ty = body.return_ty(ctx)?;
91 let control_flow = body.external_control_flow(ctx, &container_info)?;
92 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
94 let target_range = body.text_range();
96 let scope = ImportScope::find_insert_use_container_with_macros(&node, &ctx.sema)?;
99 AssistId("extract_function", crate::AssistKind::RefactorExtract),
100 "Extract into function",
103 let outliving_locals: Vec<_> = ret_values.collect();
104 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
105 // We should not have variables that outlive body if we have expression block
110 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
113 name: make::name_ref("fun_name"),
120 mods: container_info,
123 let new_indent = IndentLevel::from_node(&insert_after);
124 let old_indent = fun.body.indent_level();
126 builder.replace(target_range, make_call(ctx, &fun, old_indent));
128 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
129 let insert_offset = insert_after.text_range().end();
131 if fn_def.contains("ControlFlow") {
132 let scope = match scope {
133 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
134 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
135 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
138 let control_flow_enum =
139 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
141 if let Some(control_flow_enum) = control_flow_enum {
142 let mod_path = module.find_use_path_prefixed(
144 ModuleDef::from(control_flow_enum),
145 ctx.config.insert_use.prefix_kind,
148 if let Some(mod_path) = mod_path {
149 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
154 match ctx.config.snippet_cap {
155 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
156 None => builder.insert(insert_offset, fn_def),
162 /// Try to guess what user wants to extract
164 /// We have basically have two cases:
165 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
166 /// Then we can use `ast::Expr`
167 /// * We want a few statements for a block. E.g.
169 /// fn foo() -> i32 {
179 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
180 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
182 ast::Stmt::Item(_) => None,
183 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
184 node.parent().and_then(ast::StmtList::cast)?,
190 // Covering element returned the parent block of one or multiple statements that have been selected
191 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
192 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
193 if block_expr.syntax().text_range() == selection_range {
194 return FunctionBody::from_expr(block_expr.into());
198 // Extract the full statements.
199 return Some(FunctionBody::from_range(stmt_list, selection_range));
202 let expr = ast::Expr::cast(node.clone())?;
203 // A node got selected fully
204 if node.text_range() == selection_range {
205 return FunctionBody::from_expr(expr);
208 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
214 self_param: Option<ast::SelfParam>,
216 control_flow: ControlFlow,
219 outliving_locals: Vec<OutlivedLocal>,
232 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
240 #[derive(Debug, Eq, PartialEq)]
244 Tuple(Vec<hir::Type>),
247 /// Where to put extracted function definition
250 /// Extract free function and put right after current top-level function
252 /// Extract method and put right after current function in the impl-block
256 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
257 // probably be merged somehow.
260 kind: Option<FlowKind>,
265 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
266 #[derive(Clone, Debug)]
267 struct ContainerInfo {
270 parent_loop: Option<SyntaxNode>,
271 /// The function's return type, const's type etc.
272 ret_type: Option<hir::Type>,
275 /// Control flow that is exported from extracted function
287 #[derive(Debug, Clone)]
289 /// Return with value (`return $expr;`)
290 Return(Option<ast::Expr>),
294 /// Break with value (`break $expr;`)
295 Break(Option<ast::Expr>),
300 #[derive(Debug, Clone)]
303 Result { ty: hir::Type },
313 fn is_unit(&self) -> bool {
315 RetType::Expr(ty) => ty.is_unit(),
316 RetType::Stmt => true,
321 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
322 /// This is the future function body, the part that is being extracted.
326 Span { parent: ast::StmtList, text_range: TextRange },
330 struct OutlivedLocal {
332 mut_usage_outside_body: bool,
335 /// Container of local variable usages
337 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
338 struct LocalUsages(ide_db::search::UsageSearchResult);
341 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
343 Definition::Local(var)
345 .in_scope(SearchScope::single_file(ctx.frange.file_id))
350 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
351 self.0.iter().flat_map(|(_, rs)| rs)
356 fn return_type(&self, ctx: &AssistContext) -> FunType {
358 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
359 RetType::Expr(ty) => FunType::Single(ty.clone()),
360 RetType::Stmt => match self.outliving_locals.as_slice() {
362 [var] => FunType::Single(var.local.ty(ctx.db())),
364 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
365 FunType::Tuple(types)
373 fn is_ref(&self) -> bool {
374 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
379 fn kind(&self) -> ParamKind {
380 match (self.move_local, self.requires_mut, self.is_copy) {
381 (false, true, _) => ParamKind::MutRef,
382 (false, false, false) => ParamKind::SharedRef,
383 (true, true, _) => ParamKind::MutValue,
384 (_, false, _) => ParamKind::Value,
388 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
389 let var = path_expr_from_local(ctx, self.var);
391 ParamKind::Value | ParamKind::MutValue => var,
392 ParamKind::SharedRef => make::expr_ref(var, false),
393 ParamKind::MutRef => make::expr_ref(var, true),
397 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
398 let var = self.var.name(ctx.db()).unwrap().to_string();
399 let var_name = make::name(&var);
400 let pat = match self.kind() {
401 ParamKind::MutValue => make::ident_pat(false, true, var_name),
402 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
403 make::ext::simple_ident_pat(var_name)
407 let ty = make_ty(&self.ty, ctx, module);
408 let ty = match self.kind() {
409 ParamKind::Value | ParamKind::MutValue => ty,
410 ParamKind::SharedRef => make::ty_ref(ty, false),
411 ParamKind::MutRef => make::ty_ref(ty, true),
414 make::param(pat.into(), ty)
419 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
421 // We favour Result for `expr?`
422 return Some(TryKind::Result { ty });
424 let adt = ty.as_adt()?;
425 let name = adt.name(ctx.db());
426 // FIXME: use lang items to determine if it is std type or user defined
427 // E.g. if user happens to define type named `Option`, we would have false positive
428 match name.to_string().as_str() {
429 "Option" => Some(TryKind::Option),
430 "Result" => Some(TryKind::Result { ty }),
437 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
439 FlowKind::Return(_) => make::expr_return(expr),
440 FlowKind::Break(_) => make::expr_break(expr),
441 FlowKind::Try { .. } => {
442 stdx::never!("cannot have result handler with try");
443 expr.unwrap_or_else(|| make::expr_return(None))
445 FlowKind::Continue => {
446 stdx::always!(expr.is_none(), "continue with value is not possible");
447 make::expr_continue()
452 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
454 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
455 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
457 FlowKind::Try { .. } => {
458 stdx::never!("try does not have defined expr_ty");
467 fn parent(&self) -> Option<SyntaxNode> {
469 FunctionBody::Expr(expr) => expr.syntax().parent(),
470 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
474 fn from_expr(expr: ast::Expr) -> Option<Self> {
476 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
477 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
478 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
479 expr => Some(Self::Expr(expr)),
483 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
484 let mut text_range = parent
486 .map(|stmt| stmt.syntax().text_range())
487 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
488 .fold1(|acc, stmt| acc.cover(stmt));
489 if let Some(tail_range) = parent
491 .map(|it| it.syntax().text_range())
492 .filter(|&it| selected.intersect(it).is_some())
494 text_range = Some(match text_range {
495 Some(text_range) => text_range.cover(tail_range),
499 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
502 fn indent_level(&self) -> IndentLevel {
504 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
505 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
509 fn tail_expr(&self) -> Option<ast::Expr> {
511 FunctionBody::Expr(expr) => Some(expr.clone()),
512 FunctionBody::Span { parent, text_range } => {
513 let tail_expr = parent.tail_expr()?;
514 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
519 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
521 FunctionBody::Expr(expr) => walk_expr(expr, cb),
522 FunctionBody::Span { parent, text_range } => {
525 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
526 .filter_map(|stmt| match stmt {
527 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
528 ast::Stmt::Item(_) => None,
529 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
531 .for_each(|expr| walk_expr(&expr, cb));
532 if let Some(expr) = parent
534 .filter(|it| text_range.contains_range(it.syntax().text_range()))
536 walk_expr(&expr, cb);
542 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
544 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
545 FunctionBody::Span { parent, text_range } => {
548 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
549 .filter_map(|stmt| match stmt {
550 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
551 ast::Stmt::Item(_) => None,
552 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
554 .for_each(|expr| preorder_expr(&expr, cb));
555 if let Some(expr) = parent
557 .filter(|it| text_range.contains_range(it.syntax().text_range()))
559 preorder_expr(&expr, cb);
565 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
567 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
568 FunctionBody::Span { parent, text_range } => {
571 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
572 .for_each(|stmt| match stmt {
573 ast::Stmt::ExprStmt(expr_stmt) => {
574 if let Some(expr) = expr_stmt.expr() {
575 walk_patterns_in_expr(&expr, cb)
578 ast::Stmt::Item(_) => (),
579 ast::Stmt::LetStmt(stmt) => {
580 if let Some(pat) = stmt.pat() {
583 if let Some(expr) = stmt.initializer() {
584 walk_patterns_in_expr(&expr, cb);
588 if let Some(expr) = parent
590 .filter(|it| text_range.contains_range(it.syntax().text_range()))
592 walk_patterns_in_expr(&expr, cb);
598 fn text_range(&self) -> TextRange {
600 FunctionBody::Expr(expr) => expr.syntax().text_range(),
601 &FunctionBody::Span { text_range, .. } => text_range,
605 fn contains_range(&self, range: TextRange) -> bool {
606 self.text_range().contains_range(range)
609 fn precedes_range(&self, range: TextRange) -> bool {
610 self.text_range().end() <= range.start()
613 fn contains_node(&self, node: &SyntaxNode) -> bool {
614 self.contains_range(node.text_range())
619 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
620 /// whether it contains an await expression.
623 sema: &Semantics<RootDatabase>,
624 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
625 let mut self_param = None;
626 let mut res = FxIndexSet::default();
627 let mut cb = |name_ref: Option<_>| {
629 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
631 NameRefClass::Definition(Definition::Local(local_ref))
632 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
636 let InFile { file_id, value } = local_ref.source(sema.db);
637 // locals defined inside macros are not relevant to us
638 if !file_id.is_macro() {
640 Either::Right(it) => {
641 self_param.replace(it);
644 res.insert(local_ref);
649 self.walk_expr(&mut |expr| match expr {
650 ast::Expr::PathExpr(path_expr) => {
651 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
653 ast::Expr::MacroCall(call) => {
654 if let Some(tt) = call.token_tree() {
656 .children_with_tokens()
657 .flat_map(SyntaxElement::into_token)
658 .filter(|it| it.kind() == SyntaxKind::IDENT)
659 .flat_map(|t| sema.descend_into_macros(t))
660 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
668 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
669 let mut ancestors = self.parent()?.ancestors();
670 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
671 let mut parent_loop = None;
672 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
675 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
677 parent_loop.get_or_insert(loop_.syntax().clone());
680 let (is_const, expr, ty) = loop {
681 let anc = ancestors.next()?;
684 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
685 ast::BlockExpr(block_expr) => {
686 let (constness, block) = match block_expr.modifier() {
687 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
688 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
689 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
692 let expr = Some(ast::Expr::BlockExpr(block));
693 (constness, expr.clone(), infer_expr_opt(expr))
696 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
698 ast::Static(statik) => {
699 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
701 ast::ConstArg(ca) => {
702 (true, ca.expr(), infer_expr_opt(ca.expr()))
704 ast::Const(konst) => {
705 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
707 ast::ConstParam(cp) => {
708 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
710 ast::ConstBlockPat(cbp) => {
711 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
712 (true, expr.clone(), infer_expr_opt(expr))
714 ast::Variant(__) => return None,
715 ast::Meta(__) => return None,
716 ast::LoopExpr(it) => {
717 set_parent_loop(&it);
720 ast::ForExpr(it) => {
721 set_parent_loop(&it);
724 ast::WhileExpr(it) => {
725 set_parent_loop(&it);
732 let container_tail = match expr? {
733 ast::Expr::BlockExpr(block) => block.tail_expr(),
737 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
738 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
740 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
743 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
744 match self.tail_expr() {
745 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
746 None => Some(RetType::Stmt),
750 /// Local variables defined inside `body` that are accessed outside of it
753 ctx: &'a AssistContext,
755 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
756 let parent = parent.clone();
757 let range = self.text_range();
758 locals_defined_in_body(&ctx.sema, self)
760 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
763 /// Analyses the function body for external control flow.
764 fn external_control_flow(
767 container_info: &ContainerInfo,
768 ) -> Option<ControlFlow> {
769 let mut ret_expr = None;
770 let mut try_expr = None;
771 let mut break_expr = None;
772 let mut continue_expr = None;
773 let mut is_async = false;
774 let mut _is_unsafe = false;
776 let mut unsafe_depth = 0;
777 let mut loop_depth = 0;
779 self.preorder_expr(&mut |expr| {
780 let expr = match expr {
781 WalkEvent::Enter(e) => e,
782 WalkEvent::Leave(expr) => {
784 ast::Expr::LoopExpr(_)
785 | ast::Expr::ForExpr(_)
786 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
787 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
796 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
799 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
802 ast::Expr::ReturnExpr(it) => {
805 ast::Expr::TryExpr(it) => {
808 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
809 break_expr = Some(it);
811 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
812 continue_expr = Some(it);
814 ast::Expr::AwaitExpr(_) => is_async = true,
815 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
816 // to just lift that out of there
817 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
823 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
824 (Some(_), _, None, None) => {
825 let ret_ty = container_info.ret_type.clone()?;
826 let kind = TryKind::of_ty(ret_ty, ctx)?;
828 Some(FlowKind::Try { kind })
830 (Some(_), _, _, _) => {
831 cov_mark::hit!(external_control_flow_try_and_bc);
834 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
835 (None, Some(_), _, _) => {
836 cov_mark::hit!(external_control_flow_return_and_bc);
839 (None, None, Some(_), Some(_)) => {
840 cov_mark::hit!(external_control_flow_break_and_continue);
843 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
844 (None, None, None, Some(_)) => Some(FlowKind::Continue),
845 (None, None, None, None) => None,
848 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
851 /// find variables that should be extracted as params
853 /// Computes additional info that affects param type and mutability
854 fn extracted_function_params(
857 container_info: &ContainerInfo,
858 locals: impl Iterator<Item = Local>,
861 .map(|local| (local, local.source(ctx.db())))
862 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
863 .filter_map(|(local, src)| match src.value {
864 Either::Left(src) => Some((local, src)),
865 Either::Right(_) => {
866 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
871 let usages = LocalUsages::find_local_usages(ctx, var);
872 let ty = var.ty(ctx.db());
874 let defined_outside_parent_loop = container_info
877 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
879 let is_copy = ty.is_copy(ctx.db());
880 let has_usages = self.has_usages_after_body(&usages);
882 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
883 // We can move the value into the function call if it's not used after the call,
884 // if the var is not used but defined outside a loop we are extracting from we can't move it either
885 // as the function will reuse it in the next iteration.
886 let move_local = !has_usages && defined_outside_parent_loop;
887 Param { var, ty, move_local, requires_mut, is_copy }
892 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
893 usages.iter().any(|reference| self.precedes_range(reference.range))
897 /// checks if relevant var is used with `&mut` access inside body
898 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
901 .filter(|reference| body.contains_range(reference.range))
902 .any(|reference| reference_is_exclusive(reference, body, ctx))
905 /// checks if this reference requires `&mut` access inside node
906 fn reference_is_exclusive(
907 reference: &FileReference,
908 node: &dyn HasTokenAtOffset,
911 // we directly modify variable with set: `n = 0`, `n += 1`
912 if reference.category == Some(ReferenceCategory::Write) {
916 // we take `&mut` reference to variable: `&mut v`
917 let path = match path_element_of_reference(node, reference) {
919 None => return false,
922 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
925 /// checks if this expr requires `&mut` access, recurses on field access
926 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
927 if let ast::Expr::MacroCall(_) = expr {
928 // FIXME: expand macro and check output for mutable usages of the variable?
932 let parent = expr.syntax().parent()?;
934 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
935 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
936 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
941 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
942 return Some(ref_expr.mut_token().is_some());
945 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
946 let func = ctx.sema.resolve_method_call(&method_call)?;
947 let self_param = func.self_param(ctx.db())?;
948 let access = self_param.access(ctx.db());
950 return Some(matches!(access, hir::Access::Exclusive));
953 if let Some(field) = ast::FieldExpr::cast(parent) {
954 return expr_require_exclusive_access(ctx, &field.into());
960 trait HasTokenAtOffset {
961 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
964 impl HasTokenAtOffset for SyntaxNode {
965 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
966 SyntaxNode::token_at_offset(self, offset)
970 impl HasTokenAtOffset for FunctionBody {
971 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
973 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
974 FunctionBody::Span { parent, text_range } => {
975 match parent.syntax().token_at_offset(offset) {
976 TokenAtOffset::None => TokenAtOffset::None,
977 TokenAtOffset::Single(t) => {
978 if text_range.contains_range(t.text_range()) {
979 TokenAtOffset::Single(t)
984 TokenAtOffset::Between(a, b) => {
986 text_range.contains_range(a.text_range()),
987 text_range.contains_range(b.text_range()),
989 (true, true) => TokenAtOffset::Between(a, b),
990 (true, false) => TokenAtOffset::Single(a),
991 (false, true) => TokenAtOffset::Single(b),
992 (false, false) => TokenAtOffset::None,
1001 /// find relevant `ast::Expr` for reference
1005 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1006 fn path_element_of_reference(
1007 node: &dyn HasTokenAtOffset,
1008 reference: &FileReference,
1009 ) -> Option<ast::Expr> {
1010 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1011 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1014 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1015 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1019 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1020 "unexpected expression type for variable usage: {:?}",
1026 /// list local variables defined inside `body`
1027 fn locals_defined_in_body(
1028 sema: &Semantics<RootDatabase>,
1029 body: &FunctionBody,
1030 ) -> FxIndexSet<Local> {
1031 // FIXME: this doesn't work well with macros
1032 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1033 let mut res = FxIndexSet::default();
1034 body.walk_pat(&mut |pat| {
1035 if let ast::Pat::IdentPat(pat) = pat {
1036 if let Some(local) = sema.to_def(&pat) {
1044 /// Returns usage details if local variable is used after(outside of) body
1045 fn local_outlives_body(
1046 ctx: &AssistContext,
1047 body_range: TextRange,
1049 parent: &SyntaxNode,
1050 ) -> Option<OutlivedLocal> {
1051 let usages = LocalUsages::find_local_usages(ctx, local);
1052 let mut has_mut_usages = false;
1053 let mut any_outlives = false;
1054 for usage in usages.iter() {
1055 if body_range.end() <= usage.range.start() {
1056 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1057 any_outlives |= true;
1059 break; // no need to check more elements we have all the info we wanted
1066 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1069 /// checks if the relevant local was defined before(outside of) body
1070 fn is_defined_outside_of_body(
1071 ctx: &AssistContext,
1072 body: &FunctionBody,
1073 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1075 src.file_id.original_file(ctx.db()) == ctx.frange.file_id
1076 && !body.contains_node(either_syntax(&src.value))
1079 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1081 Either::Left(pat) => pat.syntax(),
1082 Either::Right(it) => it.syntax(),
1086 /// find where to put extracted function definition
1088 /// Function should be put right after returned node
1089 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1090 let node = match body {
1091 FunctionBody::Expr(e) => e.syntax(),
1092 FunctionBody::Span { parent, .. } => parent.syntax(),
1094 let mut ancestors = node.ancestors().peekable();
1095 let mut last_ancestor = None;
1096 while let Some(next_ancestor) = ancestors.next() {
1097 match next_ancestor.kind() {
1098 SyntaxKind::SOURCE_FILE => break,
1099 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1100 SyntaxKind::ITEM_LIST => {
1101 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1105 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1108 SyntaxKind::ASSOC_ITEM_LIST => {
1109 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1115 last_ancestor = Some(next_ancestor);
1120 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1121 let ret_ty = fun.return_type(ctx);
1123 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1124 let name = fun.name.clone();
1125 let mut call_expr = if fun.self_param.is_some() {
1126 let self_arg = make::expr_path(make::ext::ident_path("self"));
1127 make::expr_method_call(self_arg, name, args)
1129 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1130 make::expr_call(func, args)
1133 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1135 if fun.control_flow.is_async {
1136 call_expr = make::expr_await(call_expr);
1138 let expr = handler.make_call_expr(call_expr).indent(indent);
1140 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1142 let mut buf = String::new();
1143 match fun.outliving_locals.as_slice() {
1146 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1149 buf.push_str("let (");
1150 let bindings = vars.iter().format_with(", ", |local, f| {
1151 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1153 format_to!(buf, "{}", bindings);
1154 buf.push_str(") = ");
1158 format_to!(buf, "{}", expr);
1159 let insert_comma = fun
1162 .and_then(ast::MatchArm::cast)
1163 .map_or(false, |it| it.comma_token().is_none());
1166 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1174 Try { kind: TryKind },
1175 If { action: FlowKind },
1176 IfOption { action: FlowKind },
1177 MatchOption { none: FlowKind },
1178 MatchResult { err: FlowKind },
1182 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1183 match &fun.control_flow.kind {
1184 None => FlowHandler::None,
1185 Some(flow_kind) => {
1186 let action = flow_kind.clone();
1187 if *ret_ty == FunType::Unit {
1189 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1190 FlowHandler::If { action }
1192 FlowKind::Return(_) | FlowKind::Break(_) => {
1193 FlowHandler::IfOption { action }
1195 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1199 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1200 FlowHandler::MatchOption { none: action }
1202 FlowKind::Return(_) | FlowKind::Break(_) => {
1203 FlowHandler::MatchResult { err: action }
1205 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1212 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1214 FlowHandler::None => call_expr,
1215 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1216 FlowHandler::If { action } => {
1217 let action = action.make_result_handler(None);
1218 let stmt = make::expr_stmt(action);
1219 let block = make::block_expr(iter::once(stmt.into()), None);
1220 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1221 let condition = make::condition(
1224 make::tuple_struct_pat(
1225 controlflow_break_path,
1226 iter::once(make::wildcard_pat().into()),
1231 make::expr_if(condition, block, None)
1233 FlowHandler::IfOption { action } => {
1234 let path = make::ext::ident_path("Some");
1235 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1236 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1237 let cond = make::condition(call_expr, Some(pattern.into()));
1238 let value = make::expr_path(make::ext::ident_path("value"));
1239 let action_expr = action.make_result_handler(Some(value));
1240 let action_stmt = make::expr_stmt(action_expr);
1241 let then = make::block_expr(iter::once(action_stmt.into()), None);
1242 make::expr_if(cond, then, None)
1244 FlowHandler::MatchOption { none } => {
1245 let some_name = "value";
1248 let path = make::ext::ident_path("Some");
1249 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1250 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1251 let value = make::expr_path(make::ext::ident_path(some_name));
1252 make::match_arm(iter::once(pat.into()), None, value)
1255 let path = make::ext::ident_path("None");
1256 let pat = make::path_pat(path);
1257 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1259 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1260 make::expr_match(call_expr, arms)
1262 FlowHandler::MatchResult { err } => {
1263 let ok_name = "value";
1264 let err_name = "value";
1267 let path = make::ext::ident_path("Ok");
1268 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1269 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1270 let value = make::expr_path(make::ext::ident_path(ok_name));
1271 make::match_arm(iter::once(pat.into()), None, value)
1274 let path = make::ext::ident_path("Err");
1275 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1276 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1277 let value = make::expr_path(make::ext::ident_path(err_name));
1279 iter::once(pat.into()),
1281 err.make_result_handler(Some(value)),
1284 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1285 make::expr_match(call_expr, arms)
1291 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1292 let name = var.name(ctx.db()).unwrap().to_string();
1293 make::expr_path(make::ext::ident_path(&name))
1297 ctx: &AssistContext,
1298 module: hir::Module,
1300 old_indent: IndentLevel,
1301 new_indent: IndentLevel,
1303 let mut fn_def = String::new();
1304 let params = fun.make_param_list(ctx, module);
1305 let ret_ty = fun.make_ret_ty(ctx, module);
1306 let body = make_body(ctx, old_indent, new_indent, fun);
1307 let const_kw = if fun.mods.is_const { "const " } else { "" };
1308 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1309 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1310 match ctx.config.snippet_cap {
1311 Some(_) => format_to!(
1313 "\n\n{}{}{}{}fn $0{}{}",
1323 "\n\n{}{}{}{}fn {}{}",
1332 if let Some(ret_ty) = ret_ty {
1333 format_to!(fn_def, " {}", ret_ty);
1335 format_to!(fn_def, " {}", body);
1341 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1342 let self_param = self.self_param.clone();
1343 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1344 make::param_list(self_param, params)
1347 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1348 let fun_ty = self.return_type(ctx);
1349 let handler = if self.mods.is_in_tail {
1352 FlowHandler::from_ret_ty(self, &fun_ty)
1354 let ret_ty = match &handler {
1355 FlowHandler::None => {
1356 if matches!(fun_ty, FunType::Unit) {
1359 fun_ty.make_ty(ctx, module)
1361 FlowHandler::Try { kind: TryKind::Option } => {
1362 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1364 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1365 let handler_ty = parent_ret_ty
1368 .map(|ty| make_ty(&ty, ctx, module))
1369 .unwrap_or_else(make::ty_placeholder);
1370 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1372 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1373 FlowHandler::IfOption { action } => {
1374 let handler_ty = action
1376 .map(|ty| make_ty(&ty, ctx, module))
1377 .unwrap_or_else(make::ty_placeholder);
1378 make::ext::ty_option(handler_ty)
1380 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1381 FlowHandler::MatchResult { err } => {
1382 let handler_ty = err
1384 .map(|ty| make_ty(&ty, ctx, module))
1385 .unwrap_or_else(make::ty_placeholder);
1386 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1389 Some(make::ret_type(ret_ty))
1394 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1396 FunType::Unit => make::ty_unit(),
1397 FunType::Single(ty) => make_ty(ty, ctx, module),
1398 FunType::Tuple(types) => match types.as_slice() {
1400 stdx::never!("tuple type with 0 elements");
1404 stdx::never!("tuple type with 1 element");
1405 make_ty(ty, ctx, module)
1408 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1409 make::ty_tuple(types)
1417 ctx: &AssistContext,
1418 old_indent: IndentLevel,
1419 new_indent: IndentLevel,
1421 ) -> ast::BlockExpr {
1422 let ret_ty = fun.return_type(ctx);
1423 let handler = if fun.mods.is_in_tail {
1426 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
1450 .filter(|it| text_range.contains_range(it.text_range()))
1451 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1454 let mut tail_expr = match elements.pop() {
1455 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1456 elements.push(node);
1462 if tail_expr.is_none() {
1463 match fun.outliving_locals.as_slice() {
1466 tail_expr = Some(path_expr_from_local(ctx, var.local));
1469 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1470 let expr = make::expr_tuple(exprs);
1471 tail_expr = Some(expr);
1476 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1477 Some(stmt) => Some(stmt),
1479 stdx::never!("block contains non-statement");
1484 let body_indent = IndentLevel(1);
1485 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1486 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1488 make::block_expr(elements, tail_expr)
1492 let block = match &handler {
1493 FlowHandler::None => block,
1494 FlowHandler::Try { kind } => {
1495 let block = with_default_tail_expr(block, make::expr_unit());
1496 map_tail_expr(block, |tail_expr| {
1497 let constructor = match kind {
1498 TryKind::Option => "Some",
1499 TryKind::Result { .. } => "Ok",
1501 let func = make::expr_path(make::ext::ident_path(constructor));
1502 let args = make::arg_list(iter::once(tail_expr));
1503 make::expr_call(func, args)
1506 FlowHandler::If { .. } => {
1507 let controlflow_continue = make::expr_call(
1508 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1509 make::arg_list(iter::once(make::expr_unit())),
1511 with_tail_expr(block, controlflow_continue.into())
1513 FlowHandler::IfOption { .. } => {
1514 let none = make::expr_path(make::ext::ident_path("None"));
1515 with_tail_expr(block, none)
1517 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1518 let some = make::expr_path(make::ext::ident_path("Some"));
1519 let args = make::arg_list(iter::once(tail_expr));
1520 make::expr_call(some, args)
1522 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1523 let ok = make::expr_path(make::ext::ident_path("Ok"));
1524 let args = make::arg_list(iter::once(tail_expr));
1525 make::expr_call(ok, args)
1529 block.indent(new_indent)
1532 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1533 let tail_expr = match block.tail_expr() {
1534 Some(tail_expr) => tail_expr,
1535 None => return block,
1537 make::block_expr(block.statements(), Some(f(tail_expr)))
1540 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1541 match block.tail_expr() {
1543 None => make::block_expr(block.statements(), Some(tail_expr)),
1547 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1548 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1549 let stmts = block.statements().chain(stmt_tail);
1550 make::block_expr(stmts, Some(tail_expr))
1553 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1554 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1557 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1558 let ty_str = format_type(ty, ctx, module);
1562 fn rewrite_body_segment(
1563 ctx: &AssistContext,
1565 handler: &FlowHandler,
1566 syntax: &SyntaxNode,
1568 let syntax = fix_param_usages(ctx, params, syntax);
1569 update_external_control_flow(handler, &syntax);
1573 /// change all usages to account for added `&`/`&mut` for some params
1574 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1575 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1577 let tm = TreeMutator::new(syntax);
1579 for param in params {
1580 if !param.kind().is_ref() {
1584 let usages = LocalUsages::find_local_usages(ctx, param.var);
1587 .filter(|reference| syntax.text_range().contains_range(reference.range))
1588 .filter_map(|reference| path_element_of_reference(syntax, reference))
1589 .map(|expr| tm.make_mut(&expr));
1591 usages_for_param.push((param, usages.collect()));
1594 let res = tm.make_syntax_mut(syntax);
1596 for (param, usages) in usages_for_param {
1597 for usage in usages {
1598 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1599 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1602 Some(ast::Expr::RefExpr(node))
1603 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1605 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1607 Some(ast::Expr::RefExpr(node))
1608 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1610 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1613 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1614 ted::replace(usage.syntax(), p.syntax())
1623 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1624 let mut nested_loop = None;
1625 let mut nested_scope = None;
1626 for event in syntax.preorder() {
1628 WalkEvent::Enter(e) => match e.kind() {
1629 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1630 if nested_loop.is_none() {
1631 nested_loop = Some(e.clone());
1636 | SyntaxKind::STATIC
1638 | SyntaxKind::MODULE => {
1639 if nested_scope.is_none() {
1640 nested_scope = Some(e.clone());
1645 WalkEvent::Leave(e) => {
1646 if nested_scope.is_none() {
1647 if let Some(expr) = ast::Expr::cast(e.clone()) {
1649 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1650 let expr = return_expr.expr();
1651 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1652 ted::replace(return_expr.syntax(), replacement.syntax())
1655 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1656 let expr = break_expr.expr();
1657 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1658 ted::replace(break_expr.syntax(), replacement.syntax())
1661 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1662 if let Some(replacement) = make_rewritten_flow(handler, None) {
1663 ted::replace(continue_expr.syntax(), replacement.syntax())
1673 if nested_loop.as_ref() == Some(&e) {
1676 if nested_scope.as_ref() == Some(&e) {
1677 nested_scope = None;
1684 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1685 let value = match handler {
1686 FlowHandler::None | FlowHandler::Try { .. } => return None,
1687 FlowHandler::If { .. } => make::expr_call(
1688 make::expr_path(make::path_from_text("ControlFlow::Break")),
1689 make::arg_list(iter::once(make::expr_unit())),
1691 FlowHandler::IfOption { .. } => {
1692 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1693 let args = make::arg_list(iter::once(expr));
1694 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1696 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1697 FlowHandler::MatchResult { .. } => {
1698 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1699 let args = make::arg_list(iter::once(expr));
1700 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1703 Some(make::expr_return(Some(value)).clone_for_update())
1708 use crate::tests::{check_assist, check_assist_not_applicable};
1713 fn no_args_from_binary_expr() {
1726 fn $0fun_name() -> i32 {
1734 fn no_args_from_binary_expr_in_module() {
1750 fn $0fun_name() -> i32 {
1759 fn no_args_from_binary_expr_indented() {
1772 fn $0fun_name() -> i32 {
1780 fn no_args_from_stmt_with_last_expr() {
1796 fn $0fun_name() -> i32 {
1805 fn no_args_from_stmt_unit() {
1853 fn no_args_if_else() {
1858 $0if true { 1 } else { 2 }$0
1866 fn $0fun_name() -> i32 {
1867 if true { 1 } else { 2 }
1874 fn no_args_if_let_else() {
1879 $0if let true = false { 1 } else { 2 }$0
1887 fn $0fun_name() -> i32 {
1888 if let true = false { 1 } else { 2 }
1895 fn no_args_match() {
1911 fn $0fun_name() -> i32 {
1922 fn no_args_while() {
1948 $0for v in &[0, 1] { }$0
1957 for v in &[0, 1] { }
1964 fn no_args_from_loop_unit() {
1979 fn $0fun_name() -> ! {
1989 fn no_args_from_loop_with_return() {
2005 fn $0fun_name() -> i32 {
2016 fn no_args_from_match() {
2021 let v: i32 = $0match Some(1) {
2029 let v: i32 = fun_name();
2032 fn $0fun_name() -> i32 {
2043 fn extract_partial_block_single_line() {
2049 let mut v = $0n * n;$0
2056 let mut v = fun_name(n);
2060 fn $0fun_name(n: i32) -> i32 {
2069 fn extract_partial_block() {
2076 let mut v = m $0* n;
2086 let (mut v, mut w) = fun_name(m, n);
2091 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2101 fn argument_form_expr() {
2116 fn $0fun_name(n: u32) -> u32 {
2124 fn argument_used_twice_form_expr() {
2139 fn $0fun_name(n: u32) -> u32 {
2147 fn two_arguments_form_expr() {
2164 fn $0fun_name(n: u32, m: u32) -> u32 {
2172 fn argument_and_locals() {
2188 fn $0fun_name(n: u32) -> u32 {
2197 fn in_comment_is_not_applicable() {
2198 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2199 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2203 fn part_of_expr_stmt() {
2216 fn $0fun_name() -> i32 {
2224 fn function_expr() {
2245 fn extract_from_nested() {
2251 let tuple = match x {
2252 true => ($02 + 2$0, true)
2260 let tuple = match x {
2261 true => (fun_name(), true)
2266 fn $0fun_name() -> i32 {
2274 fn param_from_closure() {
2279 let lambda = |x: u32| $0x * 2$0;
2284 let lambda = |x: u32| fun_name(x);
2287 fn $0fun_name(x: u32) -> u32 {
2295 fn extract_return_stmt() {
2308 fn $0fun_name() -> u32 {
2316 fn does_not_add_extra_whitespace() {
2333 fn $0fun_name() -> u32 {
2358 fn $0fun_name() -> i32 {
2371 let v = $00f32 as u32$0;
2379 fn $0fun_name() -> u32 {
2387 fn return_not_applicable() {
2388 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2392 fn method_to_freestanding() {
2399 fn foo(&self) -> i32 {
2408 fn foo(&self) -> i32 {
2413 fn $0fun_name() -> i32 {
2421 fn method_with_reference() {
2425 struct S { f: i32 };
2428 fn foo(&self) -> i32 {
2434 struct S { f: i32 };
2437 fn foo(&self) -> i32 {
2441 fn $0fun_name(&self) -> i32 {
2450 fn method_with_mut() {
2454 struct S { f: i32 };
2463 struct S { f: i32 };
2470 fn $0fun_name(&mut self) {
2479 fn variable_defined_inside_and_used_after_no_ret() {
2492 let k = fun_name(n);
2496 fn $0fun_name(n: i32) -> i32 {
2505 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2511 $0let mut k = n * n;$0
2518 let mut k = fun_name(n);
2522 fn $0fun_name(n: i32) -> i32 {
2531 fn two_variables_defined_inside_and_used_after_no_ret() {
2545 let (k, m) = fun_name(n);
2549 fn $0fun_name(n: i32) -> (i32, i32) {
2559 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2565 $0let mut k = n * n;
2576 let (mut k, mut m, o) = fun_name(n);
2581 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2593 fn nontrivial_patterns_define_variables() {
2597 struct Counter(i32);
2599 $0let Counter(n) = Counter(0);$0
2604 struct Counter(i32);
2610 fn $0fun_name() -> i32 {
2611 let Counter(n) = Counter(0);
2619 fn struct_with_two_fields_pattern_define_variables() {
2623 struct Counter { n: i32, m: i32 };
2625 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2630 struct Counter { n: i32, m: i32 };
2632 let (n, k) = fun_name();
2636 fn $0fun_name() -> (i32, i32) {
2637 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2645 fn mut_var_from_outer_scope() {
2662 fn $0fun_name(n: &mut i32) {
2670 fn mut_field_from_outer_scope() {
2676 let mut c = C { n: 0 };
2684 let mut c = C { n: 0 };
2689 fn $0fun_name(c: &mut C) {
2697 fn mut_nested_field_from_outer_scope() {
2704 let mut c = C { p: P { n: 0 } };
2705 let mut v = C { p: P { n: 0 } };
2706 let u = C { p: P { n: 0 } };
2708 let r = &mut v.p.n;$0
2709 let m = c.p.n + v.p.n + u.p.n;
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 } };
2719 fun_name(&mut c, &u, &mut v);
2720 let m = c.p.n + v.p.n + u.p.n;
2723 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2732 fn mut_param_many_usages_stmt() {
2738 fn succ(&self) -> Self;
2739 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2742 fn succ(&self) -> Self { *self + 1 }
2761 fn succ(&self) -> Self;
2762 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2765 fn succ(&self) -> Self { *self + 1 }
2773 fn $0fun_name(n: &mut i32) {
2789 fn mut_param_many_usages_expr() {
2795 fn succ(&self) -> Self;
2796 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2799 fn succ(&self) -> Self { *self + 1 }
2820 fn succ(&self) -> Self;
2821 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2824 fn succ(&self) -> Self { *self + 1 }
2832 fn $0fun_name(n: &mut i32) {
2848 fn mut_param_by_value() {
2863 fn $0fun_name(mut n: i32) {
2871 fn mut_param_because_of_mut_ref() {
2889 fn $0fun_name(n: &mut i32) {
2898 fn mut_param_by_value_because_of_mut_ref() {
2914 fn $0fun_name(mut n: i32) {
2923 fn mut_method_call() {
2931 fn inc(&mut self) { *self += 1 }
2943 fn inc(&mut self) { *self += 1 }
2950 fn $0fun_name(mut n: i32) {
2958 fn shared_method_call() {
2966 fn succ(&self) { *self + 1 }
2978 fn succ(&self) { *self + 1 }
2985 fn $0fun_name(n: i32) {
2993 fn mut_method_call_with_other_receiver() {
2998 fn inc(&mut self, n: i32);
3001 fn inc(&mut self, n: i32) { *self += n }
3011 fn inc(&mut self, n: i32);
3014 fn inc(&mut self, n: i32) { *self += n }
3021 fn $0fun_name(n: i32) {
3030 fn non_copy_without_usages_after() {
3034 struct Counter(i32);
3041 struct Counter(i32);
3047 fn $0fun_name(c: Counter) {
3055 fn non_copy_used_after() {
3059 struct Counter(i32);
3067 struct Counter(i32);
3074 fn $0fun_name(c: &Counter) {
3082 fn copy_used_after() {
3100 fn $0fun_name(n: i32) {
3108 fn copy_custom_used_after() {
3112 //- minicore: copy, derive
3113 #[derive(Clone, Copy)]
3114 struct Counter(i32);
3122 #[derive(Clone, Copy)]
3123 struct Counter(i32);
3130 fn $0fun_name(c: Counter) {
3138 fn indented_stmts() {
3169 fn indented_stmts_inside_mod() {
3208 //- minicore: option
3223 let k = match fun_name(n) {
3224 Some(value) => value,
3231 fn $0fun_name(n: i32) -> Option<i32> {
3242 fn return_to_parent() {
3246 //- minicore: copy, result
3258 let k = match fun_name(n) {
3260 Err(value) => return value,
3265 fn $0fun_name(n: i32) -> Result<i32, i64> {
3276 fn break_and_continue() {
3277 cov_mark::check!(external_control_flow_break_and_continue);
3278 check_assist_not_applicable(
3297 fn return_and_break() {
3298 cov_mark::check!(external_control_flow_return_and_bc);
3299 check_assist_not_applicable(
3318 fn break_loop_with_if() {
3334 use core::ops::ControlFlow;
3339 if let ControlFlow::Break(_) = fun_name(&mut n) {
3346 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3348 return ControlFlow::Break(());
3350 ControlFlow::Continue(())
3357 fn break_loop_nested() {
3374 use core::ops::ControlFlow;
3379 if let ControlFlow::Break(_) = fun_name(n) {
3386 fn $0fun_name(n: i32) -> ControlFlow<()> {
3389 return ControlFlow::Break(());
3391 ControlFlow::Continue(())
3398 fn return_from_nested_loop() {
3418 let m = match fun_name() {
3419 Some(value) => value,
3426 fn $0fun_name() -> Option<i32> {
3439 fn break_from_nested_loop() {
3464 fn $0fun_name() -> i32 {
3477 fn break_from_nested_and_outer_loops() {
3500 let m = match fun_name() {
3501 Some(value) => value,
3508 fn $0fun_name() -> Option<i32> {
3524 fn return_from_nested_fn() {
3549 fn $0fun_name() -> i32 {
3562 fn break_with_value() {
3582 if let Some(value) = fun_name() {
3589 fn $0fun_name() -> Option<i32> {
3602 fn break_with_value_and_return() {
3622 let m = match fun_name() {
3624 Err(value) => break value,
3630 fn $0fun_name() -> Result<i32, i64> {
3647 //- minicore: option
3648 fn bar() -> Option<i32> { None }
3649 fn foo() -> Option<()> {
3658 fn bar() -> Option<i32> { None }
3659 fn foo() -> Option<()> {
3661 let m = fun_name()?;
3666 fn $0fun_name() -> Option<i32> {
3676 fn try_option_unit() {
3680 //- minicore: option
3681 fn foo() -> Option<()> {
3690 fn foo() -> Option<()> {
3697 fn $0fun_name() -> Option<()> {
3711 //- minicore: result
3712 fn foo() -> Result<(), i64> {
3721 fn foo() -> Result<(), i64> {
3723 let m = fun_name()?;
3728 fn $0fun_name() -> Result<i32, i64> {
3738 fn try_option_with_return() {
3742 //- minicore: option
3743 fn foo() -> Option<()> {
3755 fn foo() -> Option<()> {
3757 let m = fun_name()?;
3762 fn $0fun_name() -> Option<i32> {
3775 fn try_result_with_return() {
3779 //- minicore: result
3780 fn foo() -> Result<(), i64> {
3792 fn foo() -> Result<(), i64> {
3794 let m = fun_name()?;
3799 fn $0fun_name() -> Result<i32, i64> {
3812 fn try_and_break() {
3813 cov_mark::check!(external_control_flow_try_and_bc);
3814 check_assist_not_applicable(
3817 //- minicore: option
3818 fn foo() -> Option<()> {
3834 fn try_and_return_ok() {
3838 //- minicore: result
3839 fn foo() -> Result<(), i64> {
3851 fn foo() -> Result<(), i64> {
3853 let m = fun_name()?;
3858 fn $0fun_name() -> Result<i32, i64> {
3871 fn param_usage_in_macro() {
3876 ($val:expr) => { $val };
3881 $0let k = n * m!(n);$0
3887 ($val:expr) => { $val };
3892 let k = fun_name(n);
3896 fn $0fun_name(n: i32) -> i32 {
3905 fn extract_with_await() {
3910 $0some_function().await;$0
3913 async fn some_function() {
3922 async fn $0fun_name() {
3923 some_function().await;
3926 async fn some_function() {
3934 fn extract_with_await_and_result_not_producing_match_expr() {
3938 async fn foo() -> Result<(), ()> {
3944 async fn foo() -> Result<(), ()> {
3948 async fn $0fun_name() -> _ {
3957 fn extract_with_await_and_result_producing_match_expr() {
3961 async fn foo() -> i32 {
3964 let k = async { 1 }.await;
3974 async fn foo() -> i32 {
3977 let m = match fun_name().await {
3979 Err(value) => break value,
3985 async fn $0fun_name() -> Result<i32, i32> {
3986 let k = async { 1 }.await;
3998 fn extract_with_await_in_args() {
4003 $0function_call("a", some_function().await);$0
4006 async fn some_function() {
4015 async fn $0fun_name() {
4016 function_call("a", some_function().await);
4019 async fn some_function() {
4027 fn extract_does_not_extract_standalone_blocks() {
4028 check_assist_not_applicable(
4037 fn extract_adds_comma_for_match_arm() {
4056 fn $0fun_name() -> i32 {
4079 fn $0fun_name() -> i32 {
4087 fn extract_does_not_tear_comments_apart() {
4114 fn extract_does_not_wrap_res_in_res() {
4118 //- minicore: result
4119 fn foo() -> Result<(), i64> {
4120 $0Result::<i32, i64>::Ok(0)?;
4125 fn foo() -> Result<(), i64> {
4129 fn $0fun_name() -> Result<(), i64> {
4130 Result::<i32, i64>::Ok(0)?;
4138 fn extract_knows_const() {
4151 const fn $0fun_name() {
4168 const fn $0fun_name() {
4176 fn extract_does_not_move_outer_loop_vars() {
4195 fn $0fun_name(x: &mut i32) {
4218 fn $0fun_name(mut x: i32) {
4245 fn $0fun_name(x: &mut i32) {
4252 // regression test for #9822
4254 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4260 fn foo(&mut self) {}
4274 fn foo(&mut self) {}
4285 fn $0fun_name(y: &mut Foo) {
4293 fn extract_with_macro_arg() {
4298 ($val:expr) => { $val };
4307 ($val:expr) => { $val };
4314 fn $0fun_name(bar: &str) {
4322 fn unresolveable_types_default_to_placeholder() {
4327 let a = __unresolved;
4333 let a = __unresolved;
4334 let _ = fun_name(a);
4337 fn $0fun_name(a: _) -> _ {