6 HasSource, HirDisplay, InFile, Local, ModuleDef, PathResolution, Semantics, TypeInfo, TypeParam,
9 defs::{Definition, NameRefClass},
10 famous_defs::FamousDefs,
11 helpers::mod_path_to_ast,
12 imports::insert_use::{insert_use, ImportScope},
13 search::{FileReference, ReferenceCategory, SearchScope},
14 syntax_helpers::node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
15 FxIndexSet, RootDatabase,
17 use itertools::Itertools;
22 edit::{AstNodeEdit, IndentLevel},
23 AstNode, HasGenericParams,
25 match_ast, ted, SyntaxElement,
26 SyntaxKind::{self, COMMENT},
27 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
31 assist_context::{AssistContext, Assists, TreeMutator},
32 utils::generate_impl_text,
36 // Assist: extract_function
38 // Extracts selected statements and comments into new function.
57 // fn $0fun_name(n: i32) {
63 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
64 let range = ctx.selection_trimmed();
69 let node = ctx.covering_element();
70 if node.kind() == COMMENT {
71 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
75 let node = match node {
76 syntax::NodeOrToken::Node(n) => n,
77 syntax::NodeOrToken::Token(t) => t.parent()?,
80 let body = extraction_target(&node, range)?;
81 let container_info = body.analyze_container(&ctx.sema)?;
83 let (locals_used, self_param) = body.analyze(&ctx.sema);
85 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
86 let insert_after = node_to_insert_after(&body, anchor)?;
87 let semantics_scope = ctx.sema.scope(&insert_after)?;
88 let module = semantics_scope.module();
90 let ret_ty = body.return_ty(ctx)?;
91 let control_flow = body.external_control_flow(ctx, &container_info)?;
92 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
94 let target_range = body.text_range();
96 let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
99 AssistId("extract_function", crate::AssistKind::RefactorExtract),
100 "Extract into function",
103 let outliving_locals: Vec<_> = ret_values.collect();
104 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
105 // We should not have variables that outlive body if we have expression block
110 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
112 let extracted_from_trait_impl = body.extracted_from_trait_impl();
114 let name = make_function_name(&semantics_scope);
124 mods: container_info,
127 let new_indent = IndentLevel::from_node(&insert_after);
128 let old_indent = fun.body.indent_level();
130 builder.replace(target_range, make_call(ctx, &fun, old_indent));
132 let fn_def = match fun.self_param_adt(ctx) {
133 Some(adt) if extracted_from_trait_impl => {
134 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent + 1);
135 generate_impl_text(&adt, &fn_def).replace("{\n\n", "{")
137 _ => format_function(ctx, module, &fun, old_indent, new_indent),
140 if fn_def.contains("ControlFlow") {
141 let scope = match scope {
142 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
143 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
144 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
147 let control_flow_enum =
148 FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();
150 if let Some(control_flow_enum) = control_flow_enum {
151 let mod_path = module.find_use_path_prefixed(
153 ModuleDef::from(control_flow_enum),
154 ctx.config.insert_use.prefix_kind,
157 if let Some(mod_path) = mod_path {
158 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
163 let insert_offset = insert_after.text_range().end();
165 match ctx.config.snippet_cap {
166 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
167 None => builder.insert(insert_offset, fn_def),
173 fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef {
174 let mut names_in_scope = vec![];
175 semantics_scope.process_all_names(&mut |name, _| names_in_scope.push(name.to_string()));
177 let default_name = "fun_name";
179 let mut name = default_name.to_string();
181 while names_in_scope.contains(&name) {
183 name = format!("{}{}", &default_name, counter)
185 make::name_ref(&name)
188 /// Try to guess what user wants to extract
190 /// We have basically have two cases:
191 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
192 /// Then we can use `ast::Expr`
193 /// * We want a few statements for a block. E.g.
195 /// fn foo() -> i32 {
205 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
206 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
208 ast::Stmt::Item(_) => None,
209 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
210 node.parent().and_then(ast::StmtList::cast)?,
216 // Covering element returned the parent block of one or multiple statements that have been selected
217 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
218 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
219 if block_expr.syntax().text_range() == selection_range {
220 return FunctionBody::from_expr(block_expr.into());
224 // Extract the full statements.
225 return Some(FunctionBody::from_range(stmt_list, selection_range));
228 let expr = ast::Expr::cast(node.clone())?;
229 // A node got selected fully
230 if node.text_range() == selection_range {
231 return FunctionBody::from_expr(expr);
234 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
240 self_param: Option<ast::SelfParam>,
242 control_flow: ControlFlow,
245 outliving_locals: Vec<OutlivedLocal>,
258 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
266 #[derive(Debug, Eq, PartialEq)]
270 Tuple(Vec<hir::Type>),
273 /// Where to put extracted function definition
276 /// Extract free function and put right after current top-level function
278 /// Extract method and put right after current function in the impl-block
282 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
283 // probably be merged somehow.
286 kind: Option<FlowKind>,
291 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
292 #[derive(Clone, Debug)]
293 struct ContainerInfo {
296 parent_loop: Option<SyntaxNode>,
297 /// The function's return type, const's type etc.
298 ret_type: Option<hir::Type>,
299 generic_param_lists: Vec<ast::GenericParamList>,
300 where_clauses: Vec<ast::WhereClause>,
303 /// Control flow that is exported from extracted function
315 #[derive(Debug, Clone)]
317 /// Return with value (`return $expr;`)
318 Return(Option<ast::Expr>),
322 /// Break with label and value (`break 'label $expr;`)
323 Break(Option<ast::Lifetime>, Option<ast::Expr>),
324 /// Continue with label (`continue 'label;`)
325 Continue(Option<ast::Lifetime>),
328 #[derive(Debug, Clone)]
331 Result { ty: hir::Type },
341 fn is_unit(&self) -> bool {
343 RetType::Expr(ty) => ty.is_unit(),
344 RetType::Stmt => true,
349 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
350 /// This is the future function body, the part that is being extracted.
354 Span { parent: ast::StmtList, text_range: TextRange },
358 struct OutlivedLocal {
360 mut_usage_outside_body: bool,
363 /// Container of local variable usages
365 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
366 struct LocalUsages(ide_db::search::UsageSearchResult);
369 fn find_local_usages(ctx: &AssistContext<'_>, var: Local) -> Self {
371 Definition::Local(var)
373 .in_scope(SearchScope::single_file(ctx.file_id()))
378 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
379 self.0.iter().flat_map(|(_, rs)| rs)
384 fn return_type(&self, ctx: &AssistContext<'_>) -> FunType {
386 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
387 RetType::Expr(ty) => FunType::Single(ty.clone()),
388 RetType::Stmt => match self.outliving_locals.as_slice() {
390 [var] => FunType::Single(var.local.ty(ctx.db())),
392 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
393 FunType::Tuple(types)
399 fn self_param_adt(&self, ctx: &AssistContext<'_>) -> Option<ast::Adt> {
400 let self_param = self.self_param.as_ref()?;
401 let def = ctx.sema.to_def(self_param)?;
402 let adt = def.ty(ctx.db()).strip_references().as_adt()?;
403 let InFile { file_id: _, value } = adt.source(ctx.db())?;
409 fn is_ref(&self) -> bool {
410 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
415 fn kind(&self) -> ParamKind {
416 match (self.move_local, self.requires_mut, self.is_copy) {
417 (false, true, _) => ParamKind::MutRef,
418 (false, false, false) => ParamKind::SharedRef,
419 (true, true, _) => ParamKind::MutValue,
420 (_, false, _) => ParamKind::Value,
424 fn to_arg(&self, ctx: &AssistContext<'_>) -> ast::Expr {
425 let var = path_expr_from_local(ctx, self.var);
427 ParamKind::Value | ParamKind::MutValue => var,
428 ParamKind::SharedRef => make::expr_ref(var, false),
429 ParamKind::MutRef => make::expr_ref(var, true),
433 fn to_param(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Param {
434 let var = self.var.name(ctx.db()).to_string();
435 let var_name = make::name(&var);
436 let pat = match self.kind() {
437 ParamKind::MutValue => make::ident_pat(false, true, var_name),
438 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
439 make::ext::simple_ident_pat(var_name)
443 let ty = make_ty(&self.ty, ctx, module);
444 let ty = match self.kind() {
445 ParamKind::Value | ParamKind::MutValue => ty,
446 ParamKind::SharedRef => make::ty_ref(ty, false),
447 ParamKind::MutRef => make::ty_ref(ty, true),
450 make::param(pat.into(), ty)
455 fn of_ty(ty: hir::Type, ctx: &AssistContext<'_>) -> Option<TryKind> {
457 // We favour Result for `expr?`
458 return Some(TryKind::Result { ty });
460 let adt = ty.as_adt()?;
461 let name = adt.name(ctx.db());
462 // FIXME: use lang items to determine if it is std type or user defined
463 // E.g. if user happens to define type named `Option`, we would have false positive
464 match name.to_string().as_str() {
465 "Option" => Some(TryKind::Option),
466 "Result" => Some(TryKind::Result { ty }),
473 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
475 FlowKind::Return(_) => make::expr_return(expr),
476 FlowKind::Break(label, _) => make::expr_break(label.clone(), expr),
477 FlowKind::Try { .. } => {
478 stdx::never!("cannot have result handler with try");
479 expr.unwrap_or_else(|| make::expr_return(None))
481 FlowKind::Continue(label) => {
482 stdx::always!(expr.is_none(), "continue with value is not possible");
483 make::expr_continue(label.clone())
488 fn expr_ty(&self, ctx: &AssistContext<'_>) -> Option<hir::Type> {
490 FlowKind::Return(Some(expr)) | FlowKind::Break(_, Some(expr)) => {
491 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
493 FlowKind::Try { .. } => {
494 stdx::never!("try does not have defined expr_ty");
503 fn parent(&self) -> Option<SyntaxNode> {
505 FunctionBody::Expr(expr) => expr.syntax().parent(),
506 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
510 fn node(&self) -> &SyntaxNode {
512 FunctionBody::Expr(e) => e.syntax(),
513 FunctionBody::Span { parent, .. } => parent.syntax(),
517 fn extracted_from_trait_impl(&self) -> bool {
518 match self.node().ancestors().find_map(ast::Impl::cast) {
519 Some(c) => return c.trait_().is_some(),
524 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
526 FunctionBody::Expr(expr) => expr.syntax().descendants(),
527 FunctionBody::Span { parent, .. } => parent.syntax().descendants(),
531 fn descendant_paths(&self) -> impl Iterator<Item = ast::Path> {
532 self.descendants().filter_map(|node| {
535 ast::Path(it) => Some(it),
542 fn from_expr(expr: ast::Expr) -> Option<Self> {
544 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
545 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
546 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
547 expr => Some(Self::Expr(expr)),
551 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
552 let full_body = parent.syntax().children_with_tokens();
554 let mut text_range = full_body
555 .filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
556 .map(|element| element.text_range())
557 .filter(|&range| selected.intersect(range).filter(|it| !it.is_empty()).is_some())
558 .reduce(|acc, stmt| acc.cover(stmt));
560 if let Some(tail_range) = parent
562 .map(|it| it.syntax().text_range())
563 .filter(|&it| selected.intersect(it).is_some())
565 text_range = Some(match text_range {
566 Some(text_range) => text_range.cover(tail_range),
570 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
573 fn indent_level(&self) -> IndentLevel {
575 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
576 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
580 fn tail_expr(&self) -> Option<ast::Expr> {
582 FunctionBody::Expr(expr) => Some(expr.clone()),
583 FunctionBody::Span { parent, text_range } => {
584 let tail_expr = parent.tail_expr()?;
585 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
590 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
592 FunctionBody::Expr(expr) => walk_expr(expr, cb),
593 FunctionBody::Span { parent, text_range } => {
596 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
597 .filter_map(|stmt| match stmt {
598 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
599 ast::Stmt::Item(_) => None,
600 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
602 .for_each(|expr| walk_expr(&expr, cb));
603 if let Some(expr) = parent
605 .filter(|it| text_range.contains_range(it.syntax().text_range()))
607 walk_expr(&expr, cb);
613 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
615 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
616 FunctionBody::Span { parent, text_range } => {
619 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
620 .filter_map(|stmt| match stmt {
621 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
622 ast::Stmt::Item(_) => None,
623 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
625 .for_each(|expr| preorder_expr(&expr, cb));
626 if let Some(expr) = parent
628 .filter(|it| text_range.contains_range(it.syntax().text_range()))
630 preorder_expr(&expr, cb);
636 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
638 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
639 FunctionBody::Span { parent, text_range } => {
642 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
643 .for_each(|stmt| match stmt {
644 ast::Stmt::ExprStmt(expr_stmt) => {
645 if let Some(expr) = expr_stmt.expr() {
646 walk_patterns_in_expr(&expr, cb)
649 ast::Stmt::Item(_) => (),
650 ast::Stmt::LetStmt(stmt) => {
651 if let Some(pat) = stmt.pat() {
654 if let Some(expr) = stmt.initializer() {
655 walk_patterns_in_expr(&expr, cb);
659 if let Some(expr) = parent
661 .filter(|it| text_range.contains_range(it.syntax().text_range()))
663 walk_patterns_in_expr(&expr, cb);
669 fn text_range(&self) -> TextRange {
671 FunctionBody::Expr(expr) => expr.syntax().text_range(),
672 &FunctionBody::Span { text_range, .. } => text_range,
676 fn contains_range(&self, range: TextRange) -> bool {
677 self.text_range().contains_range(range)
680 fn precedes_range(&self, range: TextRange) -> bool {
681 self.text_range().end() <= range.start()
684 fn contains_node(&self, node: &SyntaxNode) -> bool {
685 self.contains_range(node.text_range())
690 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
691 /// whether it contains an await expression.
694 sema: &Semantics<'_, RootDatabase>,
695 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
696 let mut self_param = None;
697 let mut res = FxIndexSet::default();
698 let mut cb = |name_ref: Option<_>| {
700 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
702 NameRefClass::Definition(Definition::Local(local_ref))
703 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
707 let InFile { file_id, value } = local_ref.source(sema.db);
708 // locals defined inside macros are not relevant to us
709 if !file_id.is_macro() {
711 Either::Right(it) => {
712 self_param.replace(it);
715 res.insert(local_ref);
720 self.walk_expr(&mut |expr| match expr {
721 ast::Expr::PathExpr(path_expr) => {
722 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
724 ast::Expr::ClosureExpr(closure_expr) => {
725 if let Some(body) = closure_expr.body() {
726 body.syntax().descendants().map(ast::NameRef::cast).for_each(|it| cb(it));
729 ast::Expr::MacroExpr(expr) => {
730 if let Some(tt) = expr.macro_call().and_then(|call| call.token_tree()) {
732 .children_with_tokens()
733 .flat_map(SyntaxElement::into_token)
734 .filter(|it| it.kind() == SyntaxKind::IDENT)
735 .flat_map(|t| sema.descend_into_macros(t))
736 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
744 fn analyze_container(&self, sema: &Semantics<'_, RootDatabase>) -> Option<ContainerInfo> {
745 let mut ancestors = self.parent()?.ancestors();
746 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
747 let mut parent_loop = None;
748 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
751 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
753 parent_loop.get_or_insert(loop_.syntax().clone());
757 let (is_const, expr, ty) = loop {
758 let anc = ancestors.next()?;
761 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
762 ast::BlockExpr(block_expr) => {
763 let (constness, block) = match block_expr.modifier() {
764 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
765 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
766 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
769 let expr = Some(ast::Expr::BlockExpr(block));
770 (constness, expr.clone(), infer_expr_opt(expr))
773 let func = sema.to_def(&fn_)?;
774 let mut ret_ty = func.ret_type(sema.db);
775 if func.is_async(sema.db) {
776 if let Some(async_ret) = func.async_ret_type(sema.db) {
780 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty))
782 ast::Static(statik) => {
783 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
785 ast::ConstArg(ca) => {
786 (true, ca.expr(), infer_expr_opt(ca.expr()))
788 ast::Const(konst) => {
789 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
791 ast::ConstParam(cp) => {
792 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
794 ast::ConstBlockPat(cbp) => {
795 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
796 (true, expr.clone(), infer_expr_opt(expr))
798 ast::Variant(__) => return None,
799 ast::Meta(__) => return None,
800 ast::LoopExpr(it) => {
801 set_parent_loop(&it);
804 ast::ForExpr(it) => {
805 set_parent_loop(&it);
808 ast::WhileExpr(it) => {
809 set_parent_loop(&it);
816 let container_tail = match expr? {
817 ast::Expr::BlockExpr(block) => block.tail_expr(),
821 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
822 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
825 let parent = self.parent()?;
826 let parents = generic_parents(&parent);
827 let generic_param_lists = parents.iter().filter_map(|it| it.generic_param_list()).collect();
828 let where_clauses = parents.iter().filter_map(|it| it.where_clause()).collect();
840 fn return_ty(&self, ctx: &AssistContext<'_>) -> Option<RetType> {
841 match self.tail_expr() {
842 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
843 None => Some(RetType::Stmt),
847 /// Local variables defined inside `body` that are accessed outside of it
850 ctx: &'a AssistContext<'_>,
852 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
853 let parent = parent.clone();
854 let range = self.text_range();
855 locals_defined_in_body(&ctx.sema, self)
857 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
860 /// Analyses the function body for external control flow.
861 fn external_control_flow(
863 ctx: &AssistContext<'_>,
864 container_info: &ContainerInfo,
865 ) -> Option<ControlFlow> {
866 let mut ret_expr = None;
867 let mut try_expr = None;
868 let mut break_expr = None;
869 let mut continue_expr = None;
870 let mut is_async = false;
871 let mut _is_unsafe = false;
873 let mut unsafe_depth = 0;
874 let mut loop_depth = 0;
876 self.preorder_expr(&mut |expr| {
877 let expr = match expr {
878 WalkEvent::Enter(e) => e,
879 WalkEvent::Leave(expr) => {
881 ast::Expr::LoopExpr(_)
882 | ast::Expr::ForExpr(_)
883 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
884 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
893 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
896 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
899 ast::Expr::ReturnExpr(it) => {
902 ast::Expr::TryExpr(it) => {
905 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
906 break_expr = Some(it);
908 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
909 continue_expr = Some(it);
911 ast::Expr::AwaitExpr(_) => is_async = true,
912 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
913 // to just lift that out of there
914 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
920 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
921 (Some(_), _, None, None) => {
922 let ret_ty = container_info.ret_type.clone()?;
923 let kind = TryKind::of_ty(ret_ty, ctx)?;
925 Some(FlowKind::Try { kind })
927 (Some(_), _, _, _) => {
928 cov_mark::hit!(external_control_flow_try_and_bc);
931 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
932 (None, Some(_), _, _) => {
933 cov_mark::hit!(external_control_flow_return_and_bc);
936 (None, None, Some(_), Some(_)) => {
937 cov_mark::hit!(external_control_flow_break_and_continue);
940 (None, None, Some(b), None) => Some(FlowKind::Break(b.lifetime(), b.expr())),
941 (None, None, None, Some(c)) => Some(FlowKind::Continue(c.lifetime())),
942 (None, None, None, None) => None,
945 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
948 /// find variables that should be extracted as params
950 /// Computes additional info that affects param type and mutability
951 fn extracted_function_params(
953 ctx: &AssistContext<'_>,
954 container_info: &ContainerInfo,
955 locals: impl Iterator<Item = Local>,
958 .map(|local| (local, local.source(ctx.db())))
959 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
960 .filter_map(|(local, src)| match src.value {
961 Either::Left(src) => Some((local, src)),
962 Either::Right(_) => {
963 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
968 let usages = LocalUsages::find_local_usages(ctx, var);
969 let ty = var.ty(ctx.db());
971 let defined_outside_parent_loop = container_info
974 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
976 let is_copy = ty.is_copy(ctx.db());
977 let has_usages = self.has_usages_after_body(&usages);
979 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
980 // We can move the value into the function call if it's not used after the call,
981 // if the var is not used but defined outside a loop we are extracting from we can't move it either
982 // as the function will reuse it in the next iteration.
983 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
984 Param { var, ty, move_local, requires_mut, is_copy }
989 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
990 usages.iter().any(|reference| self.precedes_range(reference.range))
1000 impl GenericParent {
1001 fn generic_param_list(&self) -> Option<ast::GenericParamList> {
1003 GenericParent::Fn(fn_) => fn_.generic_param_list(),
1004 GenericParent::Impl(impl_) => impl_.generic_param_list(),
1005 GenericParent::Trait(trait_) => trait_.generic_param_list(),
1009 fn where_clause(&self) -> Option<ast::WhereClause> {
1011 GenericParent::Fn(fn_) => fn_.where_clause(),
1012 GenericParent::Impl(impl_) => impl_.where_clause(),
1013 GenericParent::Trait(trait_) => trait_.where_clause(),
1018 /// Search `parent`'s ancestors for items with potentially applicable generic parameters
1019 fn generic_parents(parent: &SyntaxNode) -> Vec<GenericParent> {
1020 let mut list = Vec::new();
1021 if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) {
1023 ast::Item::Fn(ref fn_) => {
1024 if let Some(parent_parent) = parent_item
1027 .and_then(|it| it.parent())
1028 .and_then(ast::Item::cast)
1030 match parent_parent {
1031 ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)),
1032 ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)),
1036 list.push(GenericParent::Fn(fn_.clone()));
1044 /// checks if relevant var is used with `&mut` access inside body
1045 fn has_exclusive_usages(
1046 ctx: &AssistContext<'_>,
1047 usages: &LocalUsages,
1048 body: &FunctionBody,
1052 .filter(|reference| body.contains_range(reference.range))
1053 .any(|reference| reference_is_exclusive(reference, body, ctx))
1056 /// checks if this reference requires `&mut` access inside node
1057 fn reference_is_exclusive(
1058 reference: &FileReference,
1059 node: &dyn HasTokenAtOffset,
1060 ctx: &AssistContext<'_>,
1062 // we directly modify variable with set: `n = 0`, `n += 1`
1063 if reference.category == Some(ReferenceCategory::Write) {
1067 // we take `&mut` reference to variable: `&mut v`
1068 let path = match path_element_of_reference(node, reference) {
1070 None => return false,
1073 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
1076 /// checks if this expr requires `&mut` access, recurses on field access
1077 fn expr_require_exclusive_access(ctx: &AssistContext<'_>, expr: &ast::Expr) -> Option<bool> {
1078 if let ast::Expr::MacroExpr(_) = expr {
1079 // FIXME: expand macro and check output for mutable usages of the variable?
1083 let parent = expr.syntax().parent()?;
1085 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
1086 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
1087 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
1092 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
1093 return Some(ref_expr.mut_token().is_some());
1096 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
1097 let func = ctx.sema.resolve_method_call(&method_call)?;
1098 let self_param = func.self_param(ctx.db())?;
1099 let access = self_param.access(ctx.db());
1101 return Some(matches!(access, hir::Access::Exclusive));
1104 if let Some(field) = ast::FieldExpr::cast(parent) {
1105 return expr_require_exclusive_access(ctx, &field.into());
1111 trait HasTokenAtOffset {
1112 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
1115 impl HasTokenAtOffset for SyntaxNode {
1116 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1117 SyntaxNode::token_at_offset(self, offset)
1121 impl HasTokenAtOffset for FunctionBody {
1122 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1124 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
1125 FunctionBody::Span { parent, text_range } => {
1126 match parent.syntax().token_at_offset(offset) {
1127 TokenAtOffset::None => TokenAtOffset::None,
1128 TokenAtOffset::Single(t) => {
1129 if text_range.contains_range(t.text_range()) {
1130 TokenAtOffset::Single(t)
1135 TokenAtOffset::Between(a, b) => {
1137 text_range.contains_range(a.text_range()),
1138 text_range.contains_range(b.text_range()),
1140 (true, true) => TokenAtOffset::Between(a, b),
1141 (true, false) => TokenAtOffset::Single(a),
1142 (false, true) => TokenAtOffset::Single(b),
1143 (false, false) => TokenAtOffset::None,
1152 /// find relevant `ast::Expr` for reference
1156 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1157 fn path_element_of_reference(
1158 node: &dyn HasTokenAtOffset,
1159 reference: &FileReference,
1160 ) -> Option<ast::Expr> {
1161 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1162 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1165 let path = token.parent_ancestors().find_map(ast::Expr::cast).or_else(|| {
1166 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1170 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroExpr(_)),
1171 "unexpected expression type for variable usage: {:?}",
1177 /// list local variables defined inside `body`
1178 fn locals_defined_in_body(
1179 sema: &Semantics<'_, RootDatabase>,
1180 body: &FunctionBody,
1181 ) -> FxIndexSet<Local> {
1182 // FIXME: this doesn't work well with macros
1183 // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550
1184 let mut res = FxIndexSet::default();
1185 body.walk_pat(&mut |pat| {
1186 if let ast::Pat::IdentPat(pat) = pat {
1187 if let Some(local) = sema.to_def(&pat) {
1195 /// Returns usage details if local variable is used after(outside of) body
1196 fn local_outlives_body(
1197 ctx: &AssistContext<'_>,
1198 body_range: TextRange,
1200 parent: &SyntaxNode,
1201 ) -> Option<OutlivedLocal> {
1202 let usages = LocalUsages::find_local_usages(ctx, local);
1203 let mut has_mut_usages = false;
1204 let mut any_outlives = false;
1205 for usage in usages.iter() {
1206 if body_range.end() <= usage.range.start() {
1207 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1208 any_outlives |= true;
1210 break; // no need to check more elements we have all the info we wanted
1217 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1220 /// checks if the relevant local was defined before(outside of) body
1221 fn is_defined_outside_of_body(
1222 ctx: &AssistContext<'_>,
1223 body: &FunctionBody,
1224 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1226 src.file_id.original_file(ctx.db()) == ctx.file_id()
1227 && !body.contains_node(either_syntax(&src.value))
1230 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1232 Either::Left(pat) => pat.syntax(),
1233 Either::Right(it) => it.syntax(),
1237 /// find where to put extracted function definition
1239 /// Function should be put right after returned node
1240 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1241 let node = body.node();
1242 let mut ancestors = node.ancestors().peekable();
1243 let mut last_ancestor = None;
1244 while let Some(next_ancestor) = ancestors.next() {
1245 match next_ancestor.kind() {
1246 SyntaxKind::SOURCE_FILE => break,
1247 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1248 SyntaxKind::ITEM_LIST => {
1249 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1253 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => continue,
1254 SyntaxKind::ASSOC_ITEM_LIST if body.extracted_from_trait_impl() => continue,
1255 SyntaxKind::ASSOC_ITEM_LIST => {
1256 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1262 last_ancestor = Some(next_ancestor);
1267 fn make_call(ctx: &AssistContext<'_>, fun: &Function, indent: IndentLevel) -> String {
1268 let ret_ty = fun.return_type(ctx);
1270 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1271 let name = fun.name.clone();
1272 let mut call_expr = if fun.self_param.is_some() {
1273 let self_arg = make::expr_path(make::ext::ident_path("self"));
1274 make::expr_method_call(self_arg, name, args)
1276 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1277 make::expr_call(func, args)
1280 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1282 if fun.control_flow.is_async {
1283 call_expr = make::expr_await(call_expr);
1285 let expr = handler.make_call_expr(call_expr).indent(indent);
1287 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1289 let mut buf = String::new();
1290 match fun.outliving_locals.as_slice() {
1293 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()))
1296 buf.push_str("let (");
1297 let bindings = vars.iter().format_with(", ", |local, f| {
1298 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db())))
1300 format_to!(buf, "{}", bindings);
1301 buf.push_str(") = ");
1305 format_to!(buf, "{}", expr);
1306 let insert_comma = fun
1309 .and_then(ast::MatchArm::cast)
1310 .map_or(false, |it| it.comma_token().is_none());
1313 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1321 Try { kind: TryKind },
1322 If { action: FlowKind },
1323 IfOption { action: FlowKind },
1324 MatchOption { none: FlowKind },
1325 MatchResult { err: FlowKind },
1329 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1330 match &fun.control_flow.kind {
1331 None => FlowHandler::None,
1332 Some(flow_kind) => {
1333 let action = flow_kind.clone();
1334 if *ret_ty == FunType::Unit {
1336 FlowKind::Return(None)
1337 | FlowKind::Break(_, None)
1338 | FlowKind::Continue(_) => FlowHandler::If { action },
1339 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1340 FlowHandler::IfOption { action }
1342 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1346 FlowKind::Return(None)
1347 | FlowKind::Break(_, None)
1348 | FlowKind::Continue(_) => FlowHandler::MatchOption { none: action },
1349 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1350 FlowHandler::MatchResult { err: action }
1352 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1359 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1361 FlowHandler::None => call_expr,
1362 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1363 FlowHandler::If { action } => {
1364 let action = action.make_result_handler(None);
1365 let stmt = make::expr_stmt(action);
1366 let block = make::block_expr(iter::once(stmt.into()), None);
1367 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1368 let condition = make::expr_let(
1369 make::tuple_struct_pat(
1370 controlflow_break_path,
1371 iter::once(make::wildcard_pat().into()),
1376 make::expr_if(condition.into(), block, None)
1378 FlowHandler::IfOption { action } => {
1379 let path = make::ext::ident_path("Some");
1380 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1381 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1382 let cond = make::expr_let(pattern.into(), call_expr);
1383 let value = make::expr_path(make::ext::ident_path("value"));
1384 let action_expr = action.make_result_handler(Some(value));
1385 let action_stmt = make::expr_stmt(action_expr);
1386 let then = make::block_expr(iter::once(action_stmt.into()), None);
1387 make::expr_if(cond.into(), then, None)
1389 FlowHandler::MatchOption { none } => {
1390 let some_name = "value";
1393 let path = make::ext::ident_path("Some");
1394 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1395 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1396 let value = make::expr_path(make::ext::ident_path(some_name));
1397 make::match_arm(iter::once(pat.into()), None, value)
1400 let path = make::ext::ident_path("None");
1401 let pat = make::path_pat(path);
1402 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1404 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1405 make::expr_match(call_expr, arms)
1407 FlowHandler::MatchResult { err } => {
1408 let ok_name = "value";
1409 let err_name = "value";
1412 let path = make::ext::ident_path("Ok");
1413 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1414 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1415 let value = make::expr_path(make::ext::ident_path(ok_name));
1416 make::match_arm(iter::once(pat.into()), None, value)
1419 let path = make::ext::ident_path("Err");
1420 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1421 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1422 let value = make::expr_path(make::ext::ident_path(err_name));
1424 iter::once(pat.into()),
1426 err.make_result_handler(Some(value)),
1429 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1430 make::expr_match(call_expr, arms)
1436 fn path_expr_from_local(ctx: &AssistContext<'_>, var: Local) -> ast::Expr {
1437 let name = var.name(ctx.db()).to_string();
1438 make::expr_path(make::ext::ident_path(&name))
1442 ctx: &AssistContext<'_>,
1443 module: hir::Module,
1445 old_indent: IndentLevel,
1446 new_indent: IndentLevel,
1448 let mut fn_def = String::new();
1449 let params = fun.make_param_list(ctx, module);
1450 let ret_ty = fun.make_ret_ty(ctx, module);
1451 let body = make_body(ctx, old_indent, new_indent, fun);
1452 let const_kw = if fun.mods.is_const { "const " } else { "" };
1453 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1454 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1455 let (generic_params, where_clause) = make_generic_params_and_where_clause(ctx, fun);
1456 match ctx.config.snippet_cap {
1457 Some(_) => format_to!(
1459 "\n\n{}{}{}{}fn $0{}",
1468 "\n\n{}{}{}{}fn {}",
1477 if let Some(generic_params) = generic_params {
1478 format_to!(fn_def, "{}", generic_params);
1481 format_to!(fn_def, "{}", params);
1483 if let Some(ret_ty) = ret_ty {
1484 format_to!(fn_def, " {}", ret_ty);
1487 if let Some(where_clause) = where_clause {
1488 format_to!(fn_def, " {}", where_clause);
1491 format_to!(fn_def, " {}", body);
1496 fn make_generic_params_and_where_clause(
1497 ctx: &AssistContext<'_>,
1499 ) -> (Option<ast::GenericParamList>, Option<ast::WhereClause>) {
1500 let used_type_params = fun.type_params(ctx);
1502 let generic_param_list = make_generic_param_list(ctx, fun, &used_type_params);
1503 let where_clause = make_where_clause(ctx, fun, &used_type_params);
1505 (generic_param_list, where_clause)
1508 fn make_generic_param_list(
1509 ctx: &AssistContext<'_>,
1511 used_type_params: &[TypeParam],
1512 ) -> Option<ast::GenericParamList> {
1513 let mut generic_params = fun
1515 .generic_param_lists
1517 .flat_map(|parent_params| {
1520 .filter(|param| param_is_required(ctx, param, used_type_params))
1524 if generic_params.peek().is_some() {
1525 Some(make::generic_param_list(generic_params))
1531 fn param_is_required(
1532 ctx: &AssistContext<'_>,
1533 param: &ast::GenericParam,
1534 used_type_params: &[TypeParam],
1537 ast::GenericParam::ConstParam(_) | ast::GenericParam::LifetimeParam(_) => false,
1538 ast::GenericParam::TypeParam(type_param) => match &ctx.sema.to_def(type_param) {
1539 Some(def) => used_type_params.contains(def),
1545 fn make_where_clause(
1546 ctx: &AssistContext<'_>,
1548 used_type_params: &[TypeParam],
1549 ) -> Option<ast::WhereClause> {
1550 let mut predicates = fun
1554 .flat_map(|parent_where_clause| {
1557 .filter(|pred| pred_is_required(ctx, pred, used_type_params))
1561 if predicates.peek().is_some() {
1562 Some(make::where_clause(predicates))
1568 fn pred_is_required(
1569 ctx: &AssistContext<'_>,
1570 pred: &ast::WherePred,
1571 used_type_params: &[TypeParam],
1573 match resolved_type_param(ctx, pred) {
1574 Some(it) => used_type_params.contains(&it),
1579 fn resolved_type_param(ctx: &AssistContext<'_>, pred: &ast::WherePred) -> Option<TypeParam> {
1580 let path = match pred.ty()? {
1581 ast::Type::PathType(path_type) => path_type.path(),
1585 match ctx.sema.resolve_path(&path)? {
1586 PathResolution::TypeParam(type_param) => Some(type_param),
1592 /// Collect all the `TypeParam`s used in the `body` and `params`.
1593 fn type_params(&self, ctx: &AssistContext<'_>) -> Vec<TypeParam> {
1594 let type_params_in_descendant_paths =
1595 self.body.descendant_paths().filter_map(|it| match ctx.sema.resolve_path(&it) {
1596 Some(PathResolution::TypeParam(type_param)) => Some(type_param),
1599 let type_params_in_params = self.params.iter().filter_map(|p| p.ty.as_type_param(ctx.db()));
1600 type_params_in_descendant_paths.chain(type_params_in_params).collect()
1603 fn make_param_list(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::ParamList {
1604 let self_param = self.self_param.clone();
1605 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1606 make::param_list(self_param, params)
1609 fn make_ret_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> Option<ast::RetType> {
1610 let fun_ty = self.return_type(ctx);
1611 let handler = if self.mods.is_in_tail {
1614 FlowHandler::from_ret_ty(self, &fun_ty)
1616 let ret_ty = match &handler {
1617 FlowHandler::None => {
1618 if matches!(fun_ty, FunType::Unit) {
1621 fun_ty.make_ty(ctx, module)
1623 FlowHandler::Try { kind: TryKind::Option } => {
1624 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1626 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1627 let handler_ty = parent_ret_ty
1630 .map(|ty| make_ty(&ty, ctx, module))
1631 .unwrap_or_else(make::ty_placeholder);
1632 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1634 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1635 FlowHandler::IfOption { action } => {
1636 let handler_ty = action
1638 .map(|ty| make_ty(&ty, ctx, module))
1639 .unwrap_or_else(make::ty_placeholder);
1640 make::ext::ty_option(handler_ty)
1642 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1643 FlowHandler::MatchResult { err } => {
1644 let handler_ty = err
1646 .map(|ty| make_ty(&ty, ctx, module))
1647 .unwrap_or_else(make::ty_placeholder);
1648 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1651 Some(make::ret_type(ret_ty))
1656 fn make_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1658 FunType::Unit => make::ty_unit(),
1659 FunType::Single(ty) => make_ty(ty, ctx, module),
1660 FunType::Tuple(types) => match types.as_slice() {
1662 stdx::never!("tuple type with 0 elements");
1666 stdx::never!("tuple type with 1 element");
1667 make_ty(ty, ctx, module)
1670 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1671 make::ty_tuple(types)
1679 ctx: &AssistContext<'_>,
1680 old_indent: IndentLevel,
1681 new_indent: IndentLevel,
1683 ) -> ast::BlockExpr {
1684 let ret_ty = fun.return_type(ctx);
1685 let handler = if fun.mods.is_in_tail {
1688 FlowHandler::from_ret_ty(fun, &ret_ty)
1691 let block = match &fun.body {
1692 FunctionBody::Expr(expr) => {
1693 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1694 let expr = ast::Expr::cast(expr).unwrap();
1696 ast::Expr::BlockExpr(block) => {
1697 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1698 let block = block.dedent(old_indent);
1699 // Recreate the block for formatting consistency with other extracted functions.
1700 make::block_expr(block.statements(), block.tail_expr())
1703 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1705 make::block_expr(Vec::new(), Some(expr))
1709 FunctionBody::Span { parent, text_range } => {
1710 let mut elements: Vec<_> = parent
1712 .children_with_tokens()
1713 .filter(|it| text_range.contains_range(it.text_range()))
1714 .map(|it| match &it {
1715 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1716 rewrite_body_segment(ctx, &fun.params, &handler, n),
1722 let mut tail_expr = match &elements.last() {
1723 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1724 ast::Expr::cast(node.clone())
1733 None => match fun.outliving_locals.as_slice() {
1736 tail_expr = Some(path_expr_from_local(ctx, var.local));
1739 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1740 let expr = make::expr_tuple(exprs);
1741 tail_expr = Some(expr);
1746 let body_indent = IndentLevel(1);
1747 let elements = elements
1749 .map(|node_or_token| match &node_or_token {
1750 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1752 let indented = stmt.dedent(old_indent).indent(body_indent);
1753 let ast_node = indented.syntax().clone_subtree();
1754 syntax::NodeOrToken::Node(ast_node)
1760 .collect::<Vec<SyntaxElement>>();
1761 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1763 make::hacky_block_expr_with_comments(elements, tail_expr)
1767 let block = match &handler {
1768 FlowHandler::None => block,
1769 FlowHandler::Try { kind } => {
1770 let block = with_default_tail_expr(block, make::expr_unit());
1771 map_tail_expr(block, |tail_expr| {
1772 let constructor = match kind {
1773 TryKind::Option => "Some",
1774 TryKind::Result { .. } => "Ok",
1776 let func = make::expr_path(make::ext::ident_path(constructor));
1777 let args = make::arg_list(iter::once(tail_expr));
1778 make::expr_call(func, args)
1781 FlowHandler::If { .. } => {
1782 let controlflow_continue = make::expr_call(
1783 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1784 make::arg_list(iter::once(make::expr_unit())),
1786 with_tail_expr(block, controlflow_continue)
1788 FlowHandler::IfOption { .. } => {
1789 let none = make::expr_path(make::ext::ident_path("None"));
1790 with_tail_expr(block, none)
1792 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1793 let some = make::expr_path(make::ext::ident_path("Some"));
1794 let args = make::arg_list(iter::once(tail_expr));
1795 make::expr_call(some, args)
1797 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1798 let ok = make::expr_path(make::ext::ident_path("Ok"));
1799 let args = make::arg_list(iter::once(tail_expr));
1800 make::expr_call(ok, args)
1804 block.indent(new_indent)
1807 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1808 let tail_expr = match block.tail_expr() {
1809 Some(tail_expr) => tail_expr,
1810 None => return block,
1812 make::block_expr(block.statements(), Some(f(tail_expr)))
1815 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1816 match block.tail_expr() {
1818 None => make::block_expr(block.statements(), Some(tail_expr)),
1822 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1823 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1824 let stmts = block.statements().chain(stmt_tail);
1825 make::block_expr(stmts, Some(tail_expr))
1828 fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String {
1829 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1832 fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1833 let ty_str = format_type(ty, ctx, module);
1837 fn rewrite_body_segment(
1838 ctx: &AssistContext<'_>,
1840 handler: &FlowHandler,
1841 syntax: &SyntaxNode,
1843 let syntax = fix_param_usages(ctx, params, syntax);
1844 update_external_control_flow(handler, &syntax);
1848 /// change all usages to account for added `&`/`&mut` for some params
1849 fn fix_param_usages(ctx: &AssistContext<'_>, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1850 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1852 let tm = TreeMutator::new(syntax);
1854 for param in params {
1855 if !param.kind().is_ref() {
1859 let usages = LocalUsages::find_local_usages(ctx, param.var);
1862 .filter(|reference| syntax.text_range().contains_range(reference.range))
1863 .filter_map(|reference| path_element_of_reference(syntax, reference))
1864 .map(|expr| tm.make_mut(&expr));
1866 usages_for_param.push((param, usages.collect()));
1869 let res = tm.make_syntax_mut(syntax);
1871 for (param, usages) in usages_for_param {
1872 for usage in usages {
1873 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1874 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1877 Some(ast::Expr::RefExpr(node))
1878 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1880 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1882 Some(ast::Expr::RefExpr(node))
1883 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1885 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1888 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1889 ted::replace(usage.syntax(), p.syntax())
1898 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1899 let mut nested_loop = None;
1900 let mut nested_scope = None;
1901 for event in syntax.preorder() {
1903 WalkEvent::Enter(e) => match e.kind() {
1904 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1905 if nested_loop.is_none() {
1906 nested_loop = Some(e.clone());
1911 | SyntaxKind::STATIC
1913 | SyntaxKind::MODULE => {
1914 if nested_scope.is_none() {
1915 nested_scope = Some(e.clone());
1920 WalkEvent::Leave(e) => {
1921 if nested_scope.is_none() {
1922 if let Some(expr) = ast::Expr::cast(e.clone()) {
1924 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1925 let expr = return_expr.expr();
1926 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1927 ted::replace(return_expr.syntax(), replacement.syntax())
1930 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1931 let expr = break_expr.expr();
1932 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1933 ted::replace(break_expr.syntax(), replacement.syntax())
1936 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1937 if let Some(replacement) = make_rewritten_flow(handler, None) {
1938 ted::replace(continue_expr.syntax(), replacement.syntax())
1948 if nested_loop.as_ref() == Some(&e) {
1951 if nested_scope.as_ref() == Some(&e) {
1952 nested_scope = None;
1959 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1960 let value = match handler {
1961 FlowHandler::None | FlowHandler::Try { .. } => return None,
1962 FlowHandler::If { .. } => make::expr_call(
1963 make::expr_path(make::path_from_text("ControlFlow::Break")),
1964 make::arg_list(iter::once(make::expr_unit())),
1966 FlowHandler::IfOption { .. } => {
1967 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1968 let args = make::arg_list(iter::once(expr));
1969 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1971 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1972 FlowHandler::MatchResult { .. } => {
1973 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1974 let args = make::arg_list(iter::once(expr));
1975 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1978 Some(make::expr_return(Some(value)).clone_for_update())
1983 use crate::tests::{check_assist, check_assist_not_applicable};
1988 fn no_args_from_binary_expr() {
2001 fn $0fun_name() -> i32 {
2009 fn no_args_from_binary_expr_in_module() {
2025 fn $0fun_name() -> i32 {
2034 fn no_args_from_binary_expr_indented() {
2047 fn $0fun_name() -> i32 {
2055 fn no_args_from_stmt_with_last_expr() {
2071 fn $0fun_name() -> i32 {
2080 fn no_args_from_stmt_unit() {
2128 fn no_args_if_else() {
2133 $0if true { 1 } else { 2 }$0
2141 fn $0fun_name() -> i32 {
2142 if true { 1 } else { 2 }
2149 fn no_args_if_let_else() {
2154 $0if let true = false { 1 } else { 2 }$0
2162 fn $0fun_name() -> i32 {
2163 if let true = false { 1 } else { 2 }
2170 fn no_args_match() {
2186 fn $0fun_name() -> i32 {
2197 fn no_args_while() {
2223 $0for v in &[0, 1] { }$0
2232 for v in &[0, 1] { }
2239 fn no_args_from_loop_unit() {
2254 fn $0fun_name() -> ! {
2264 fn no_args_from_loop_with_return() {
2280 fn $0fun_name() -> i32 {
2291 fn no_args_from_match() {
2296 let v: i32 = $0match Some(1) {
2304 let v: i32 = fun_name();
2307 fn $0fun_name() -> i32 {
2318 fn extract_partial_block_single_line() {
2324 let mut v = $0n * n;$0
2331 let mut v = fun_name(n);
2335 fn $0fun_name(n: i32) -> i32 {
2344 fn extract_partial_block() {
2351 let mut v = m $0* n;
2361 let (mut v, mut w) = fun_name(m, n);
2366 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2376 fn argument_form_expr() {
2391 fn $0fun_name(n: u32) -> u32 {
2399 fn argument_used_twice_form_expr() {
2414 fn $0fun_name(n: u32) -> u32 {
2422 fn two_arguments_form_expr() {
2439 fn $0fun_name(n: u32, m: u32) -> u32 {
2447 fn argument_and_locals() {
2463 fn $0fun_name(n: u32) -> u32 {
2472 fn in_comment_is_not_applicable() {
2473 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2474 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2478 fn part_of_expr_stmt() {
2491 fn $0fun_name() -> i32 {
2499 fn function_expr() {
2520 fn extract_from_nested() {
2526 let tuple = match x {
2527 true => ($02 + 2$0, true)
2535 let tuple = match x {
2536 true => (fun_name(), true)
2541 fn $0fun_name() -> i32 {
2549 fn param_from_closure() {
2554 let lambda = |x: u32| $0x * 2$0;
2559 let lambda = |x: u32| fun_name(x);
2562 fn $0fun_name(x: u32) -> u32 {
2570 fn extract_return_stmt() {
2583 fn $0fun_name() -> u32 {
2591 fn does_not_add_extra_whitespace() {
2608 fn $0fun_name() -> u32 {
2633 fn $0fun_name() -> i32 {
2646 let v = $00f32 as u32$0;
2654 fn $0fun_name() -> u32 {
2662 fn return_not_applicable() {
2663 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2667 fn method_to_freestanding() {
2674 fn foo(&self) -> i32 {
2683 fn foo(&self) -> i32 {
2688 fn $0fun_name() -> i32 {
2696 fn method_with_reference() {
2700 struct S { f: i32 };
2703 fn foo(&self) -> i32 {
2709 struct S { f: i32 };
2712 fn foo(&self) -> i32 {
2716 fn $0fun_name(&self) -> i32 {
2725 fn method_with_mut() {
2729 struct S { f: i32 };
2738 struct S { f: i32 };
2745 fn $0fun_name(&mut self) {
2754 fn variable_defined_inside_and_used_after_no_ret() {
2767 let k = fun_name(n);
2771 fn $0fun_name(n: i32) -> i32 {
2780 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2786 $0let mut k = n * n;$0
2793 let mut k = fun_name(n);
2797 fn $0fun_name(n: i32) -> i32 {
2806 fn two_variables_defined_inside_and_used_after_no_ret() {
2820 let (k, m) = fun_name(n);
2824 fn $0fun_name(n: i32) -> (i32, i32) {
2834 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2840 $0let mut k = n * n;
2851 let (mut k, mut m, o) = fun_name(n);
2856 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2868 fn nontrivial_patterns_define_variables() {
2872 struct Counter(i32);
2874 $0let Counter(n) = Counter(0);$0
2879 struct Counter(i32);
2885 fn $0fun_name() -> i32 {
2886 let Counter(n) = Counter(0);
2894 fn struct_with_two_fields_pattern_define_variables() {
2898 struct Counter { n: i32, m: i32 };
2900 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2905 struct Counter { n: i32, m: i32 };
2907 let (n, k) = fun_name();
2911 fn $0fun_name() -> (i32, i32) {
2912 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2920 fn mut_var_from_outer_scope() {
2937 fn $0fun_name(n: &mut i32) {
2945 fn mut_field_from_outer_scope() {
2951 let mut c = C { n: 0 };
2959 let mut c = C { n: 0 };
2964 fn $0fun_name(c: &mut C) {
2972 fn mut_nested_field_from_outer_scope() {
2979 let mut c = C { p: P { n: 0 } };
2980 let mut v = C { p: P { n: 0 } };
2981 let u = C { p: P { n: 0 } };
2983 let r = &mut v.p.n;$0
2984 let m = c.p.n + v.p.n + u.p.n;
2991 let mut c = C { p: P { n: 0 } };
2992 let mut v = C { p: P { n: 0 } };
2993 let u = C { p: P { n: 0 } };
2994 fun_name(&mut c, &u, &mut v);
2995 let m = c.p.n + v.p.n + u.p.n;
2998 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
3007 fn mut_param_many_usages_stmt() {
3013 fn succ(&self) -> Self;
3014 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3017 fn succ(&self) -> Self { *self + 1 }
3036 fn succ(&self) -> Self;
3037 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3040 fn succ(&self) -> Self { *self + 1 }
3048 fn $0fun_name(n: &mut i32) {
3064 fn mut_param_many_usages_expr() {
3070 fn succ(&self) -> Self;
3071 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3074 fn succ(&self) -> Self { *self + 1 }
3095 fn succ(&self) -> Self;
3096 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3099 fn succ(&self) -> Self { *self + 1 }
3107 fn $0fun_name(n: &mut i32) {
3123 fn mut_param_by_value() {
3138 fn $0fun_name(mut n: i32) {
3146 fn mut_param_because_of_mut_ref() {
3164 fn $0fun_name(n: &mut i32) {
3173 fn mut_param_by_value_because_of_mut_ref() {
3189 fn $0fun_name(mut n: i32) {
3198 fn mut_method_call() {
3206 fn inc(&mut self) { *self += 1 }
3218 fn inc(&mut self) { *self += 1 }
3225 fn $0fun_name(mut n: i32) {
3233 fn shared_method_call() {
3241 fn succ(&self) { *self + 1 }
3253 fn succ(&self) { *self + 1 }
3260 fn $0fun_name(n: i32) {
3268 fn mut_method_call_with_other_receiver() {
3273 fn inc(&mut self, n: i32);
3276 fn inc(&mut self, n: i32) { *self += n }
3286 fn inc(&mut self, n: i32);
3289 fn inc(&mut self, n: i32) { *self += n }
3296 fn $0fun_name(n: i32) {
3305 fn non_copy_without_usages_after() {
3309 struct Counter(i32);
3316 struct Counter(i32);
3322 fn $0fun_name(c: Counter) {
3330 fn non_copy_used_after() {
3334 struct Counter(i32);
3342 struct Counter(i32);
3349 fn $0fun_name(c: &Counter) {
3357 fn copy_used_after() {
3375 fn $0fun_name(n: i32) {
3383 fn copy_custom_used_after() {
3387 //- minicore: copy, derive
3388 #[derive(Clone, Copy)]
3389 struct Counter(i32);
3397 #[derive(Clone, Copy)]
3398 struct Counter(i32);
3405 fn $0fun_name(c: Counter) {
3413 fn indented_stmts() {
3444 fn indented_stmts_inside_mod() {
3483 //- minicore: option
3498 let k = match fun_name(n) {
3499 Some(value) => value,
3506 fn $0fun_name(n: i32) -> Option<i32> {
3517 fn return_to_parent() {
3521 //- minicore: copy, result
3533 let k = match fun_name(n) {
3535 Err(value) => return value,
3540 fn $0fun_name(n: i32) -> Result<i32, i64> {
3551 fn break_and_continue() {
3552 cov_mark::check!(external_control_flow_break_and_continue);
3553 check_assist_not_applicable(
3572 fn return_and_break() {
3573 cov_mark::check!(external_control_flow_return_and_bc);
3574 check_assist_not_applicable(
3593 fn break_loop_with_if() {
3609 use core::ops::ControlFlow;
3614 if let ControlFlow::Break(_) = fun_name(&mut n) {
3621 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3623 return ControlFlow::Break(());
3625 ControlFlow::Continue(())
3632 fn break_loop_nested() {
3649 use core::ops::ControlFlow;
3654 if let ControlFlow::Break(_) = fun_name(n) {
3661 fn $0fun_name(n: i32) -> ControlFlow<()> {
3664 return ControlFlow::Break(());
3666 ControlFlow::Continue(())
3673 fn break_loop_nested_labeled() {
3687 use core::ops::ControlFlow;
3692 if let ControlFlow::Break(_) = fun_name() {
3699 fn $0fun_name() -> ControlFlow<()> {
3700 return ControlFlow::Break(());
3701 ControlFlow::Continue(())
3708 fn continue_loop_nested_labeled() {
3722 use core::ops::ControlFlow;
3727 if let ControlFlow::Break(_) = fun_name() {
3734 fn $0fun_name() -> ControlFlow<()> {
3735 return ControlFlow::Break(());
3736 ControlFlow::Continue(())
3743 fn return_from_nested_loop() {
3763 let m = match fun_name() {
3764 Some(value) => value,
3771 fn $0fun_name() -> Option<i32> {
3784 fn break_from_nested_loop() {
3809 fn $0fun_name() -> i32 {
3822 fn break_from_nested_and_outer_loops() {
3845 let m = match fun_name() {
3846 Some(value) => value,
3853 fn $0fun_name() -> Option<i32> {
3869 fn return_from_nested_fn() {
3894 fn $0fun_name() -> i32 {
3907 fn break_with_value() {
3927 if let Some(value) = fun_name() {
3934 fn $0fun_name() -> Option<i32> {
3947 fn break_with_value_and_label() {
3967 if let Some(value) = fun_name() {
3974 fn $0fun_name() -> Option<i32> {
3987 fn break_with_value_and_return() {
4007 let m = match fun_name() {
4009 Err(value) => break value,
4015 fn $0fun_name() -> Result<i32, i64> {
4032 //- minicore: option
4033 fn bar() -> Option<i32> { None }
4034 fn foo() -> Option<()> {
4043 fn bar() -> Option<i32> { None }
4044 fn foo() -> Option<()> {
4046 let m = fun_name()?;
4051 fn $0fun_name() -> Option<i32> {
4061 fn try_option_unit() {
4065 //- minicore: option
4066 fn foo() -> Option<()> {
4075 fn foo() -> Option<()> {
4082 fn $0fun_name() -> Option<()> {
4096 //- minicore: result
4097 fn foo() -> Result<(), i64> {
4106 fn foo() -> Result<(), i64> {
4108 let m = fun_name()?;
4113 fn $0fun_name() -> Result<i32, i64> {
4123 fn try_option_with_return() {
4127 //- minicore: option
4128 fn foo() -> Option<()> {
4140 fn foo() -> Option<()> {
4142 let m = fun_name()?;
4147 fn $0fun_name() -> Option<i32> {
4160 fn try_result_with_return() {
4164 //- minicore: result
4165 fn foo() -> Result<(), i64> {
4177 fn foo() -> Result<(), i64> {
4179 let m = fun_name()?;
4184 fn $0fun_name() -> Result<i32, i64> {
4197 fn try_and_break() {
4198 cov_mark::check!(external_control_flow_try_and_bc);
4199 check_assist_not_applicable(
4202 //- minicore: option
4203 fn foo() -> Option<()> {
4219 fn try_and_return_ok() {
4223 //- minicore: result
4224 fn foo() -> Result<(), i64> {
4236 fn foo() -> Result<(), i64> {
4238 let m = fun_name()?;
4243 fn $0fun_name() -> Result<i32, i64> {
4256 fn param_usage_in_macro() {
4261 ($val:expr) => { $val };
4266 $0let k = n * m!(n);$0
4272 ($val:expr) => { $val };
4277 let k = fun_name(n);
4281 fn $0fun_name(n: i32) -> i32 {
4290 fn extract_with_await() {
4294 //- minicore: future
4296 $0some_function().await;$0
4299 async fn some_function() {
4308 async fn $0fun_name() {
4309 some_function().await;
4312 async fn some_function() {
4320 fn extract_with_await_and_result_not_producing_match_expr() {
4324 //- minicore: future, result
4325 async fn foo() -> Result<(), ()> {
4331 async fn foo() -> Result<(), ()> {
4335 async fn $0fun_name() -> Result<(), ()> {
4344 fn extract_with_await_and_result_producing_match_expr() {
4348 //- minicore: future
4349 async fn foo() -> i32 {
4352 let k = async { 1 }.await;
4362 async fn foo() -> i32 {
4365 let m = match fun_name().await {
4367 Err(value) => break value,
4373 async fn $0fun_name() -> Result<i32, i32> {
4374 let k = async { 1 }.await;
4386 fn extract_with_await_in_args() {
4390 //- minicore: future
4392 $0function_call("a", some_function().await);$0
4395 async fn some_function() {
4404 async fn $0fun_name() {
4405 function_call("a", some_function().await);
4408 async fn some_function() {
4416 fn extract_does_not_extract_standalone_blocks() {
4417 check_assist_not_applicable(
4426 fn extract_adds_comma_for_match_arm() {
4445 fn $0fun_name() -> i32 {
4468 fn $0fun_name() -> i32 {
4476 fn extract_does_not_tear_comments_apart() {
4503 fn extract_does_not_tear_body_apart() {
4524 fn extract_does_not_wrap_res_in_res() {
4528 //- minicore: result
4529 fn foo() -> Result<(), i64> {
4530 $0Result::<i32, i64>::Ok(0)?;
4535 fn foo() -> Result<(), i64> {
4539 fn $0fun_name() -> Result<(), i64> {
4540 Result::<i32, i64>::Ok(0)?;
4548 fn extract_knows_const() {
4561 const fn $0fun_name() {
4578 const fn $0fun_name() {
4586 fn extract_does_not_move_outer_loop_vars() {
4605 fn $0fun_name(x: &mut i32) {
4628 fn $0fun_name(mut x: i32) {
4655 fn $0fun_name(x: &mut i32) {
4662 // regression test for #9822
4664 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4670 fn foo(&mut self) {}
4684 fn foo(&mut self) {}
4695 fn $0fun_name(y: &mut Foo) {
4703 fn extract_with_macro_arg() {
4708 ($val:expr) => { $val };
4717 ($val:expr) => { $val };
4724 fn $0fun_name(bar: &str) {
4732 fn unresolveable_types_default_to_placeholder() {
4737 let a = __unresolved;
4743 let a = __unresolved;
4744 let _ = fun_name(a);
4747 fn $0fun_name(a: _) -> _ {
4755 fn reference_mutable_param_with_further_usages() {
4763 pub fn testfn(arg: &mut Foo) {
4765 // Simulating access after the extracted portion
4774 pub fn testfn(arg: &mut Foo) {
4776 // Simulating access after the extracted portion
4780 fn $0fun_name(arg: &mut Foo) {
4788 fn reference_mutable_param_without_further_usages() {
4796 pub fn testfn(arg: &mut Foo) {
4805 pub fn testfn(arg: &mut Foo) {
4809 fn $0fun_name(arg: &mut Foo) {
4817 fn extract_function_copies_comment_at_start() {
4842 fn extract_function_copies_comment_in_between() {
4869 fn extract_function_copies_comment_at_end() {
4894 fn extract_function_copies_comment_indented() {
4922 // FIXME: we do want to preserve whitespace
4924 fn extract_function_does_not_preserve_whitespace() {
4950 fn extract_function_long_form_comment() {
4975 fn it_should_not_generate_duplicate_function_names() {
4996 fn should_increment_suffix_until_it_finds_space() {
5025 fn extract_method_from_trait_impl() {
5031 fn bar(&self) -> i32;
5034 impl Trait for Struct {
5035 fn bar(&self) -> i32 {
5043 fn bar(&self) -> i32;
5046 impl Trait for Struct {
5047 fn bar(&self) -> i32 {
5053 fn $0fun_name(&self) -> i32 {
5062 fn closure_arguments() {
5066 fn parent(factor: i32) {
5069 $0v.iter().map(|it| it * factor);$0
5073 fn parent(factor: i32) {
5076 fun_name(v, factor);
5079 fn $0fun_name(v: &[i32; 3], factor: i32) {
5080 v.iter().map(|it| it * factor);
5087 fn preserve_generics() {
5091 fn func<T: Debug>(i: T) {
5096 fn func<T: Debug>(i: T) {
5100 fn $0fun_name<T: Debug>(i: T) {
5108 fn preserve_generics_from_body() {
5112 fn func<T: Default>() -> T {
5117 fn func<T: Default>() -> T {
5121 fn $0fun_name<T: Default>() -> T {
5129 fn filter_unused_generics() {
5133 fn func<T: Debug, U: Copy>(i: T, u: U) {
5139 fn func<T: Debug, U: Copy>(i: T, u: U) {
5144 fn $0fun_name<T: Debug>(i: T) {
5152 fn empty_generic_param_list() {
5156 fn func<T: Debug>(t: T, i: u32) {
5162 fn func<T: Debug>(t: T, i: u32) {
5167 fn $0fun_name(i: u32) {
5175 fn preserve_where_clause() {
5179 fn func<T>(i: T) where T: Debug {
5184 fn func<T>(i: T) where T: Debug {
5188 fn $0fun_name<T>(i: T) where T: Debug {
5196 fn filter_unused_where_clause() {
5200 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5206 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5211 fn $0fun_name<T>(i: T) where T: Debug {
5219 fn nested_generics() {
5223 struct Struct<T: Into<i32>>(T);
5224 impl <T: Into<i32> + Copy> Struct<T> {
5225 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5227 $0t.into() + v.into()$0
5232 struct Struct<T: Into<i32>>(T);
5233 impl <T: Into<i32> + Copy> Struct<T> {
5234 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5240 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5248 fn filters_unused_nested_generics() {
5252 struct Struct<T: Into<i32>, U: Debug>(T, U);
5253 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5254 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5256 $0t.into() + v.into()$0
5261 struct Struct<T: Into<i32>, U: Debug>(T, U);
5262 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5263 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5269 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5277 fn nested_where_clauses() {
5281 struct Struct<T>(T) where T: Into<i32>;
5282 impl <T> Struct<T> where T: Into<i32> + Copy {
5283 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5285 $0t.into() + v.into()$0
5290 struct Struct<T>(T) where T: Into<i32>;
5291 impl <T> Struct<T> where T: Into<i32> + Copy {
5292 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5298 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
5306 fn filters_unused_nested_where_clauses() {
5310 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5311 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5312 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5314 $0t.into() + v.into()$0
5319 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5320 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5321 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5327 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {