5 use hir::{HirDisplay, InFile, Local, ModuleDef, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
9 insert_use::{insert_use, ImportScope},
11 node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
14 search::{FileReference, ReferenceCategory, SearchScope},
15 FxIndexSet, RootDatabase,
17 use itertools::Itertools;
22 edit::{AstNodeEdit, IndentLevel},
25 match_ast, ted, SyntaxElement,
26 SyntaxKind::{self, COMMENT},
27 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
31 assist_context::{AssistContext, Assists, TreeMutator},
35 // Assist: extract_function
37 // Extracts selected statements into new function.
55 // fn $0fun_name(n: i32) {
60 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
61 let range = ctx.selection_trimmed();
66 let node = ctx.covering_element();
67 if node.kind() == COMMENT {
68 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
72 let node = match node {
73 syntax::NodeOrToken::Node(n) => n,
74 syntax::NodeOrToken::Token(t) => t.parent()?,
76 let body = extraction_target(&node, range)?;
77 let container_info = body.analyze_container(&ctx.sema)?;
79 let (locals_used, self_param) = body.analyze(&ctx.sema);
81 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
82 let insert_after = node_to_insert_after(&body, anchor)?;
83 let module = ctx.sema.scope(&insert_after).module()?;
85 let ret_ty = body.return_ty(ctx)?;
86 let control_flow = body.external_control_flow(ctx, &container_info)?;
87 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
89 let target_range = body.text_range();
91 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
94 AssistId("extract_function", crate::AssistKind::RefactorExtract),
95 "Extract into function",
98 let outliving_locals: Vec<_> = ret_values.collect();
99 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
100 // We should not have variables that outlive body if we have expression block
105 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
108 name: make::name_ref("fun_name"),
115 mods: container_info,
118 let new_indent = IndentLevel::from_node(&insert_after);
119 let old_indent = fun.body.indent_level();
121 builder.replace(target_range, make_call(ctx, &fun, old_indent));
123 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
124 let insert_offset = insert_after.text_range().end();
126 if fn_def.contains("ControlFlow") {
127 let scope = match scope {
128 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
129 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
130 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
133 let control_flow_enum =
134 FamousDefs(&ctx.sema, Some(module.krate())).core_ops_ControlFlow();
136 if let Some(control_flow_enum) = control_flow_enum {
137 let mod_path = module.find_use_path_prefixed(
139 ModuleDef::from(control_flow_enum),
140 ctx.config.insert_use.prefix_kind,
143 if let Some(mod_path) = mod_path {
144 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
149 match ctx.config.snippet_cap {
150 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
151 None => builder.insert(insert_offset, fn_def),
157 /// Try to guess what user wants to extract
159 /// We have basically have two cases:
160 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
161 /// Then we can use `ast::Expr`
162 /// * We want a few statements for a block. E.g.
164 /// fn foo() -> i32 {
174 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
175 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
177 ast::Stmt::Item(_) => None,
178 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
179 node.parent().and_then(ast::StmtList::cast)?,
185 // Covering element returned the parent block of one or multiple statements that have been selected
186 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
187 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
188 if block_expr.syntax().text_range() == selection_range {
189 return FunctionBody::from_expr(block_expr.into());
193 // Extract the full statements.
194 return Some(FunctionBody::from_range(stmt_list, selection_range));
197 let expr = ast::Expr::cast(node.clone())?;
198 // A node got selected fully
199 if node.text_range() == selection_range {
200 return FunctionBody::from_expr(expr);
203 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
209 self_param: Option<ast::SelfParam>,
211 control_flow: ControlFlow,
214 outliving_locals: Vec<OutlivedLocal>,
227 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
235 #[derive(Debug, Eq, PartialEq)]
239 Tuple(Vec<hir::Type>),
242 /// Where to put extracted function definition
245 /// Extract free function and put right after current top-level function
247 /// Extract method and put right after current function in the impl-block
251 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
252 // probably be merged somehow.
255 kind: Option<FlowKind>,
260 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
261 #[derive(Clone, Debug)]
262 struct ContainerInfo {
265 parent_loop: Option<SyntaxNode>,
266 /// The function's return type, const's type etc.
267 ret_type: Option<hir::Type>,
270 /// Control flow that is exported from extracted function
282 #[derive(Debug, Clone)]
284 /// Return with value (`return $expr;`)
285 Return(Option<ast::Expr>),
289 /// Break with value (`break $expr;`)
290 Break(Option<ast::Expr>),
295 #[derive(Debug, Clone)]
298 Result { ty: hir::Type },
308 fn is_unit(&self) -> bool {
310 RetType::Expr(ty) => ty.is_unit(),
311 RetType::Stmt => true,
316 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
317 /// This is the future function body, the part that is being extracted.
321 Span { parent: ast::StmtList, text_range: TextRange },
325 struct OutlivedLocal {
327 mut_usage_outside_body: bool,
330 /// Container of local variable usages
332 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
333 struct LocalUsages(ide_db::search::UsageSearchResult);
336 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
338 Definition::Local(var)
340 .in_scope(SearchScope::single_file(ctx.file_id()))
345 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
346 self.0.iter().flat_map(|(_, rs)| rs)
351 fn return_type(&self, ctx: &AssistContext) -> FunType {
353 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
354 RetType::Expr(ty) => FunType::Single(ty.clone()),
355 RetType::Stmt => match self.outliving_locals.as_slice() {
357 [var] => FunType::Single(var.local.ty(ctx.db())),
359 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
360 FunType::Tuple(types)
368 fn is_ref(&self) -> bool {
369 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
374 fn kind(&self) -> ParamKind {
375 match (self.move_local, self.requires_mut, self.is_copy) {
376 (false, true, _) => ParamKind::MutRef,
377 (false, false, false) => ParamKind::SharedRef,
378 (true, true, _) => ParamKind::MutValue,
379 (_, false, _) => ParamKind::Value,
383 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
384 let var = path_expr_from_local(ctx, self.var);
386 ParamKind::Value | ParamKind::MutValue => var,
387 ParamKind::SharedRef => make::expr_ref(var, false),
388 ParamKind::MutRef => make::expr_ref(var, true),
392 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
393 let var = self.var.name(ctx.db()).unwrap().to_string();
394 let var_name = make::name(&var);
395 let pat = match self.kind() {
396 ParamKind::MutValue => make::ident_pat(false, true, var_name),
397 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
398 make::ext::simple_ident_pat(var_name)
402 let ty = make_ty(&self.ty, ctx, module);
403 let ty = match self.kind() {
404 ParamKind::Value | ParamKind::MutValue => ty,
405 ParamKind::SharedRef => make::ty_ref(ty, false),
406 ParamKind::MutRef => make::ty_ref(ty, true),
409 make::param(pat.into(), ty)
414 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
416 // We favour Result for `expr?`
417 return Some(TryKind::Result { ty });
419 let adt = ty.as_adt()?;
420 let name = adt.name(ctx.db());
421 // FIXME: use lang items to determine if it is std type or user defined
422 // E.g. if user happens to define type named `Option`, we would have false positive
423 match name.to_string().as_str() {
424 "Option" => Some(TryKind::Option),
425 "Result" => Some(TryKind::Result { ty }),
432 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
434 FlowKind::Return(_) => make::expr_return(expr),
435 FlowKind::Break(_) => make::expr_break(expr),
436 FlowKind::Try { .. } => {
437 stdx::never!("cannot have result handler with try");
438 expr.unwrap_or_else(|| make::expr_return(None))
440 FlowKind::Continue => {
441 stdx::always!(expr.is_none(), "continue with value is not possible");
442 make::expr_continue()
447 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
449 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
450 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
452 FlowKind::Try { .. } => {
453 stdx::never!("try does not have defined expr_ty");
462 fn parent(&self) -> Option<SyntaxNode> {
464 FunctionBody::Expr(expr) => expr.syntax().parent(),
465 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
469 fn from_expr(expr: ast::Expr) -> Option<Self> {
471 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
472 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
473 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
474 expr => Some(Self::Expr(expr)),
478 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
479 let mut text_range = parent
481 .map(|stmt| stmt.syntax().text_range())
482 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
483 .reduce(|acc, stmt| acc.cover(stmt));
484 if let Some(tail_range) = parent
486 .map(|it| it.syntax().text_range())
487 .filter(|&it| selected.intersect(it).is_some())
489 text_range = Some(match text_range {
490 Some(text_range) => text_range.cover(tail_range),
494 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
497 fn indent_level(&self) -> IndentLevel {
499 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
500 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
504 fn tail_expr(&self) -> Option<ast::Expr> {
506 FunctionBody::Expr(expr) => Some(expr.clone()),
507 FunctionBody::Span { parent, text_range } => {
508 let tail_expr = parent.tail_expr()?;
509 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
514 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
516 FunctionBody::Expr(expr) => walk_expr(expr, cb),
517 FunctionBody::Span { parent, text_range } => {
520 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
521 .filter_map(|stmt| match stmt {
522 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
523 ast::Stmt::Item(_) => None,
524 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
526 .for_each(|expr| walk_expr(&expr, cb));
527 if let Some(expr) = parent
529 .filter(|it| text_range.contains_range(it.syntax().text_range()))
531 walk_expr(&expr, cb);
537 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
539 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
540 FunctionBody::Span { parent, text_range } => {
543 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
544 .filter_map(|stmt| match stmt {
545 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
546 ast::Stmt::Item(_) => None,
547 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
549 .for_each(|expr| preorder_expr(&expr, cb));
550 if let Some(expr) = parent
552 .filter(|it| text_range.contains_range(it.syntax().text_range()))
554 preorder_expr(&expr, cb);
560 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
562 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
563 FunctionBody::Span { parent, text_range } => {
566 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
567 .for_each(|stmt| match stmt {
568 ast::Stmt::ExprStmt(expr_stmt) => {
569 if let Some(expr) = expr_stmt.expr() {
570 walk_patterns_in_expr(&expr, cb)
573 ast::Stmt::Item(_) => (),
574 ast::Stmt::LetStmt(stmt) => {
575 if let Some(pat) = stmt.pat() {
578 if let Some(expr) = stmt.initializer() {
579 walk_patterns_in_expr(&expr, cb);
583 if let Some(expr) = parent
585 .filter(|it| text_range.contains_range(it.syntax().text_range()))
587 walk_patterns_in_expr(&expr, cb);
593 fn text_range(&self) -> TextRange {
595 FunctionBody::Expr(expr) => expr.syntax().text_range(),
596 &FunctionBody::Span { text_range, .. } => text_range,
600 fn contains_range(&self, range: TextRange) -> bool {
601 self.text_range().contains_range(range)
604 fn precedes_range(&self, range: TextRange) -> bool {
605 self.text_range().end() <= range.start()
608 fn contains_node(&self, node: &SyntaxNode) -> bool {
609 self.contains_range(node.text_range())
614 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
615 /// whether it contains an await expression.
618 sema: &Semantics<RootDatabase>,
619 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
620 let mut self_param = None;
621 let mut res = FxIndexSet::default();
622 let mut cb = |name_ref: Option<_>| {
624 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
626 NameRefClass::Definition(Definition::Local(local_ref))
627 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
631 let InFile { file_id, value } = local_ref.source(sema.db);
632 // locals defined inside macros are not relevant to us
633 if !file_id.is_macro() {
635 Either::Right(it) => {
636 self_param.replace(it);
639 res.insert(local_ref);
644 self.walk_expr(&mut |expr| match expr {
645 ast::Expr::PathExpr(path_expr) => {
646 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
648 ast::Expr::MacroCall(call) => {
649 if let Some(tt) = call.token_tree() {
651 .children_with_tokens()
652 .flat_map(SyntaxElement::into_token)
653 .filter(|it| it.kind() == SyntaxKind::IDENT)
654 .flat_map(|t| sema.descend_into_macros(t))
655 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
663 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
664 let mut ancestors = self.parent()?.ancestors();
665 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
666 let mut parent_loop = None;
667 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
670 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
672 parent_loop.get_or_insert(loop_.syntax().clone());
675 let (is_const, expr, ty) = loop {
676 let anc = ancestors.next()?;
679 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
680 ast::BlockExpr(block_expr) => {
681 let (constness, block) = match block_expr.modifier() {
682 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
683 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
684 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
687 let expr = Some(ast::Expr::BlockExpr(block));
688 (constness, expr.clone(), infer_expr_opt(expr))
691 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
693 ast::Static(statik) => {
694 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
696 ast::ConstArg(ca) => {
697 (true, ca.expr(), infer_expr_opt(ca.expr()))
699 ast::Const(konst) => {
700 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
702 ast::ConstParam(cp) => {
703 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
705 ast::ConstBlockPat(cbp) => {
706 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
707 (true, expr.clone(), infer_expr_opt(expr))
709 ast::Variant(__) => return None,
710 ast::Meta(__) => return None,
711 ast::LoopExpr(it) => {
712 set_parent_loop(&it);
715 ast::ForExpr(it) => {
716 set_parent_loop(&it);
719 ast::WhileExpr(it) => {
720 set_parent_loop(&it);
727 let container_tail = match expr? {
728 ast::Expr::BlockExpr(block) => block.tail_expr(),
732 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
733 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
735 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
738 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
739 match self.tail_expr() {
740 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
741 None => Some(RetType::Stmt),
745 /// Local variables defined inside `body` that are accessed outside of it
748 ctx: &'a AssistContext,
750 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
751 let parent = parent.clone();
752 let range = self.text_range();
753 locals_defined_in_body(&ctx.sema, self)
755 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
758 /// Analyses the function body for external control flow.
759 fn external_control_flow(
762 container_info: &ContainerInfo,
763 ) -> Option<ControlFlow> {
764 let mut ret_expr = None;
765 let mut try_expr = None;
766 let mut break_expr = None;
767 let mut continue_expr = None;
768 let mut is_async = false;
769 let mut _is_unsafe = false;
771 let mut unsafe_depth = 0;
772 let mut loop_depth = 0;
774 self.preorder_expr(&mut |expr| {
775 let expr = match expr {
776 WalkEvent::Enter(e) => e,
777 WalkEvent::Leave(expr) => {
779 ast::Expr::LoopExpr(_)
780 | ast::Expr::ForExpr(_)
781 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
782 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
791 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
794 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
797 ast::Expr::ReturnExpr(it) => {
800 ast::Expr::TryExpr(it) => {
803 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
804 break_expr = Some(it);
806 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
807 continue_expr = Some(it);
809 ast::Expr::AwaitExpr(_) => is_async = true,
810 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
811 // to just lift that out of there
812 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
818 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
819 (Some(_), _, None, None) => {
820 let ret_ty = container_info.ret_type.clone()?;
821 let kind = TryKind::of_ty(ret_ty, ctx)?;
823 Some(FlowKind::Try { kind })
825 (Some(_), _, _, _) => {
826 cov_mark::hit!(external_control_flow_try_and_bc);
829 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
830 (None, Some(_), _, _) => {
831 cov_mark::hit!(external_control_flow_return_and_bc);
834 (None, None, Some(_), Some(_)) => {
835 cov_mark::hit!(external_control_flow_break_and_continue);
838 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
839 (None, None, None, Some(_)) => Some(FlowKind::Continue),
840 (None, None, None, None) => None,
843 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
846 /// find variables that should be extracted as params
848 /// Computes additional info that affects param type and mutability
849 fn extracted_function_params(
852 container_info: &ContainerInfo,
853 locals: impl Iterator<Item = Local>,
856 .map(|local| (local, local.source(ctx.db())))
857 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
858 .filter_map(|(local, src)| match src.value {
859 Either::Left(src) => Some((local, src)),
860 Either::Right(_) => {
861 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
866 let usages = LocalUsages::find_local_usages(ctx, var);
867 let ty = var.ty(ctx.db());
869 let defined_outside_parent_loop = container_info
872 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
874 let is_copy = ty.is_copy(ctx.db());
875 let has_usages = self.has_usages_after_body(&usages);
877 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
878 // We can move the value into the function call if it's not used after the call,
879 // if the var is not used but defined outside a loop we are extracting from we can't move it either
880 // as the function will reuse it in the next iteration.
881 let move_local = !has_usages && defined_outside_parent_loop;
882 Param { var, ty, move_local, requires_mut, is_copy }
887 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
888 usages.iter().any(|reference| self.precedes_range(reference.range))
892 /// checks if relevant var is used with `&mut` access inside body
893 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
896 .filter(|reference| body.contains_range(reference.range))
897 .any(|reference| reference_is_exclusive(reference, body, ctx))
900 /// checks if this reference requires `&mut` access inside node
901 fn reference_is_exclusive(
902 reference: &FileReference,
903 node: &dyn HasTokenAtOffset,
906 // we directly modify variable with set: `n = 0`, `n += 1`
907 if reference.category == Some(ReferenceCategory::Write) {
911 // we take `&mut` reference to variable: `&mut v`
912 let path = match path_element_of_reference(node, reference) {
914 None => return false,
917 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
920 /// checks if this expr requires `&mut` access, recurses on field access
921 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
922 if let ast::Expr::MacroCall(_) = expr {
923 // FIXME: expand macro and check output for mutable usages of the variable?
927 let parent = expr.syntax().parent()?;
929 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
930 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
931 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
936 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
937 return Some(ref_expr.mut_token().is_some());
940 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
941 let func = ctx.sema.resolve_method_call(&method_call)?;
942 let self_param = func.self_param(ctx.db())?;
943 let access = self_param.access(ctx.db());
945 return Some(matches!(access, hir::Access::Exclusive));
948 if let Some(field) = ast::FieldExpr::cast(parent) {
949 return expr_require_exclusive_access(ctx, &field.into());
955 trait HasTokenAtOffset {
956 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
959 impl HasTokenAtOffset for SyntaxNode {
960 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
961 SyntaxNode::token_at_offset(self, offset)
965 impl HasTokenAtOffset for FunctionBody {
966 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
968 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
969 FunctionBody::Span { parent, text_range } => {
970 match parent.syntax().token_at_offset(offset) {
971 TokenAtOffset::None => TokenAtOffset::None,
972 TokenAtOffset::Single(t) => {
973 if text_range.contains_range(t.text_range()) {
974 TokenAtOffset::Single(t)
979 TokenAtOffset::Between(a, b) => {
981 text_range.contains_range(a.text_range()),
982 text_range.contains_range(b.text_range()),
984 (true, true) => TokenAtOffset::Between(a, b),
985 (true, false) => TokenAtOffset::Single(a),
986 (false, true) => TokenAtOffset::Single(b),
987 (false, false) => TokenAtOffset::None,
996 /// find relevant `ast::Expr` for reference
1000 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1001 fn path_element_of_reference(
1002 node: &dyn HasTokenAtOffset,
1003 reference: &FileReference,
1004 ) -> Option<ast::Expr> {
1005 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1006 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1009 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
1010 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1014 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
1015 "unexpected expression type for variable usage: {:?}",
1021 /// list local variables defined inside `body`
1022 fn locals_defined_in_body(
1023 sema: &Semantics<RootDatabase>,
1024 body: &FunctionBody,
1025 ) -> FxIndexSet<Local> {
1026 // FIXME: this doesn't work well with macros
1027 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1028 let mut res = FxIndexSet::default();
1029 body.walk_pat(&mut |pat| {
1030 if let ast::Pat::IdentPat(pat) = pat {
1031 if let Some(local) = sema.to_def(&pat) {
1039 /// Returns usage details if local variable is used after(outside of) body
1040 fn local_outlives_body(
1041 ctx: &AssistContext,
1042 body_range: TextRange,
1044 parent: &SyntaxNode,
1045 ) -> Option<OutlivedLocal> {
1046 let usages = LocalUsages::find_local_usages(ctx, local);
1047 let mut has_mut_usages = false;
1048 let mut any_outlives = false;
1049 for usage in usages.iter() {
1050 if body_range.end() <= usage.range.start() {
1051 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1052 any_outlives |= true;
1054 break; // no need to check more elements we have all the info we wanted
1061 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1064 /// checks if the relevant local was defined before(outside of) body
1065 fn is_defined_outside_of_body(
1066 ctx: &AssistContext,
1067 body: &FunctionBody,
1068 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1070 src.file_id.original_file(ctx.db()) == ctx.file_id()
1071 && !body.contains_node(either_syntax(&src.value))
1074 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1076 Either::Left(pat) => pat.syntax(),
1077 Either::Right(it) => it.syntax(),
1081 /// find where to put extracted function definition
1083 /// Function should be put right after returned node
1084 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1085 let node = match body {
1086 FunctionBody::Expr(e) => e.syntax(),
1087 FunctionBody::Span { parent, .. } => parent.syntax(),
1089 let mut ancestors = node.ancestors().peekable();
1090 let mut last_ancestor = None;
1091 while let Some(next_ancestor) = ancestors.next() {
1092 match next_ancestor.kind() {
1093 SyntaxKind::SOURCE_FILE => break,
1094 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1095 SyntaxKind::ITEM_LIST => {
1096 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1100 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1103 SyntaxKind::ASSOC_ITEM_LIST => {
1104 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1110 last_ancestor = Some(next_ancestor);
1115 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1116 let ret_ty = fun.return_type(ctx);
1118 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1119 let name = fun.name.clone();
1120 let mut call_expr = if fun.self_param.is_some() {
1121 let self_arg = make::expr_path(make::ext::ident_path("self"));
1122 make::expr_method_call(self_arg, name, args)
1124 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1125 make::expr_call(func, args)
1128 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1130 if fun.control_flow.is_async {
1131 call_expr = make::expr_await(call_expr);
1133 let expr = handler.make_call_expr(call_expr).indent(indent);
1135 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1137 let mut buf = String::new();
1138 match fun.outliving_locals.as_slice() {
1141 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1144 buf.push_str("let (");
1145 let bindings = vars.iter().format_with(", ", |local, f| {
1146 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1148 format_to!(buf, "{}", bindings);
1149 buf.push_str(") = ");
1153 format_to!(buf, "{}", expr);
1154 let insert_comma = fun
1157 .and_then(ast::MatchArm::cast)
1158 .map_or(false, |it| it.comma_token().is_none());
1161 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1169 Try { kind: TryKind },
1170 If { action: FlowKind },
1171 IfOption { action: FlowKind },
1172 MatchOption { none: FlowKind },
1173 MatchResult { err: FlowKind },
1177 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1178 match &fun.control_flow.kind {
1179 None => FlowHandler::None,
1180 Some(flow_kind) => {
1181 let action = flow_kind.clone();
1182 if *ret_ty == FunType::Unit {
1184 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1185 FlowHandler::If { action }
1187 FlowKind::Return(_) | FlowKind::Break(_) => {
1188 FlowHandler::IfOption { action }
1190 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1194 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1195 FlowHandler::MatchOption { none: action }
1197 FlowKind::Return(_) | FlowKind::Break(_) => {
1198 FlowHandler::MatchResult { err: action }
1200 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1207 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1209 FlowHandler::None => call_expr,
1210 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1211 FlowHandler::If { action } => {
1212 let action = action.make_result_handler(None);
1213 let stmt = make::expr_stmt(action);
1214 let block = make::block_expr(iter::once(stmt.into()), None);
1215 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1216 let condition = make::condition(
1219 make::tuple_struct_pat(
1220 controlflow_break_path,
1221 iter::once(make::wildcard_pat().into()),
1226 make::expr_if(condition, block, None)
1228 FlowHandler::IfOption { action } => {
1229 let path = make::ext::ident_path("Some");
1230 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1231 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1232 let cond = make::condition(call_expr, Some(pattern.into()));
1233 let value = make::expr_path(make::ext::ident_path("value"));
1234 let action_expr = action.make_result_handler(Some(value));
1235 let action_stmt = make::expr_stmt(action_expr);
1236 let then = make::block_expr(iter::once(action_stmt.into()), None);
1237 make::expr_if(cond, then, None)
1239 FlowHandler::MatchOption { none } => {
1240 let some_name = "value";
1243 let path = make::ext::ident_path("Some");
1244 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1245 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1246 let value = make::expr_path(make::ext::ident_path(some_name));
1247 make::match_arm(iter::once(pat.into()), None, value)
1250 let path = make::ext::ident_path("None");
1251 let pat = make::path_pat(path);
1252 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1254 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1255 make::expr_match(call_expr, arms)
1257 FlowHandler::MatchResult { err } => {
1258 let ok_name = "value";
1259 let err_name = "value";
1262 let path = make::ext::ident_path("Ok");
1263 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1264 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1265 let value = make::expr_path(make::ext::ident_path(ok_name));
1266 make::match_arm(iter::once(pat.into()), None, value)
1269 let path = make::ext::ident_path("Err");
1270 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1271 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1272 let value = make::expr_path(make::ext::ident_path(err_name));
1274 iter::once(pat.into()),
1276 err.make_result_handler(Some(value)),
1279 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1280 make::expr_match(call_expr, arms)
1286 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1287 let name = var.name(ctx.db()).unwrap().to_string();
1288 make::expr_path(make::ext::ident_path(&name))
1292 ctx: &AssistContext,
1293 module: hir::Module,
1295 old_indent: IndentLevel,
1296 new_indent: IndentLevel,
1298 let mut fn_def = String::new();
1299 let params = fun.make_param_list(ctx, module);
1300 let ret_ty = fun.make_ret_ty(ctx, module);
1301 let body = make_body(ctx, old_indent, new_indent, fun);
1302 let const_kw = if fun.mods.is_const { "const " } else { "" };
1303 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1304 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1305 match ctx.config.snippet_cap {
1306 Some(_) => format_to!(
1308 "\n\n{}{}{}{}fn $0{}{}",
1318 "\n\n{}{}{}{}fn {}{}",
1327 if let Some(ret_ty) = ret_ty {
1328 format_to!(fn_def, " {}", ret_ty);
1330 format_to!(fn_def, " {}", body);
1336 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1337 let self_param = self.self_param.clone();
1338 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1339 make::param_list(self_param, params)
1342 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1343 let fun_ty = self.return_type(ctx);
1344 let handler = if self.mods.is_in_tail {
1347 FlowHandler::from_ret_ty(self, &fun_ty)
1349 let ret_ty = match &handler {
1350 FlowHandler::None => {
1351 if matches!(fun_ty, FunType::Unit) {
1354 fun_ty.make_ty(ctx, module)
1356 FlowHandler::Try { kind: TryKind::Option } => {
1357 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1359 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1360 let handler_ty = parent_ret_ty
1363 .map(|ty| make_ty(&ty, ctx, module))
1364 .unwrap_or_else(make::ty_placeholder);
1365 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1367 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1368 FlowHandler::IfOption { action } => {
1369 let handler_ty = action
1371 .map(|ty| make_ty(&ty, ctx, module))
1372 .unwrap_or_else(make::ty_placeholder);
1373 make::ext::ty_option(handler_ty)
1375 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1376 FlowHandler::MatchResult { err } => {
1377 let handler_ty = err
1379 .map(|ty| make_ty(&ty, ctx, module))
1380 .unwrap_or_else(make::ty_placeholder);
1381 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1384 Some(make::ret_type(ret_ty))
1389 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1391 FunType::Unit => make::ty_unit(),
1392 FunType::Single(ty) => make_ty(ty, ctx, module),
1393 FunType::Tuple(types) => match types.as_slice() {
1395 stdx::never!("tuple type with 0 elements");
1399 stdx::never!("tuple type with 1 element");
1400 make_ty(ty, ctx, module)
1403 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1404 make::ty_tuple(types)
1412 ctx: &AssistContext,
1413 old_indent: IndentLevel,
1414 new_indent: IndentLevel,
1416 ) -> ast::BlockExpr {
1417 let ret_ty = fun.return_type(ctx);
1418 let handler = if fun.mods.is_in_tail {
1421 FlowHandler::from_ret_ty(fun, &ret_ty)
1423 let block = match &fun.body {
1424 FunctionBody::Expr(expr) => {
1425 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1426 let expr = ast::Expr::cast(expr).unwrap();
1428 ast::Expr::BlockExpr(block) => {
1429 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1430 let block = block.dedent(old_indent);
1431 // Recreate the block for formatting consistency with other extracted functions.
1432 make::block_expr(block.statements(), block.tail_expr())
1435 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1437 make::block_expr(Vec::new(), Some(expr))
1441 FunctionBody::Span { parent, text_range } => {
1442 let mut elements: Vec<_> = parent
1445 .filter(|it| text_range.contains_range(it.text_range()))
1446 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1449 let mut tail_expr = match elements.pop() {
1450 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1451 elements.push(node);
1457 if tail_expr.is_none() {
1458 match fun.outliving_locals.as_slice() {
1461 tail_expr = Some(path_expr_from_local(ctx, var.local));
1464 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1465 let expr = make::expr_tuple(exprs);
1466 tail_expr = Some(expr);
1471 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1472 Some(stmt) => Some(stmt),
1474 stdx::never!("block contains non-statement");
1479 let body_indent = IndentLevel(1);
1480 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1481 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1483 make::block_expr(elements, tail_expr)
1487 let block = match &handler {
1488 FlowHandler::None => block,
1489 FlowHandler::Try { kind } => {
1490 let block = with_default_tail_expr(block, make::expr_unit());
1491 map_tail_expr(block, |tail_expr| {
1492 let constructor = match kind {
1493 TryKind::Option => "Some",
1494 TryKind::Result { .. } => "Ok",
1496 let func = make::expr_path(make::ext::ident_path(constructor));
1497 let args = make::arg_list(iter::once(tail_expr));
1498 make::expr_call(func, args)
1501 FlowHandler::If { .. } => {
1502 let controlflow_continue = make::expr_call(
1503 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1504 make::arg_list(iter::once(make::expr_unit())),
1506 with_tail_expr(block, controlflow_continue.into())
1508 FlowHandler::IfOption { .. } => {
1509 let none = make::expr_path(make::ext::ident_path("None"));
1510 with_tail_expr(block, none)
1512 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1513 let some = make::expr_path(make::ext::ident_path("Some"));
1514 let args = make::arg_list(iter::once(tail_expr));
1515 make::expr_call(some, args)
1517 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1518 let ok = make::expr_path(make::ext::ident_path("Ok"));
1519 let args = make::arg_list(iter::once(tail_expr));
1520 make::expr_call(ok, args)
1524 block.indent(new_indent)
1527 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1528 let tail_expr = match block.tail_expr() {
1529 Some(tail_expr) => tail_expr,
1530 None => return block,
1532 make::block_expr(block.statements(), Some(f(tail_expr)))
1535 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1536 match block.tail_expr() {
1538 None => make::block_expr(block.statements(), Some(tail_expr)),
1542 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1543 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1544 let stmts = block.statements().chain(stmt_tail);
1545 make::block_expr(stmts, Some(tail_expr))
1548 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1549 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1552 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1553 let ty_str = format_type(ty, ctx, module);
1557 fn rewrite_body_segment(
1558 ctx: &AssistContext,
1560 handler: &FlowHandler,
1561 syntax: &SyntaxNode,
1563 let syntax = fix_param_usages(ctx, params, syntax);
1564 update_external_control_flow(handler, &syntax);
1568 /// change all usages to account for added `&`/`&mut` for some params
1569 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1570 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1572 let tm = TreeMutator::new(syntax);
1574 for param in params {
1575 if !param.kind().is_ref() {
1579 let usages = LocalUsages::find_local_usages(ctx, param.var);
1582 .filter(|reference| syntax.text_range().contains_range(reference.range))
1583 .filter_map(|reference| path_element_of_reference(syntax, reference))
1584 .map(|expr| tm.make_mut(&expr));
1586 usages_for_param.push((param, usages.collect()));
1589 let res = tm.make_syntax_mut(syntax);
1591 for (param, usages) in usages_for_param {
1592 for usage in usages {
1593 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1594 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1597 Some(ast::Expr::RefExpr(node))
1598 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1600 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1602 Some(ast::Expr::RefExpr(node))
1603 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1605 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1608 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1609 ted::replace(usage.syntax(), p.syntax())
1618 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1619 let mut nested_loop = None;
1620 let mut nested_scope = None;
1621 for event in syntax.preorder() {
1623 WalkEvent::Enter(e) => match e.kind() {
1624 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1625 if nested_loop.is_none() {
1626 nested_loop = Some(e.clone());
1631 | SyntaxKind::STATIC
1633 | SyntaxKind::MODULE => {
1634 if nested_scope.is_none() {
1635 nested_scope = Some(e.clone());
1640 WalkEvent::Leave(e) => {
1641 if nested_scope.is_none() {
1642 if let Some(expr) = ast::Expr::cast(e.clone()) {
1644 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1645 let expr = return_expr.expr();
1646 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1647 ted::replace(return_expr.syntax(), replacement.syntax())
1650 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1651 let expr = break_expr.expr();
1652 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1653 ted::replace(break_expr.syntax(), replacement.syntax())
1656 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1657 if let Some(replacement) = make_rewritten_flow(handler, None) {
1658 ted::replace(continue_expr.syntax(), replacement.syntax())
1668 if nested_loop.as_ref() == Some(&e) {
1671 if nested_scope.as_ref() == Some(&e) {
1672 nested_scope = None;
1679 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1680 let value = match handler {
1681 FlowHandler::None | FlowHandler::Try { .. } => return None,
1682 FlowHandler::If { .. } => make::expr_call(
1683 make::expr_path(make::path_from_text("ControlFlow::Break")),
1684 make::arg_list(iter::once(make::expr_unit())),
1686 FlowHandler::IfOption { .. } => {
1687 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1688 let args = make::arg_list(iter::once(expr));
1689 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1691 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1692 FlowHandler::MatchResult { .. } => {
1693 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1694 let args = make::arg_list(iter::once(expr));
1695 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1698 Some(make::expr_return(Some(value)).clone_for_update())
1703 use crate::tests::{check_assist, check_assist_not_applicable};
1708 fn no_args_from_binary_expr() {
1721 fn $0fun_name() -> i32 {
1729 fn no_args_from_binary_expr_in_module() {
1745 fn $0fun_name() -> i32 {
1754 fn no_args_from_binary_expr_indented() {
1767 fn $0fun_name() -> i32 {
1775 fn no_args_from_stmt_with_last_expr() {
1791 fn $0fun_name() -> i32 {
1800 fn no_args_from_stmt_unit() {
1848 fn no_args_if_else() {
1853 $0if true { 1 } else { 2 }$0
1861 fn $0fun_name() -> i32 {
1862 if true { 1 } else { 2 }
1869 fn no_args_if_let_else() {
1874 $0if let true = false { 1 } else { 2 }$0
1882 fn $0fun_name() -> i32 {
1883 if let true = false { 1 } else { 2 }
1890 fn no_args_match() {
1906 fn $0fun_name() -> i32 {
1917 fn no_args_while() {
1943 $0for v in &[0, 1] { }$0
1952 for v in &[0, 1] { }
1959 fn no_args_from_loop_unit() {
1974 fn $0fun_name() -> ! {
1984 fn no_args_from_loop_with_return() {
2000 fn $0fun_name() -> i32 {
2011 fn no_args_from_match() {
2016 let v: i32 = $0match Some(1) {
2024 let v: i32 = fun_name();
2027 fn $0fun_name() -> i32 {
2038 fn extract_partial_block_single_line() {
2044 let mut v = $0n * n;$0
2051 let mut v = fun_name(n);
2055 fn $0fun_name(n: i32) -> i32 {
2064 fn extract_partial_block() {
2071 let mut v = m $0* n;
2081 let (mut v, mut w) = fun_name(m, n);
2086 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2096 fn argument_form_expr() {
2111 fn $0fun_name(n: u32) -> u32 {
2119 fn argument_used_twice_form_expr() {
2134 fn $0fun_name(n: u32) -> u32 {
2142 fn two_arguments_form_expr() {
2159 fn $0fun_name(n: u32, m: u32) -> u32 {
2167 fn argument_and_locals() {
2183 fn $0fun_name(n: u32) -> u32 {
2192 fn in_comment_is_not_applicable() {
2193 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2194 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2198 fn part_of_expr_stmt() {
2211 fn $0fun_name() -> i32 {
2219 fn function_expr() {
2240 fn extract_from_nested() {
2246 let tuple = match x {
2247 true => ($02 + 2$0, true)
2255 let tuple = match x {
2256 true => (fun_name(), true)
2261 fn $0fun_name() -> i32 {
2269 fn param_from_closure() {
2274 let lambda = |x: u32| $0x * 2$0;
2279 let lambda = |x: u32| fun_name(x);
2282 fn $0fun_name(x: u32) -> u32 {
2290 fn extract_return_stmt() {
2303 fn $0fun_name() -> u32 {
2311 fn does_not_add_extra_whitespace() {
2328 fn $0fun_name() -> u32 {
2353 fn $0fun_name() -> i32 {
2366 let v = $00f32 as u32$0;
2374 fn $0fun_name() -> u32 {
2382 fn return_not_applicable() {
2383 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2387 fn method_to_freestanding() {
2394 fn foo(&self) -> i32 {
2403 fn foo(&self) -> i32 {
2408 fn $0fun_name() -> i32 {
2416 fn method_with_reference() {
2420 struct S { f: i32 };
2423 fn foo(&self) -> i32 {
2429 struct S { f: i32 };
2432 fn foo(&self) -> i32 {
2436 fn $0fun_name(&self) -> i32 {
2445 fn method_with_mut() {
2449 struct S { f: i32 };
2458 struct S { f: i32 };
2465 fn $0fun_name(&mut self) {
2474 fn variable_defined_inside_and_used_after_no_ret() {
2487 let k = fun_name(n);
2491 fn $0fun_name(n: i32) -> i32 {
2500 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2506 $0let mut k = n * n;$0
2513 let mut k = fun_name(n);
2517 fn $0fun_name(n: i32) -> i32 {
2526 fn two_variables_defined_inside_and_used_after_no_ret() {
2540 let (k, m) = fun_name(n);
2544 fn $0fun_name(n: i32) -> (i32, i32) {
2554 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2560 $0let mut k = n * n;
2571 let (mut k, mut m, o) = fun_name(n);
2576 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2588 fn nontrivial_patterns_define_variables() {
2592 struct Counter(i32);
2594 $0let Counter(n) = Counter(0);$0
2599 struct Counter(i32);
2605 fn $0fun_name() -> i32 {
2606 let Counter(n) = Counter(0);
2614 fn struct_with_two_fields_pattern_define_variables() {
2618 struct Counter { n: i32, m: i32 };
2620 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2625 struct Counter { n: i32, m: i32 };
2627 let (n, k) = fun_name();
2631 fn $0fun_name() -> (i32, i32) {
2632 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2640 fn mut_var_from_outer_scope() {
2657 fn $0fun_name(n: &mut i32) {
2665 fn mut_field_from_outer_scope() {
2671 let mut c = C { n: 0 };
2679 let mut c = C { n: 0 };
2684 fn $0fun_name(c: &mut C) {
2692 fn mut_nested_field_from_outer_scope() {
2699 let mut c = C { p: P { n: 0 } };
2700 let mut v = C { p: P { n: 0 } };
2701 let u = C { p: P { n: 0 } };
2703 let r = &mut v.p.n;$0
2704 let m = c.p.n + v.p.n + u.p.n;
2711 let mut c = C { p: P { n: 0 } };
2712 let mut v = C { p: P { n: 0 } };
2713 let u = C { p: P { n: 0 } };
2714 fun_name(&mut c, &u, &mut v);
2715 let m = c.p.n + v.p.n + u.p.n;
2718 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2727 fn mut_param_many_usages_stmt() {
2733 fn succ(&self) -> Self;
2734 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2737 fn succ(&self) -> Self { *self + 1 }
2756 fn succ(&self) -> Self;
2757 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2760 fn succ(&self) -> Self { *self + 1 }
2768 fn $0fun_name(n: &mut i32) {
2784 fn mut_param_many_usages_expr() {
2790 fn succ(&self) -> Self;
2791 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2794 fn succ(&self) -> Self { *self + 1 }
2815 fn succ(&self) -> Self;
2816 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2819 fn succ(&self) -> Self { *self + 1 }
2827 fn $0fun_name(n: &mut i32) {
2843 fn mut_param_by_value() {
2858 fn $0fun_name(mut n: i32) {
2866 fn mut_param_because_of_mut_ref() {
2884 fn $0fun_name(n: &mut i32) {
2893 fn mut_param_by_value_because_of_mut_ref() {
2909 fn $0fun_name(mut n: i32) {
2918 fn mut_method_call() {
2926 fn inc(&mut self) { *self += 1 }
2938 fn inc(&mut self) { *self += 1 }
2945 fn $0fun_name(mut n: i32) {
2953 fn shared_method_call() {
2961 fn succ(&self) { *self + 1 }
2973 fn succ(&self) { *self + 1 }
2980 fn $0fun_name(n: i32) {
2988 fn mut_method_call_with_other_receiver() {
2993 fn inc(&mut self, n: i32);
2996 fn inc(&mut self, n: i32) { *self += n }
3006 fn inc(&mut self, n: i32);
3009 fn inc(&mut self, n: i32) { *self += n }
3016 fn $0fun_name(n: i32) {
3025 fn non_copy_without_usages_after() {
3029 struct Counter(i32);
3036 struct Counter(i32);
3042 fn $0fun_name(c: Counter) {
3050 fn non_copy_used_after() {
3054 struct Counter(i32);
3062 struct Counter(i32);
3069 fn $0fun_name(c: &Counter) {
3077 fn copy_used_after() {
3095 fn $0fun_name(n: i32) {
3103 fn copy_custom_used_after() {
3107 //- minicore: copy, derive
3108 #[derive(Clone, Copy)]
3109 struct Counter(i32);
3117 #[derive(Clone, Copy)]
3118 struct Counter(i32);
3125 fn $0fun_name(c: Counter) {
3133 fn indented_stmts() {
3164 fn indented_stmts_inside_mod() {
3203 //- minicore: option
3218 let k = match fun_name(n) {
3219 Some(value) => value,
3226 fn $0fun_name(n: i32) -> Option<i32> {
3237 fn return_to_parent() {
3241 //- minicore: copy, result
3253 let k = match fun_name(n) {
3255 Err(value) => return value,
3260 fn $0fun_name(n: i32) -> Result<i32, i64> {
3271 fn break_and_continue() {
3272 cov_mark::check!(external_control_flow_break_and_continue);
3273 check_assist_not_applicable(
3292 fn return_and_break() {
3293 cov_mark::check!(external_control_flow_return_and_bc);
3294 check_assist_not_applicable(
3313 fn break_loop_with_if() {
3329 use core::ops::ControlFlow;
3334 if let ControlFlow::Break(_) = fun_name(&mut n) {
3341 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3343 return ControlFlow::Break(());
3345 ControlFlow::Continue(())
3352 fn break_loop_nested() {
3369 use core::ops::ControlFlow;
3374 if let ControlFlow::Break(_) = fun_name(n) {
3381 fn $0fun_name(n: i32) -> ControlFlow<()> {
3384 return ControlFlow::Break(());
3386 ControlFlow::Continue(())
3393 fn return_from_nested_loop() {
3413 let m = match fun_name() {
3414 Some(value) => value,
3421 fn $0fun_name() -> Option<i32> {
3434 fn break_from_nested_loop() {
3459 fn $0fun_name() -> i32 {
3472 fn break_from_nested_and_outer_loops() {
3495 let m = match fun_name() {
3496 Some(value) => value,
3503 fn $0fun_name() -> Option<i32> {
3519 fn return_from_nested_fn() {
3544 fn $0fun_name() -> i32 {
3557 fn break_with_value() {
3577 if let Some(value) = fun_name() {
3584 fn $0fun_name() -> Option<i32> {
3597 fn break_with_value_and_return() {
3617 let m = match fun_name() {
3619 Err(value) => break value,
3625 fn $0fun_name() -> Result<i32, i64> {
3642 //- minicore: option
3643 fn bar() -> Option<i32> { None }
3644 fn foo() -> Option<()> {
3653 fn bar() -> Option<i32> { None }
3654 fn foo() -> Option<()> {
3656 let m = fun_name()?;
3661 fn $0fun_name() -> Option<i32> {
3671 fn try_option_unit() {
3675 //- minicore: option
3676 fn foo() -> Option<()> {
3685 fn foo() -> Option<()> {
3692 fn $0fun_name() -> Option<()> {
3706 //- minicore: result
3707 fn foo() -> Result<(), i64> {
3716 fn foo() -> Result<(), i64> {
3718 let m = fun_name()?;
3723 fn $0fun_name() -> Result<i32, i64> {
3733 fn try_option_with_return() {
3737 //- minicore: option
3738 fn foo() -> Option<()> {
3750 fn foo() -> Option<()> {
3752 let m = fun_name()?;
3757 fn $0fun_name() -> Option<i32> {
3770 fn try_result_with_return() {
3774 //- minicore: result
3775 fn foo() -> Result<(), i64> {
3787 fn foo() -> Result<(), i64> {
3789 let m = fun_name()?;
3794 fn $0fun_name() -> Result<i32, i64> {
3807 fn try_and_break() {
3808 cov_mark::check!(external_control_flow_try_and_bc);
3809 check_assist_not_applicable(
3812 //- minicore: option
3813 fn foo() -> Option<()> {
3829 fn try_and_return_ok() {
3833 //- minicore: result
3834 fn foo() -> Result<(), i64> {
3846 fn foo() -> Result<(), i64> {
3848 let m = fun_name()?;
3853 fn $0fun_name() -> Result<i32, i64> {
3866 fn param_usage_in_macro() {
3871 ($val:expr) => { $val };
3876 $0let k = n * m!(n);$0
3882 ($val:expr) => { $val };
3887 let k = fun_name(n);
3891 fn $0fun_name(n: i32) -> i32 {
3900 fn extract_with_await() {
3905 $0some_function().await;$0
3908 async fn some_function() {
3917 async fn $0fun_name() {
3918 some_function().await;
3921 async fn some_function() {
3929 fn extract_with_await_and_result_not_producing_match_expr() {
3933 async fn foo() -> Result<(), ()> {
3939 async fn foo() -> Result<(), ()> {
3943 async fn $0fun_name() -> _ {
3952 fn extract_with_await_and_result_producing_match_expr() {
3956 async fn foo() -> i32 {
3959 let k = async { 1 }.await;
3969 async fn foo() -> i32 {
3972 let m = match fun_name().await {
3974 Err(value) => break value,
3980 async fn $0fun_name() -> Result<i32, i32> {
3981 let k = async { 1 }.await;
3993 fn extract_with_await_in_args() {
3998 $0function_call("a", some_function().await);$0
4001 async fn some_function() {
4010 async fn $0fun_name() {
4011 function_call("a", some_function().await);
4014 async fn some_function() {
4022 fn extract_does_not_extract_standalone_blocks() {
4023 check_assist_not_applicable(
4032 fn extract_adds_comma_for_match_arm() {
4051 fn $0fun_name() -> i32 {
4074 fn $0fun_name() -> i32 {
4082 fn extract_does_not_tear_comments_apart() {
4109 fn extract_does_not_wrap_res_in_res() {
4113 //- minicore: result
4114 fn foo() -> Result<(), i64> {
4115 $0Result::<i32, i64>::Ok(0)?;
4120 fn foo() -> Result<(), i64> {
4124 fn $0fun_name() -> Result<(), i64> {
4125 Result::<i32, i64>::Ok(0)?;
4133 fn extract_knows_const() {
4146 const fn $0fun_name() {
4163 const fn $0fun_name() {
4171 fn extract_does_not_move_outer_loop_vars() {
4190 fn $0fun_name(x: &mut i32) {
4213 fn $0fun_name(mut x: i32) {
4240 fn $0fun_name(x: &mut i32) {
4247 // regression test for #9822
4249 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4255 fn foo(&mut self) {}
4269 fn foo(&mut self) {}
4280 fn $0fun_name(y: &mut Foo) {
4288 fn extract_with_macro_arg() {
4293 ($val:expr) => { $val };
4302 ($val:expr) => { $val };
4309 fn $0fun_name(bar: &str) {
4317 fn unresolveable_types_default_to_placeholder() {
4322 let a = __unresolved;
4328 let a = __unresolved;
4329 let _ = fun_name(a);
4332 fn $0fun_name(a: _) -> _ {