5 use hir::{HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
9 insert_use::{insert_use, ImportScope},
11 node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
14 search::{FileReference, ReferenceCategory, SearchScope},
15 FxIndexSet, RootDatabase,
17 use itertools::Itertools;
22 edit::{AstNodeEdit, IndentLevel},
25 match_ast, ted, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize,
26 TokenAtOffset, WalkEvent, T,
30 assist_context::{AssistContext, Assists, TreeMutator},
34 // Assist: extract_function
36 // Extracts selected statements and comments into new function.
55 // fn $0fun_name(n: i32) {
61 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
62 let range = ctx.selection_trimmed();
67 let node = match ctx.covering_element() {
68 syntax::NodeOrToken::Node(n) => n,
69 syntax::NodeOrToken::Token(t) => t.parent()?,
72 let body = extraction_target(&node, range)?;
73 let container_info = body.analyze_container(&ctx.sema)?;
75 let (locals_used, self_param) = body.analyze(&ctx.sema);
77 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
78 let insert_after = node_to_insert_after(&body, anchor)?;
79 let module = ctx.sema.scope(&insert_after).module()?;
81 let ret_ty = body.return_ty(ctx)?;
82 let control_flow = body.external_control_flow(ctx, &container_info)?;
83 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
85 let target_range = body.text_range();
87 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
90 AssistId("extract_function", crate::AssistKind::RefactorExtract),
91 "Extract into function",
94 let outliving_locals: Vec<_> = ret_values.collect();
95 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
96 // We should not have variables that outlive body if we have expression block
101 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
104 name: make::name_ref("fun_name"),
111 mods: container_info,
114 let new_indent = IndentLevel::from_node(&insert_after);
115 let old_indent = fun.body.indent_level();
117 builder.replace(target_range, make_call(ctx, &fun, old_indent));
119 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
120 let insert_offset = insert_after.text_range().end();
122 if fn_def.contains("ControlFlow") {
123 let scope = match scope {
124 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
125 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
126 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
129 let control_flow_enum =
130 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
132 if let Some(control_flow_enum) = control_flow_enum {
133 let mod_path = module.find_use_path_prefixed(
135 ModuleDef::from(control_flow_enum),
136 ctx.config.insert_use.prefix_kind,
139 if let Some(mod_path) = mod_path {
140 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
145 match ctx.config.snippet_cap {
146 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
147 None => builder.insert(insert_offset, fn_def),
153 /// Try to guess what user wants to extract
155 /// We have basically have two cases:
156 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
157 /// Then we can use `ast::Expr`
158 /// * We want a few statements for a block. E.g.
160 /// fn foo() -> i32 {
170 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
171 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
173 ast::Stmt::Item(_) => None,
174 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
175 node.parent().and_then(ast::StmtList::cast)?,
181 // Covering element returned the parent block of one or multiple statements that have been selected
182 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
183 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
184 if block_expr.syntax().text_range() == selection_range {
185 return FunctionBody::from_expr(block_expr.into());
189 // Extract the full statements.
190 return Some(FunctionBody::from_range(stmt_list, selection_range));
193 let expr = ast::Expr::cast(node.clone())?;
194 // A node got selected fully
195 if node.text_range() == selection_range {
196 return FunctionBody::from_expr(expr);
199 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
205 self_param: Option<ast::SelfParam>,
207 control_flow: ControlFlow,
210 outliving_locals: Vec<OutlivedLocal>,
223 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
231 #[derive(Debug, Eq, PartialEq)]
235 Tuple(Vec<hir::Type>),
238 /// Where to put extracted function definition
241 /// Extract free function and put right after current top-level function
243 /// Extract method and put right after current function in the impl-block
247 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
248 // probably be merged somehow.
251 kind: Option<FlowKind>,
256 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
257 #[derive(Clone, Debug)]
258 struct ContainerInfo {
261 parent_loop: Option<SyntaxNode>,
262 /// The function's return type, const's type etc.
263 ret_type: Option<hir::Type>,
266 /// Control flow that is exported from extracted function
278 #[derive(Debug, Clone)]
280 /// Return with value (`return $expr;`)
281 Return(Option<ast::Expr>),
285 /// Break with value (`break $expr;`)
286 Break(Option<ast::Expr>),
291 #[derive(Debug, Clone)]
294 Result { ty: hir::Type },
304 fn is_unit(&self) -> bool {
306 RetType::Expr(ty) => ty.is_unit(),
307 RetType::Stmt => true,
312 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
313 /// This is the future function body, the part that is being extracted.
317 Span { parent: ast::StmtList, text_range: TextRange },
321 struct OutlivedLocal {
323 mut_usage_outside_body: bool,
326 /// Container of local variable usages
328 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
329 struct LocalUsages(ide_db::search::UsageSearchResult);
332 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
334 Definition::Local(var)
336 .in_scope(SearchScope::single_file(ctx.file_id()))
341 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
342 self.0.iter().flat_map(|(_, rs)| rs)
347 fn return_type(&self, ctx: &AssistContext) -> FunType {
349 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
350 RetType::Expr(ty) => FunType::Single(ty.clone()),
351 RetType::Stmt => match self.outliving_locals.as_slice() {
353 [var] => FunType::Single(var.local.ty(ctx.db())),
355 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
356 FunType::Tuple(types)
364 fn is_ref(&self) -> bool {
365 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
370 fn kind(&self) -> ParamKind {
371 match (self.move_local, self.requires_mut, self.is_copy) {
372 (false, true, _) => ParamKind::MutRef,
373 (false, false, false) => ParamKind::SharedRef,
374 (true, true, _) => ParamKind::MutValue,
375 (_, false, _) => ParamKind::Value,
379 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
380 let var = path_expr_from_local(ctx, self.var);
382 ParamKind::Value | ParamKind::MutValue => var,
383 ParamKind::SharedRef => make::expr_ref(var, false),
384 ParamKind::MutRef => make::expr_ref(var, true),
388 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
389 let var = self.var.name(ctx.db()).unwrap().to_string();
390 let var_name = make::name(&var);
391 let pat = match self.kind() {
392 ParamKind::MutValue => make::ident_pat(false, true, var_name),
393 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
394 make::ext::simple_ident_pat(var_name)
398 let ty = make_ty(&self.ty, ctx, module);
399 let ty = match self.kind() {
400 ParamKind::Value | ParamKind::MutValue => ty,
401 ParamKind::SharedRef => make::ty_ref(ty, false),
402 ParamKind::MutRef => make::ty_ref(ty, true),
405 make::param(pat.into(), ty)
410 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
412 // We favour Result for `expr?`
413 return Some(TryKind::Result { ty });
415 let adt = ty.as_adt()?;
416 let name = adt.name(ctx.db());
417 // FIXME: use lang items to determine if it is std type or user defined
418 // E.g. if user happens to define type named `Option`, we would have false positive
419 match name.to_string().as_str() {
420 "Option" => Some(TryKind::Option),
421 "Result" => Some(TryKind::Result { ty }),
428 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
430 FlowKind::Return(_) => make::expr_return(expr),
431 FlowKind::Break(_) => make::expr_break(expr),
432 FlowKind::Try { .. } => {
433 stdx::never!("cannot have result handler with try");
434 expr.unwrap_or_else(|| make::expr_return(None))
436 FlowKind::Continue => {
437 stdx::always!(expr.is_none(), "continue with value is not possible");
438 make::expr_continue()
443 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
445 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
446 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
448 FlowKind::Try { .. } => {
449 stdx::never!("try does not have defined expr_ty");
458 fn parent(&self) -> Option<SyntaxNode> {
460 FunctionBody::Expr(expr) => expr.syntax().parent(),
461 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
465 fn from_expr(expr: ast::Expr) -> Option<Self> {
467 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
468 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
469 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
470 expr => Some(Self::Expr(expr)),
474 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
475 let full_body = parent.syntax().children_with_tokens();
477 let mut text_range = full_body
478 .map(|stmt| stmt.text_range())
479 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
480 .reduce(|acc, stmt| acc.cover(stmt));
482 if let Some(tail_range) = parent
484 .map(|it| it.syntax().text_range())
485 .filter(|&it| selected.intersect(it).is_some())
487 text_range = Some(match text_range {
488 Some(text_range) => text_range.cover(tail_range),
492 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
495 fn indent_level(&self) -> IndentLevel {
497 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
498 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
502 fn tail_expr(&self) -> Option<ast::Expr> {
504 FunctionBody::Expr(expr) => Some(expr.clone()),
505 FunctionBody::Span { parent, text_range } => {
506 let tail_expr = parent.tail_expr()?;
507 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
512 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
514 FunctionBody::Expr(expr) => walk_expr(expr, cb),
515 FunctionBody::Span { parent, text_range } => {
518 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
519 .filter_map(|stmt| match stmt {
520 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
521 ast::Stmt::Item(_) => None,
522 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
524 .for_each(|expr| walk_expr(&expr, cb));
525 if let Some(expr) = parent
527 .filter(|it| text_range.contains_range(it.syntax().text_range()))
529 walk_expr(&expr, cb);
535 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
537 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
538 FunctionBody::Span { parent, text_range } => {
541 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
542 .filter_map(|stmt| match stmt {
543 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
544 ast::Stmt::Item(_) => None,
545 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
547 .for_each(|expr| preorder_expr(&expr, cb));
548 if let Some(expr) = parent
550 .filter(|it| text_range.contains_range(it.syntax().text_range()))
552 preorder_expr(&expr, cb);
558 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
560 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
561 FunctionBody::Span { parent, text_range } => {
564 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
565 .for_each(|stmt| match stmt {
566 ast::Stmt::ExprStmt(expr_stmt) => {
567 if let Some(expr) = expr_stmt.expr() {
568 walk_patterns_in_expr(&expr, cb)
571 ast::Stmt::Item(_) => (),
572 ast::Stmt::LetStmt(stmt) => {
573 if let Some(pat) = stmt.pat() {
576 if let Some(expr) = stmt.initializer() {
577 walk_patterns_in_expr(&expr, cb);
581 if let Some(expr) = parent
583 .filter(|it| text_range.contains_range(it.syntax().text_range()))
585 walk_patterns_in_expr(&expr, cb);
591 fn text_range(&self) -> TextRange {
593 FunctionBody::Expr(expr) => expr.syntax().text_range(),
594 &FunctionBody::Span { text_range, .. } => text_range,
598 fn contains_range(&self, range: TextRange) -> bool {
599 self.text_range().contains_range(range)
602 fn precedes_range(&self, range: TextRange) -> bool {
603 self.text_range().end() <= range.start()
606 fn contains_node(&self, node: &SyntaxNode) -> bool {
607 self.contains_range(node.text_range())
612 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
613 /// whether it contains an await expression.
616 sema: &Semantics<RootDatabase>,
617 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
618 let mut self_param = None;
619 let mut res = FxIndexSet::default();
620 let mut cb = |name_ref: Option<_>| {
622 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
624 NameRefClass::Definition(Definition::Local(local_ref))
625 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
629 let InFile { file_id, value } = local_ref.source(sema.db);
630 // locals defined inside macros are not relevant to us
631 if !file_id.is_macro() {
633 Either::Right(it) => {
634 self_param.replace(it);
637 res.insert(local_ref);
642 self.walk_expr(&mut |expr| match expr {
643 ast::Expr::PathExpr(path_expr) => {
644 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
646 ast::Expr::MacroCall(call) => {
647 if let Some(tt) = call.token_tree() {
649 .children_with_tokens()
650 .flat_map(SyntaxElement::into_token)
651 .filter(|it| it.kind() == SyntaxKind::IDENT)
652 .flat_map(|t| sema.descend_into_macros(t))
653 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
661 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
662 let mut ancestors = self.parent()?.ancestors();
663 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
664 let mut parent_loop = None;
665 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
668 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
670 parent_loop.get_or_insert(loop_.syntax().clone());
673 let (is_const, expr, ty) = loop {
674 let anc = ancestors.next()?;
677 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
678 ast::BlockExpr(block_expr) => {
679 let (constness, block) = match block_expr.modifier() {
680 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
681 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
682 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
685 let expr = Some(ast::Expr::BlockExpr(block));
686 (constness, expr.clone(), infer_expr_opt(expr))
689 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
691 ast::Static(statik) => {
692 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
694 ast::ConstArg(ca) => {
695 (true, ca.expr(), infer_expr_opt(ca.expr()))
697 ast::Const(konst) => {
698 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
700 ast::ConstParam(cp) => {
701 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
703 ast::ConstBlockPat(cbp) => {
704 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
705 (true, expr.clone(), infer_expr_opt(expr))
707 ast::Variant(__) => return None,
708 ast::Meta(__) => return None,
709 ast::LoopExpr(it) => {
710 set_parent_loop(&it);
713 ast::ForExpr(it) => {
714 set_parent_loop(&it);
717 ast::WhileExpr(it) => {
718 set_parent_loop(&it);
725 let container_tail = match expr? {
726 ast::Expr::BlockExpr(block) => block.tail_expr(),
730 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
731 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
733 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
736 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
737 match self.tail_expr() {
738 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
739 None => Some(RetType::Stmt),
743 /// Local variables defined inside `body` that are accessed outside of it
746 ctx: &'a AssistContext,
748 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
749 let parent = parent.clone();
750 let range = self.text_range();
751 locals_defined_in_body(&ctx.sema, self)
753 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
756 /// Analyses the function body for external control flow.
757 fn external_control_flow(
760 container_info: &ContainerInfo,
761 ) -> Option<ControlFlow> {
762 let mut ret_expr = None;
763 let mut try_expr = None;
764 let mut break_expr = None;
765 let mut continue_expr = None;
766 let mut is_async = false;
767 let mut _is_unsafe = false;
769 let mut unsafe_depth = 0;
770 let mut loop_depth = 0;
772 self.preorder_expr(&mut |expr| {
773 let expr = match expr {
774 WalkEvent::Enter(e) => e,
775 WalkEvent::Leave(expr) => {
777 ast::Expr::LoopExpr(_)
778 | ast::Expr::ForExpr(_)
779 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
780 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
789 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
792 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
795 ast::Expr::ReturnExpr(it) => {
798 ast::Expr::TryExpr(it) => {
801 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
802 break_expr = Some(it);
804 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
805 continue_expr = Some(it);
807 ast::Expr::AwaitExpr(_) => is_async = true,
808 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
809 // to just lift that out of there
810 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
816 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
817 (Some(_), _, None, None) => {
818 let ret_ty = container_info.ret_type.clone()?;
819 let kind = TryKind::of_ty(ret_ty, ctx)?;
821 Some(FlowKind::Try { kind })
823 (Some(_), _, _, _) => {
824 cov_mark::hit!(external_control_flow_try_and_bc);
827 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
828 (None, Some(_), _, _) => {
829 cov_mark::hit!(external_control_flow_return_and_bc);
832 (None, None, Some(_), Some(_)) => {
833 cov_mark::hit!(external_control_flow_break_and_continue);
836 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
837 (None, None, None, Some(_)) => Some(FlowKind::Continue),
838 (None, None, None, None) => None,
841 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
844 /// find variables that should be extracted as params
846 /// Computes additional info that affects param type and mutability
847 fn extracted_function_params(
850 container_info: &ContainerInfo,
851 locals: impl Iterator<Item = Local>,
854 .map(|local| (local, local.source(ctx.db())))
855 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
856 .filter_map(|(local, src)| match src.value {
857 Either::Left(src) => Some((local, src)),
858 Either::Right(_) => {
859 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
864 let usages = LocalUsages::find_local_usages(ctx, var);
865 let ty = var.ty(ctx.db());
867 let defined_outside_parent_loop = container_info
870 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
872 let is_copy = ty.is_copy(ctx.db());
873 let has_usages = self.has_usages_after_body(&usages);
875 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
876 // We can move the value into the function call if it's not used after the call,
877 // if the var is not used but defined outside a loop we are extracting from we can't move it either
878 // as the function will reuse it in the next iteration.
879 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
880 Param { var, ty, move_local, requires_mut, is_copy }
885 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
886 usages.iter().any(|reference| self.precedes_range(reference.range))
890 /// checks if relevant var is used with `&mut` access inside body
891 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
894 .filter(|reference| body.contains_range(reference.range))
895 .any(|reference| reference_is_exclusive(reference, body, ctx))
898 /// checks if this reference requires `&mut` access inside node
899 fn reference_is_exclusive(
900 reference: &FileReference,
901 node: &dyn HasTokenAtOffset,
904 // we directly modify variable with set: `n = 0`, `n += 1`
905 if reference.category == Some(ReferenceCategory::Write) {
909 // we take `&mut` reference to variable: `&mut v`
910 let path = match path_element_of_reference(node, reference) {
912 None => return false,
915 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
918 /// checks if this expr requires `&mut` access, recurses on field access
919 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
920 if let ast::Expr::MacroCall(_) = expr {
921 // FIXME: expand macro and check output for mutable usages of the variable?
925 let parent = expr.syntax().parent()?;
927 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
928 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
929 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
934 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
935 return Some(ref_expr.mut_token().is_some());
938 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
939 let func = ctx.sema.resolve_method_call(&method_call)?;
940 let self_param = func.self_param(ctx.db())?;
941 let access = self_param.access(ctx.db());
943 return Some(matches!(access, hir::Access::Exclusive));
946 if let Some(field) = ast::FieldExpr::cast(parent) {
947 return expr_require_exclusive_access(ctx, &field.into());
953 trait HasTokenAtOffset {
954 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
957 impl HasTokenAtOffset for SyntaxNode {
958 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
959 SyntaxNode::token_at_offset(self, offset)
963 impl HasTokenAtOffset for FunctionBody {
964 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
966 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
967 FunctionBody::Span { parent, text_range } => {
968 match parent.syntax().token_at_offset(offset) {
969 TokenAtOffset::None => TokenAtOffset::None,
970 TokenAtOffset::Single(t) => {
971 if text_range.contains_range(t.text_range()) {
972 TokenAtOffset::Single(t)
977 TokenAtOffset::Between(a, b) => {
979 text_range.contains_range(a.text_range()),
980 text_range.contains_range(b.text_range()),
982 (true, true) => TokenAtOffset::Between(a, b),
983 (true, false) => TokenAtOffset::Single(a),
984 (false, true) => TokenAtOffset::Single(b),
985 (false, false) => TokenAtOffset::None,
994 /// find relevant `ast::Expr` for reference
998 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
999 fn path_element_of_reference(
1000 node: &dyn HasTokenAtOffset,
1001 reference: &FileReference,
1002 ) -> Option<ast::Expr> {
1003 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1004 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1007 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1008 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1012 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1013 "unexpected expression type for variable usage: {:?}",
1019 /// list local variables defined inside `body`
1020 fn locals_defined_in_body(
1021 sema: &Semantics<RootDatabase>,
1022 body: &FunctionBody,
1023 ) -> FxIndexSet<Local> {
1024 // FIXME: this doesn't work well with macros
1025 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1026 let mut res = FxIndexSet::default();
1027 body.walk_pat(&mut |pat| {
1028 if let ast::Pat::IdentPat(pat) = pat {
1029 if let Some(local) = sema.to_def(&pat) {
1037 /// Returns usage details if local variable is used after(outside of) body
1038 fn local_outlives_body(
1039 ctx: &AssistContext,
1040 body_range: TextRange,
1042 parent: &SyntaxNode,
1043 ) -> Option<OutlivedLocal> {
1044 let usages = LocalUsages::find_local_usages(ctx, local);
1045 let mut has_mut_usages = false;
1046 let mut any_outlives = false;
1047 for usage in usages.iter() {
1048 if body_range.end() <= usage.range.start() {
1049 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1050 any_outlives |= true;
1052 break; // no need to check more elements we have all the info we wanted
1059 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1062 /// checks if the relevant local was defined before(outside of) body
1063 fn is_defined_outside_of_body(
1064 ctx: &AssistContext,
1065 body: &FunctionBody,
1066 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1068 src.file_id.original_file(ctx.db()) == ctx.file_id()
1069 && !body.contains_node(either_syntax(&src.value))
1072 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1074 Either::Left(pat) => pat.syntax(),
1075 Either::Right(it) => it.syntax(),
1079 /// find where to put extracted function definition
1081 /// Function should be put right after returned node
1082 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1083 let node = match body {
1084 FunctionBody::Expr(e) => e.syntax(),
1085 FunctionBody::Span { parent, .. } => parent.syntax(),
1087 let mut ancestors = node.ancestors().peekable();
1088 let mut last_ancestor = None;
1089 while let Some(next_ancestor) = ancestors.next() {
1090 match next_ancestor.kind() {
1091 SyntaxKind::SOURCE_FILE => break,
1092 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1093 SyntaxKind::ITEM_LIST => {
1094 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1098 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1101 SyntaxKind::ASSOC_ITEM_LIST => {
1102 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1108 last_ancestor = Some(next_ancestor);
1113 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1114 let ret_ty = fun.return_type(ctx);
1116 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1117 let name = fun.name.clone();
1118 let mut call_expr = if fun.self_param.is_some() {
1119 let self_arg = make::expr_path(make::ext::ident_path("self"));
1120 make::expr_method_call(self_arg, name, args)
1122 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1123 make::expr_call(func, args)
1126 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1128 if fun.control_flow.is_async {
1129 call_expr = make::expr_await(call_expr);
1131 let expr = handler.make_call_expr(call_expr).indent(indent);
1133 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1135 let mut buf = String::new();
1136 match fun.outliving_locals.as_slice() {
1139 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1142 buf.push_str("let (");
1143 let bindings = vars.iter().format_with(", ", |local, f| {
1144 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1146 format_to!(buf, "{}", bindings);
1147 buf.push_str(") = ");
1151 format_to!(buf, "{}", expr);
1152 let insert_comma = fun
1155 .and_then(ast::MatchArm::cast)
1156 .map_or(false, |it| it.comma_token().is_none());
1159 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1167 Try { kind: TryKind },
1168 If { action: FlowKind },
1169 IfOption { action: FlowKind },
1170 MatchOption { none: FlowKind },
1171 MatchResult { err: FlowKind },
1175 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1176 match &fun.control_flow.kind {
1177 None => FlowHandler::None,
1178 Some(flow_kind) => {
1179 let action = flow_kind.clone();
1180 if *ret_ty == FunType::Unit {
1182 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1183 FlowHandler::If { action }
1185 FlowKind::Return(_) | FlowKind::Break(_) => {
1186 FlowHandler::IfOption { action }
1188 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1192 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1193 FlowHandler::MatchOption { none: action }
1195 FlowKind::Return(_) | FlowKind::Break(_) => {
1196 FlowHandler::MatchResult { err: action }
1198 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1205 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1207 FlowHandler::None => call_expr,
1208 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1209 FlowHandler::If { action } => {
1210 let action = action.make_result_handler(None);
1211 let stmt = make::expr_stmt(action);
1212 let block = make::block_expr(iter::once(stmt.into()), None);
1213 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1214 let condition = make::condition(
1217 make::tuple_struct_pat(
1218 controlflow_break_path,
1219 iter::once(make::wildcard_pat().into()),
1224 make::expr_if(condition, block, None)
1226 FlowHandler::IfOption { action } => {
1227 let path = make::ext::ident_path("Some");
1228 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1229 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1230 let cond = make::condition(call_expr, Some(pattern.into()));
1231 let value = make::expr_path(make::ext::ident_path("value"));
1232 let action_expr = action.make_result_handler(Some(value));
1233 let action_stmt = make::expr_stmt(action_expr);
1234 let then = make::block_expr(iter::once(action_stmt.into()), None);
1235 make::expr_if(cond, then, None)
1237 FlowHandler::MatchOption { none } => {
1238 let some_name = "value";
1241 let path = make::ext::ident_path("Some");
1242 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1243 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1244 let value = make::expr_path(make::ext::ident_path(some_name));
1245 make::match_arm(iter::once(pat.into()), None, value)
1248 let path = make::ext::ident_path("None");
1249 let pat = make::path_pat(path);
1250 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1252 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1253 make::expr_match(call_expr, arms)
1255 FlowHandler::MatchResult { err } => {
1256 let ok_name = "value";
1257 let err_name = "value";
1260 let path = make::ext::ident_path("Ok");
1261 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1262 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1263 let value = make::expr_path(make::ext::ident_path(ok_name));
1264 make::match_arm(iter::once(pat.into()), None, value)
1267 let path = make::ext::ident_path("Err");
1268 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1269 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1270 let value = make::expr_path(make::ext::ident_path(err_name));
1272 iter::once(pat.into()),
1274 err.make_result_handler(Some(value)),
1277 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1278 make::expr_match(call_expr, arms)
1284 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1285 let name = var.name(ctx.db()).unwrap().to_string();
1286 make::expr_path(make::ext::ident_path(&name))
1290 ctx: &AssistContext,
1291 module: hir::Module,
1293 old_indent: IndentLevel,
1294 new_indent: IndentLevel,
1296 let mut fn_def = String::new();
1297 let params = fun.make_param_list(ctx, module);
1298 let ret_ty = fun.make_ret_ty(ctx, module);
1299 let body = make_body(ctx, old_indent, new_indent, fun);
1300 let const_kw = if fun.mods.is_const { "const " } else { "" };
1301 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1302 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1303 match ctx.config.snippet_cap {
1304 Some(_) => format_to!(
1306 "\n\n{}{}{}{}fn $0{}{}",
1316 "\n\n{}{}{}{}fn {}{}",
1325 if let Some(ret_ty) = ret_ty {
1326 format_to!(fn_def, " {}", ret_ty);
1328 format_to!(fn_def, " {}", body);
1334 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1335 let self_param = self.self_param.clone();
1336 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1337 make::param_list(self_param, params)
1340 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1341 let fun_ty = self.return_type(ctx);
1342 let handler = if self.mods.is_in_tail {
1345 FlowHandler::from_ret_ty(self, &fun_ty)
1347 let ret_ty = match &handler {
1348 FlowHandler::None => {
1349 if matches!(fun_ty, FunType::Unit) {
1352 fun_ty.make_ty(ctx, module)
1354 FlowHandler::Try { kind: TryKind::Option } => {
1355 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1357 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1358 let handler_ty = parent_ret_ty
1361 .map(|ty| make_ty(&ty, ctx, module))
1362 .unwrap_or_else(make::ty_placeholder);
1363 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1365 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1366 FlowHandler::IfOption { action } => {
1367 let handler_ty = action
1369 .map(|ty| make_ty(&ty, ctx, module))
1370 .unwrap_or_else(make::ty_placeholder);
1371 make::ext::ty_option(handler_ty)
1373 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1374 FlowHandler::MatchResult { err } => {
1375 let handler_ty = err
1377 .map(|ty| make_ty(&ty, ctx, module))
1378 .unwrap_or_else(make::ty_placeholder);
1379 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1382 Some(make::ret_type(ret_ty))
1387 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1389 FunType::Unit => make::ty_unit(),
1390 FunType::Single(ty) => make_ty(ty, ctx, module),
1391 FunType::Tuple(types) => match types.as_slice() {
1393 stdx::never!("tuple type with 0 elements");
1397 stdx::never!("tuple type with 1 element");
1398 make_ty(ty, ctx, module)
1401 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1402 make::ty_tuple(types)
1410 ctx: &AssistContext,
1411 old_indent: IndentLevel,
1412 new_indent: IndentLevel,
1414 ) -> ast::BlockExpr {
1415 let ret_ty = fun.return_type(ctx);
1416 let handler = if fun.mods.is_in_tail {
1419 FlowHandler::from_ret_ty(fun, &ret_ty)
1422 let block = match &fun.body {
1423 FunctionBody::Expr(expr) => {
1424 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1425 let expr = ast::Expr::cast(expr).unwrap();
1427 ast::Expr::BlockExpr(block) => {
1428 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1429 let block = block.dedent(old_indent);
1430 // Recreate the block for formatting consistency with other extracted functions.
1431 make::block_expr(block.statements(), block.tail_expr())
1434 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1436 make::block_expr(Vec::new(), Some(expr))
1440 FunctionBody::Span { parent, text_range } => {
1441 let mut elements: Vec<_> = parent
1443 .children_with_tokens()
1444 .filter(|it| text_range.contains_range(it.text_range()))
1445 .map(|it| match &it {
1446 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1447 rewrite_body_segment(ctx, &fun.params, &handler, &n),
1453 let mut tail_expr = match &elements.last() {
1454 Some(element) => match element {
1455 syntax::NodeOrToken::Node(node) if ast::Expr::can_cast(node.kind()) => {
1456 ast::Expr::cast(node.clone())
1467 None => match fun.outliving_locals.as_slice() {
1470 tail_expr = Some(path_expr_from_local(ctx, var.local));
1473 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1474 let expr = make::expr_tuple(exprs);
1475 tail_expr = Some(expr);
1480 let body_indent = IndentLevel(1);
1481 let elements = elements
1483 .map(|node_or_token| match &node_or_token {
1484 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1486 let indented = stmt.dedent(old_indent).indent(body_indent);
1487 let ast_node = indented.syntax().clone_subtree();
1488 syntax::NodeOrToken::Node(ast_node)
1494 .collect::<Vec<SyntaxElement>>();
1495 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1497 make::hacky_block_expr_with_comments(elements, tail_expr)
1501 let block = match &handler {
1502 FlowHandler::None => block,
1503 FlowHandler::Try { kind } => {
1504 let block = with_default_tail_expr(block, make::expr_unit());
1505 map_tail_expr(block, |tail_expr| {
1506 let constructor = match kind {
1507 TryKind::Option => "Some",
1508 TryKind::Result { .. } => "Ok",
1510 let func = make::expr_path(make::ext::ident_path(constructor));
1511 let args = make::arg_list(iter::once(tail_expr));
1512 make::expr_call(func, args)
1515 FlowHandler::If { .. } => {
1516 let controlflow_continue = make::expr_call(
1517 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1518 make::arg_list(iter::once(make::expr_unit())),
1520 with_tail_expr(block, controlflow_continue.into())
1522 FlowHandler::IfOption { .. } => {
1523 let none = make::expr_path(make::ext::ident_path("None"));
1524 with_tail_expr(block, none)
1526 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1527 let some = make::expr_path(make::ext::ident_path("Some"));
1528 let args = make::arg_list(iter::once(tail_expr));
1529 make::expr_call(some, args)
1531 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1532 let ok = make::expr_path(make::ext::ident_path("Ok"));
1533 let args = make::arg_list(iter::once(tail_expr));
1534 make::expr_call(ok, args)
1538 block.indent(new_indent)
1541 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1542 let tail_expr = match block.tail_expr() {
1543 Some(tail_expr) => tail_expr,
1544 None => return block,
1546 make::block_expr(block.statements(), Some(f(tail_expr)))
1549 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1550 match block.tail_expr() {
1552 None => make::block_expr(block.statements(), Some(tail_expr)),
1556 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1557 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1558 let stmts = block.statements().chain(stmt_tail);
1559 make::block_expr(stmts, Some(tail_expr))
1562 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1563 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1566 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1567 let ty_str = format_type(ty, ctx, module);
1571 fn rewrite_body_segment(
1572 ctx: &AssistContext,
1574 handler: &FlowHandler,
1575 syntax: &SyntaxNode,
1577 let syntax = fix_param_usages(ctx, params, syntax);
1578 update_external_control_flow(handler, &syntax);
1582 /// change all usages to account for added `&`/`&mut` for some params
1583 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1584 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1586 let tm = TreeMutator::new(syntax);
1588 for param in params {
1589 if !param.kind().is_ref() {
1593 let usages = LocalUsages::find_local_usages(ctx, param.var);
1596 .filter(|reference| syntax.text_range().contains_range(reference.range))
1597 .filter_map(|reference| path_element_of_reference(syntax, reference))
1598 .map(|expr| tm.make_mut(&expr));
1600 usages_for_param.push((param, usages.collect()));
1603 let res = tm.make_syntax_mut(syntax);
1605 for (param, usages) in usages_for_param {
1606 for usage in usages {
1607 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1608 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1611 Some(ast::Expr::RefExpr(node))
1612 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1614 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1616 Some(ast::Expr::RefExpr(node))
1617 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1619 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1622 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1623 ted::replace(usage.syntax(), p.syntax())
1632 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1633 let mut nested_loop = None;
1634 let mut nested_scope = None;
1635 for event in syntax.preorder() {
1637 WalkEvent::Enter(e) => match e.kind() {
1638 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1639 if nested_loop.is_none() {
1640 nested_loop = Some(e.clone());
1645 | SyntaxKind::STATIC
1647 | SyntaxKind::MODULE => {
1648 if nested_scope.is_none() {
1649 nested_scope = Some(e.clone());
1654 WalkEvent::Leave(e) => {
1655 if nested_scope.is_none() {
1656 if let Some(expr) = ast::Expr::cast(e.clone()) {
1658 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1659 let expr = return_expr.expr();
1660 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1661 ted::replace(return_expr.syntax(), replacement.syntax())
1664 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1665 let expr = break_expr.expr();
1666 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1667 ted::replace(break_expr.syntax(), replacement.syntax())
1670 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1671 if let Some(replacement) = make_rewritten_flow(handler, None) {
1672 ted::replace(continue_expr.syntax(), replacement.syntax())
1682 if nested_loop.as_ref() == Some(&e) {
1685 if nested_scope.as_ref() == Some(&e) {
1686 nested_scope = None;
1693 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1694 let value = match handler {
1695 FlowHandler::None | FlowHandler::Try { .. } => return None,
1696 FlowHandler::If { .. } => make::expr_call(
1697 make::expr_path(make::path_from_text("ControlFlow::Break")),
1698 make::arg_list(iter::once(make::expr_unit())),
1700 FlowHandler::IfOption { .. } => {
1701 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1702 let args = make::arg_list(iter::once(expr));
1703 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1705 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1706 FlowHandler::MatchResult { .. } => {
1707 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1708 let args = make::arg_list(iter::once(expr));
1709 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1712 Some(make::expr_return(Some(value)).clone_for_update())
1717 use crate::tests::{check_assist, check_assist_not_applicable};
1722 fn no_args_from_binary_expr() {
1735 fn $0fun_name() -> i32 {
1743 fn no_args_from_binary_expr_in_module() {
1759 fn $0fun_name() -> i32 {
1768 fn no_args_from_binary_expr_indented() {
1781 fn $0fun_name() -> i32 {
1789 fn no_args_from_stmt_with_last_expr() {
1805 fn $0fun_name() -> i32 {
1814 fn no_args_from_stmt_unit() {
1862 fn no_args_if_else() {
1867 $0if true { 1 } else { 2 }$0
1875 fn $0fun_name() -> i32 {
1876 if true { 1 } else { 2 }
1883 fn no_args_if_let_else() {
1888 $0if let true = false { 1 } else { 2 }$0
1896 fn $0fun_name() -> i32 {
1897 if let true = false { 1 } else { 2 }
1904 fn no_args_match() {
1920 fn $0fun_name() -> i32 {
1931 fn no_args_while() {
1957 $0for v in &[0, 1] { }$0
1966 for v in &[0, 1] { }
1973 fn no_args_from_loop_unit() {
1988 fn $0fun_name() -> ! {
1998 fn no_args_from_loop_with_return() {
2014 fn $0fun_name() -> i32 {
2025 fn no_args_from_match() {
2030 let v: i32 = $0match Some(1) {
2038 let v: i32 = fun_name();
2041 fn $0fun_name() -> i32 {
2052 fn extract_partial_block_single_line() {
2058 let mut v = $0n * n;$0
2065 let mut v = fun_name(n);
2069 fn $0fun_name(n: i32) -> i32 {
2078 fn extract_partial_block() {
2085 let mut v = m $0* n;
2095 let (mut v, mut w) = fun_name(m, n);
2100 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2110 fn argument_form_expr() {
2125 fn $0fun_name(n: u32) -> u32 {
2133 fn argument_used_twice_form_expr() {
2148 fn $0fun_name(n: u32) -> u32 {
2156 fn two_arguments_form_expr() {
2173 fn $0fun_name(n: u32, m: u32) -> u32 {
2181 fn argument_and_locals() {
2197 fn $0fun_name(n: u32) -> u32 {
2206 fn part_of_expr_stmt() {
2219 fn $0fun_name() -> i32 {
2227 fn function_expr() {
2248 fn extract_from_nested() {
2254 let tuple = match x {
2255 true => ($02 + 2$0, true)
2263 let tuple = match x {
2264 true => (fun_name(), true)
2269 fn $0fun_name() -> i32 {
2277 fn param_from_closure() {
2282 let lambda = |x: u32| $0x * 2$0;
2287 let lambda = |x: u32| fun_name(x);
2290 fn $0fun_name(x: u32) -> u32 {
2298 fn extract_return_stmt() {
2311 fn $0fun_name() -> u32 {
2319 fn does_not_add_extra_whitespace() {
2336 fn $0fun_name() -> u32 {
2361 fn $0fun_name() -> i32 {
2374 let v = $00f32 as u32$0;
2382 fn $0fun_name() -> u32 {
2390 fn return_not_applicable() {
2391 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2395 fn method_to_freestanding() {
2402 fn foo(&self) -> i32 {
2411 fn foo(&self) -> i32 {
2416 fn $0fun_name() -> i32 {
2424 fn method_with_reference() {
2428 struct S { f: i32 };
2431 fn foo(&self) -> i32 {
2437 struct S { f: i32 };
2440 fn foo(&self) -> i32 {
2444 fn $0fun_name(&self) -> i32 {
2453 fn method_with_mut() {
2457 struct S { f: i32 };
2466 struct S { f: i32 };
2473 fn $0fun_name(&mut self) {
2482 fn variable_defined_inside_and_used_after_no_ret() {
2495 let k = fun_name(n);
2499 fn $0fun_name(n: i32) -> i32 {
2508 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2514 $0let mut k = n * n;$0
2521 let mut k = fun_name(n);
2525 fn $0fun_name(n: i32) -> i32 {
2534 fn two_variables_defined_inside_and_used_after_no_ret() {
2548 let (k, m) = fun_name(n);
2552 fn $0fun_name(n: i32) -> (i32, i32) {
2562 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2568 $0let mut k = n * n;
2579 let (mut k, mut m, o) = fun_name(n);
2584 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2596 fn nontrivial_patterns_define_variables() {
2600 struct Counter(i32);
2602 $0let Counter(n) = Counter(0);$0
2607 struct Counter(i32);
2613 fn $0fun_name() -> i32 {
2614 let Counter(n) = Counter(0);
2622 fn struct_with_two_fields_pattern_define_variables() {
2626 struct Counter { n: i32, m: i32 };
2628 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2633 struct Counter { n: i32, m: i32 };
2635 let (n, k) = fun_name();
2639 fn $0fun_name() -> (i32, i32) {
2640 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2648 fn mut_var_from_outer_scope() {
2665 fn $0fun_name(n: &mut i32) {
2673 fn mut_field_from_outer_scope() {
2679 let mut c = C { n: 0 };
2687 let mut c = C { n: 0 };
2692 fn $0fun_name(c: &mut C) {
2700 fn mut_nested_field_from_outer_scope() {
2707 let mut c = C { p: P { n: 0 } };
2708 let mut v = C { p: P { n: 0 } };
2709 let u = C { p: P { n: 0 } };
2711 let r = &mut v.p.n;$0
2712 let m = c.p.n + v.p.n + u.p.n;
2719 let mut c = C { p: P { n: 0 } };
2720 let mut v = C { p: P { n: 0 } };
2721 let u = C { p: P { n: 0 } };
2722 fun_name(&mut c, &u, &mut v);
2723 let m = c.p.n + v.p.n + u.p.n;
2726 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2735 fn mut_param_many_usages_stmt() {
2741 fn succ(&self) -> Self;
2742 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2745 fn succ(&self) -> Self { *self + 1 }
2764 fn succ(&self) -> Self;
2765 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2768 fn succ(&self) -> Self { *self + 1 }
2776 fn $0fun_name(n: &mut i32) {
2792 fn mut_param_many_usages_expr() {
2798 fn succ(&self) -> Self;
2799 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2802 fn succ(&self) -> Self { *self + 1 }
2823 fn succ(&self) -> Self;
2824 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2827 fn succ(&self) -> Self { *self + 1 }
2835 fn $0fun_name(n: &mut i32) {
2851 fn mut_param_by_value() {
2866 fn $0fun_name(mut n: i32) {
2874 fn mut_param_because_of_mut_ref() {
2892 fn $0fun_name(n: &mut i32) {
2901 fn mut_param_by_value_because_of_mut_ref() {
2917 fn $0fun_name(mut n: i32) {
2926 fn mut_method_call() {
2934 fn inc(&mut self) { *self += 1 }
2946 fn inc(&mut self) { *self += 1 }
2953 fn $0fun_name(mut n: i32) {
2961 fn shared_method_call() {
2969 fn succ(&self) { *self + 1 }
2981 fn succ(&self) { *self + 1 }
2988 fn $0fun_name(n: i32) {
2996 fn mut_method_call_with_other_receiver() {
3001 fn inc(&mut self, n: i32);
3004 fn inc(&mut self, n: i32) { *self += n }
3014 fn inc(&mut self, n: i32);
3017 fn inc(&mut self, n: i32) { *self += n }
3024 fn $0fun_name(n: i32) {
3033 fn non_copy_without_usages_after() {
3037 struct Counter(i32);
3044 struct Counter(i32);
3050 fn $0fun_name(c: Counter) {
3058 fn non_copy_used_after() {
3062 struct Counter(i32);
3070 struct Counter(i32);
3077 fn $0fun_name(c: &Counter) {
3085 fn copy_used_after() {
3103 fn $0fun_name(n: i32) {
3111 fn copy_custom_used_after() {
3115 //- minicore: copy, derive
3116 #[derive(Clone, Copy)]
3117 struct Counter(i32);
3125 #[derive(Clone, Copy)]
3126 struct Counter(i32);
3133 fn $0fun_name(c: Counter) {
3141 fn indented_stmts() {
3172 fn indented_stmts_inside_mod() {
3211 //- minicore: option
3226 let k = match fun_name(n) {
3227 Some(value) => value,
3234 fn $0fun_name(n: i32) -> Option<i32> {
3245 fn return_to_parent() {
3249 //- minicore: copy, result
3261 let k = match fun_name(n) {
3263 Err(value) => return value,
3268 fn $0fun_name(n: i32) -> Result<i32, i64> {
3279 fn break_and_continue() {
3280 cov_mark::check!(external_control_flow_break_and_continue);
3281 check_assist_not_applicable(
3300 fn return_and_break() {
3301 cov_mark::check!(external_control_flow_return_and_bc);
3302 check_assist_not_applicable(
3321 fn break_loop_with_if() {
3337 use core::ops::ControlFlow;
3342 if let ControlFlow::Break(_) = fun_name(&mut n) {
3349 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3351 return ControlFlow::Break(());
3353 ControlFlow::Continue(())
3360 fn break_loop_nested() {
3377 use core::ops::ControlFlow;
3382 if let ControlFlow::Break(_) = fun_name(n) {
3389 fn $0fun_name(n: i32) -> ControlFlow<()> {
3392 return ControlFlow::Break(());
3394 ControlFlow::Continue(())
3401 fn return_from_nested_loop() {
3421 let m = match fun_name() {
3422 Some(value) => value,
3429 fn $0fun_name() -> Option<i32> {
3442 fn break_from_nested_loop() {
3467 fn $0fun_name() -> i32 {
3480 fn break_from_nested_and_outer_loops() {
3503 let m = match fun_name() {
3504 Some(value) => value,
3511 fn $0fun_name() -> Option<i32> {
3527 fn return_from_nested_fn() {
3552 fn $0fun_name() -> i32 {
3565 fn break_with_value() {
3585 if let Some(value) = fun_name() {
3592 fn $0fun_name() -> Option<i32> {
3605 fn break_with_value_and_return() {
3625 let m = match fun_name() {
3627 Err(value) => break value,
3633 fn $0fun_name() -> Result<i32, i64> {
3650 //- minicore: option
3651 fn bar() -> Option<i32> { None }
3652 fn foo() -> Option<()> {
3661 fn bar() -> Option<i32> { None }
3662 fn foo() -> Option<()> {
3664 let m = fun_name()?;
3669 fn $0fun_name() -> Option<i32> {
3679 fn try_option_unit() {
3683 //- minicore: option
3684 fn foo() -> Option<()> {
3693 fn foo() -> Option<()> {
3700 fn $0fun_name() -> Option<()> {
3714 //- minicore: result
3715 fn foo() -> Result<(), i64> {
3724 fn foo() -> Result<(), i64> {
3726 let m = fun_name()?;
3731 fn $0fun_name() -> Result<i32, i64> {
3741 fn try_option_with_return() {
3745 //- minicore: option
3746 fn foo() -> Option<()> {
3758 fn foo() -> Option<()> {
3760 let m = fun_name()?;
3765 fn $0fun_name() -> Option<i32> {
3778 fn try_result_with_return() {
3782 //- minicore: result
3783 fn foo() -> Result<(), i64> {
3795 fn foo() -> Result<(), i64> {
3797 let m = fun_name()?;
3802 fn $0fun_name() -> Result<i32, i64> {
3815 fn try_and_break() {
3816 cov_mark::check!(external_control_flow_try_and_bc);
3817 check_assist_not_applicable(
3820 //- minicore: option
3821 fn foo() -> Option<()> {
3837 fn try_and_return_ok() {
3841 //- minicore: result
3842 fn foo() -> Result<(), i64> {
3854 fn foo() -> Result<(), i64> {
3856 let m = fun_name()?;
3861 fn $0fun_name() -> Result<i32, i64> {
3874 fn param_usage_in_macro() {
3879 ($val:expr) => { $val };
3884 $0let k = n * m!(n);$0
3890 ($val:expr) => { $val };
3895 let k = fun_name(n);
3899 fn $0fun_name(n: i32) -> i32 {
3908 fn extract_with_await() {
3913 $0some_function().await;$0
3916 async fn some_function() {
3925 async fn $0fun_name() {
3926 some_function().await;
3929 async fn some_function() {
3937 fn extract_with_await_and_result_not_producing_match_expr() {
3941 async fn foo() -> Result<(), ()> {
3947 async fn foo() -> Result<(), ()> {
3951 async fn $0fun_name() -> _ {
3960 fn extract_with_await_and_result_producing_match_expr() {
3964 async fn foo() -> i32 {
3967 let k = async { 1 }.await;
3977 async fn foo() -> i32 {
3980 let m = match fun_name().await {
3982 Err(value) => break value,
3988 async fn $0fun_name() -> Result<i32, i32> {
3989 let k = async { 1 }.await;
4001 fn extract_with_await_in_args() {
4006 $0function_call("a", some_function().await);$0
4009 async fn some_function() {
4018 async fn $0fun_name() {
4019 function_call("a", some_function().await);
4022 async fn some_function() {
4030 fn extract_does_not_extract_standalone_blocks() {
4031 check_assist_not_applicable(
4040 fn extract_adds_comma_for_match_arm() {
4059 fn $0fun_name() -> i32 {
4082 fn $0fun_name() -> i32 {
4090 fn extract_does_not_tear_comments_apart() {
4117 fn extract_does_not_wrap_res_in_res() {
4121 //- minicore: result
4122 fn foo() -> Result<(), i64> {
4123 $0Result::<i32, i64>::Ok(0)?;
4128 fn foo() -> Result<(), i64> {
4132 fn $0fun_name() -> Result<(), i64> {
4133 Result::<i32, i64>::Ok(0)?;
4141 fn extract_knows_const() {
4154 const fn $0fun_name() {
4171 const fn $0fun_name() {
4179 fn extract_does_not_move_outer_loop_vars() {
4198 fn $0fun_name(x: &mut i32) {
4221 fn $0fun_name(mut x: i32) {
4248 fn $0fun_name(x: &mut i32) {
4255 // regression test for #9822
4257 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4263 fn foo(&mut self) {}
4277 fn foo(&mut self) {}
4288 fn $0fun_name(y: &mut Foo) {
4296 fn extract_with_macro_arg() {
4301 ($val:expr) => { $val };
4310 ($val:expr) => { $val };
4317 fn $0fun_name(bar: &str) {
4325 fn unresolveable_types_default_to_placeholder() {
4330 let a = __unresolved;
4336 let a = __unresolved;
4337 let _ = fun_name(a);
4340 fn $0fun_name(a: _) -> _ {
4348 fn reference_mutable_param_with_further_usages() {
4356 pub fn testfn(arg: &mut Foo) {
4358 // Simulating access after the extracted portion
4367 pub fn testfn(arg: &mut Foo) {
4369 // Simulating access after the extracted portion
4373 fn $0fun_name(arg: &mut Foo) {
4381 fn reference_mutable_param_without_further_usages() {
4389 pub fn testfn(arg: &mut Foo) {
4398 pub fn testfn(arg: &mut Foo) {
4402 fn $0fun_name(arg: &mut Foo) {
4410 fn extract_function_copies_comment_at_start() {
4435 fn extract_function_copies_comment_in_between() {
4462 fn extract_function_copies_comment_at_end() {
4487 fn extract_function_copies_comment_indented() {
4516 fn extract_function_does_not_preserve_whitespace() {
4542 fn extract_function_long_form_comment() {
4567 fn extract_function_long_form_comment_multiline() {
4598 fn extract_function_long_form_comment_multiline_alone() {