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 name = make_function_name(&semantics_scope);
122 mods: container_info,
125 let new_indent = IndentLevel::from_node(&insert_after);
126 let old_indent = fun.body.indent_level();
128 builder.replace(target_range, make_call(ctx, &fun, old_indent));
130 let has_impl_wrapper = insert_after
132 .find(|a| a.kind() == SyntaxKind::IMPL && a != &insert_after)
135 let fn_def = match fun.self_param_adt(ctx) {
136 Some(adt) if anchor == Anchor::Method && !has_impl_wrapper => {
137 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent + 1);
138 generate_impl_text(&adt, &fn_def).replace("{\n\n", "{")
140 _ => format_function(ctx, module, &fun, old_indent, new_indent),
143 if fn_def.contains("ControlFlow") {
144 let scope = match scope {
145 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
146 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
147 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
150 let control_flow_enum =
151 FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();
153 if let Some(control_flow_enum) = control_flow_enum {
154 let mod_path = module.find_use_path_prefixed(
156 ModuleDef::from(control_flow_enum),
157 ctx.config.insert_use.prefix_kind,
160 if let Some(mod_path) = mod_path {
161 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
166 let insert_offset = insert_after.text_range().end();
168 match ctx.config.snippet_cap {
169 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
170 None => builder.insert(insert_offset, fn_def),
176 fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef {
177 let mut names_in_scope = vec![];
178 semantics_scope.process_all_names(&mut |name, _| names_in_scope.push(name.to_string()));
180 let default_name = "fun_name";
182 let mut name = default_name.to_string();
184 while names_in_scope.contains(&name) {
186 name = format!("{}{}", &default_name, counter)
188 make::name_ref(&name)
191 /// Try to guess what user wants to extract
193 /// We have basically have two cases:
194 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
195 /// Then we can use `ast::Expr`
196 /// * We want a few statements for a block. E.g.
198 /// fn foo() -> i32 {
208 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
209 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
211 ast::Stmt::Item(_) => None,
212 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
213 node.parent().and_then(ast::StmtList::cast)?,
219 // Covering element returned the parent block of one or multiple statements that have been selected
220 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
221 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
222 if block_expr.syntax().text_range() == selection_range {
223 return FunctionBody::from_expr(block_expr.into());
227 // Extract the full statements.
228 return Some(FunctionBody::from_range(stmt_list, selection_range));
231 let expr = ast::Expr::cast(node.clone())?;
232 // A node got selected fully
233 if node.text_range() == selection_range {
234 return FunctionBody::from_expr(expr);
237 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
243 self_param: Option<ast::SelfParam>,
245 control_flow: ControlFlow,
248 outliving_locals: Vec<OutlivedLocal>,
261 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
269 #[derive(Debug, Eq, PartialEq)]
273 Tuple(Vec<hir::Type>),
276 /// Where to put extracted function definition
277 #[derive(Debug, Eq, PartialEq, Clone, Copy)]
279 /// Extract free function and put right after current top-level function
281 /// Extract method and put right after current function in the impl-block
285 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
286 // probably be merged somehow.
289 kind: Option<FlowKind>,
294 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
295 #[derive(Clone, Debug)]
296 struct ContainerInfo {
299 parent_loop: Option<SyntaxNode>,
300 /// The function's return type, const's type etc.
301 ret_type: Option<hir::Type>,
302 generic_param_lists: Vec<ast::GenericParamList>,
303 where_clauses: Vec<ast::WhereClause>,
306 /// Control flow that is exported from extracted function
318 #[derive(Debug, Clone)]
320 /// Return with value (`return $expr;`)
321 Return(Option<ast::Expr>),
325 /// Break with label and value (`break 'label $expr;`)
326 Break(Option<ast::Lifetime>, Option<ast::Expr>),
327 /// Continue with label (`continue 'label;`)
328 Continue(Option<ast::Lifetime>),
331 #[derive(Debug, Clone)]
334 Result { ty: hir::Type },
344 fn is_unit(&self) -> bool {
346 RetType::Expr(ty) => ty.is_unit(),
347 RetType::Stmt => true,
352 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
353 /// This is the future function body, the part that is being extracted.
357 Span { parent: ast::StmtList, text_range: TextRange },
361 struct OutlivedLocal {
363 mut_usage_outside_body: bool,
366 /// Container of local variable usages
368 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
369 struct LocalUsages(ide_db::search::UsageSearchResult);
372 fn find_local_usages(ctx: &AssistContext<'_>, var: Local) -> Self {
374 Definition::Local(var)
376 .in_scope(SearchScope::single_file(ctx.file_id()))
381 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
382 self.0.iter().flat_map(|(_, rs)| rs)
387 fn return_type(&self, ctx: &AssistContext<'_>) -> FunType {
389 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
390 RetType::Expr(ty) => FunType::Single(ty.clone()),
391 RetType::Stmt => match self.outliving_locals.as_slice() {
393 [var] => FunType::Single(var.local.ty(ctx.db())),
395 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
396 FunType::Tuple(types)
402 fn self_param_adt(&self, ctx: &AssistContext<'_>) -> Option<ast::Adt> {
403 let self_param = self.self_param.as_ref()?;
404 let def = ctx.sema.to_def(self_param)?;
405 let adt = def.ty(ctx.db()).strip_references().as_adt()?;
406 let InFile { file_id: _, value } = adt.source(ctx.db())?;
412 fn is_ref(&self) -> bool {
413 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
418 fn kind(&self) -> ParamKind {
419 match (self.move_local, self.requires_mut, self.is_copy) {
420 (false, true, _) => ParamKind::MutRef,
421 (false, false, false) => ParamKind::SharedRef,
422 (true, true, _) => ParamKind::MutValue,
423 (_, false, _) => ParamKind::Value,
427 fn to_arg(&self, ctx: &AssistContext<'_>) -> ast::Expr {
428 let var = path_expr_from_local(ctx, self.var);
430 ParamKind::Value | ParamKind::MutValue => var,
431 ParamKind::SharedRef => make::expr_ref(var, false),
432 ParamKind::MutRef => make::expr_ref(var, true),
436 fn to_param(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Param {
437 let var = self.var.name(ctx.db()).to_string();
438 let var_name = make::name(&var);
439 let pat = match self.kind() {
440 ParamKind::MutValue => make::ident_pat(false, true, var_name),
441 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
442 make::ext::simple_ident_pat(var_name)
446 let ty = make_ty(&self.ty, ctx, module);
447 let ty = match self.kind() {
448 ParamKind::Value | ParamKind::MutValue => ty,
449 ParamKind::SharedRef => make::ty_ref(ty, false),
450 ParamKind::MutRef => make::ty_ref(ty, true),
453 make::param(pat.into(), ty)
458 fn of_ty(ty: hir::Type, ctx: &AssistContext<'_>) -> Option<TryKind> {
460 // We favour Result for `expr?`
461 return Some(TryKind::Result { ty });
463 let adt = ty.as_adt()?;
464 let name = adt.name(ctx.db());
465 // FIXME: use lang items to determine if it is std type or user defined
466 // E.g. if user happens to define type named `Option`, we would have false positive
467 match name.to_string().as_str() {
468 "Option" => Some(TryKind::Option),
469 "Result" => Some(TryKind::Result { ty }),
476 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
478 FlowKind::Return(_) => make::expr_return(expr),
479 FlowKind::Break(label, _) => make::expr_break(label.clone(), expr),
480 FlowKind::Try { .. } => {
481 stdx::never!("cannot have result handler with try");
482 expr.unwrap_or_else(|| make::expr_return(None))
484 FlowKind::Continue(label) => {
485 stdx::always!(expr.is_none(), "continue with value is not possible");
486 make::expr_continue(label.clone())
491 fn expr_ty(&self, ctx: &AssistContext<'_>) -> Option<hir::Type> {
493 FlowKind::Return(Some(expr)) | FlowKind::Break(_, Some(expr)) => {
494 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
496 FlowKind::Try { .. } => {
497 stdx::never!("try does not have defined expr_ty");
506 fn parent(&self) -> Option<SyntaxNode> {
508 FunctionBody::Expr(expr) => expr.syntax().parent(),
509 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
513 fn node(&self) -> &SyntaxNode {
515 FunctionBody::Expr(e) => e.syntax(),
516 FunctionBody::Span { parent, .. } => parent.syntax(),
520 fn extracted_from_trait_impl(&self) -> bool {
521 match self.node().ancestors().find_map(ast::Impl::cast) {
522 Some(c) => return c.trait_().is_some(),
527 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
529 FunctionBody::Expr(expr) => expr.syntax().descendants(),
530 FunctionBody::Span { parent, .. } => parent.syntax().descendants(),
534 fn descendant_paths(&self) -> impl Iterator<Item = ast::Path> {
535 self.descendants().filter_map(|node| {
538 ast::Path(it) => Some(it),
545 fn from_expr(expr: ast::Expr) -> Option<Self> {
547 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
548 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
549 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
550 expr => Some(Self::Expr(expr)),
554 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
555 let full_body = parent.syntax().children_with_tokens();
557 let mut text_range = full_body
558 .filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
559 .map(|element| element.text_range())
560 .filter(|&range| selected.intersect(range).filter(|it| !it.is_empty()).is_some())
561 .reduce(|acc, stmt| acc.cover(stmt));
563 if let Some(tail_range) = parent
565 .map(|it| it.syntax().text_range())
566 .filter(|&it| selected.intersect(it).is_some())
568 text_range = Some(match text_range {
569 Some(text_range) => text_range.cover(tail_range),
573 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
576 fn indent_level(&self) -> IndentLevel {
578 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
579 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
583 fn tail_expr(&self) -> Option<ast::Expr> {
585 FunctionBody::Expr(expr) => Some(expr.clone()),
586 FunctionBody::Span { parent, text_range } => {
587 let tail_expr = parent.tail_expr()?;
588 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
593 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
595 FunctionBody::Expr(expr) => walk_expr(expr, cb),
596 FunctionBody::Span { parent, text_range } => {
599 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
600 .filter_map(|stmt| match stmt {
601 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
602 ast::Stmt::Item(_) => None,
603 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
605 .for_each(|expr| walk_expr(&expr, cb));
606 if let Some(expr) = parent
608 .filter(|it| text_range.contains_range(it.syntax().text_range()))
610 walk_expr(&expr, cb);
616 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
618 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
619 FunctionBody::Span { parent, text_range } => {
622 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
623 .filter_map(|stmt| match stmt {
624 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
625 ast::Stmt::Item(_) => None,
626 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
628 .for_each(|expr| preorder_expr(&expr, cb));
629 if let Some(expr) = parent
631 .filter(|it| text_range.contains_range(it.syntax().text_range()))
633 preorder_expr(&expr, cb);
639 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
641 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
642 FunctionBody::Span { parent, text_range } => {
645 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
646 .for_each(|stmt| match stmt {
647 ast::Stmt::ExprStmt(expr_stmt) => {
648 if let Some(expr) = expr_stmt.expr() {
649 walk_patterns_in_expr(&expr, cb)
652 ast::Stmt::Item(_) => (),
653 ast::Stmt::LetStmt(stmt) => {
654 if let Some(pat) = stmt.pat() {
657 if let Some(expr) = stmt.initializer() {
658 walk_patterns_in_expr(&expr, cb);
662 if let Some(expr) = parent
664 .filter(|it| text_range.contains_range(it.syntax().text_range()))
666 walk_patterns_in_expr(&expr, cb);
672 fn text_range(&self) -> TextRange {
674 FunctionBody::Expr(expr) => expr.syntax().text_range(),
675 &FunctionBody::Span { text_range, .. } => text_range,
679 fn contains_range(&self, range: TextRange) -> bool {
680 self.text_range().contains_range(range)
683 fn precedes_range(&self, range: TextRange) -> bool {
684 self.text_range().end() <= range.start()
687 fn contains_node(&self, node: &SyntaxNode) -> bool {
688 self.contains_range(node.text_range())
693 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
694 /// whether it contains an await expression.
697 sema: &Semantics<'_, RootDatabase>,
698 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
699 let mut self_param = None;
700 let mut res = FxIndexSet::default();
701 let mut cb = |name_ref: Option<_>| {
703 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
705 NameRefClass::Definition(Definition::Local(local_ref))
706 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
710 let InFile { file_id, value } = local_ref.source(sema.db);
711 // locals defined inside macros are not relevant to us
712 if !file_id.is_macro() {
714 Either::Right(it) => {
715 self_param.replace(it);
718 res.insert(local_ref);
723 self.walk_expr(&mut |expr| match expr {
724 ast::Expr::PathExpr(path_expr) => {
725 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
727 ast::Expr::ClosureExpr(closure_expr) => {
728 if let Some(body) = closure_expr.body() {
729 body.syntax().descendants().map(ast::NameRef::cast).for_each(|it| cb(it));
732 ast::Expr::MacroExpr(expr) => {
733 if let Some(tt) = expr.macro_call().and_then(|call| call.token_tree()) {
735 .children_with_tokens()
736 .flat_map(SyntaxElement::into_token)
737 .filter(|it| it.kind() == SyntaxKind::IDENT)
738 .flat_map(|t| sema.descend_into_macros(t))
739 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
747 fn analyze_container(&self, sema: &Semantics<'_, RootDatabase>) -> Option<ContainerInfo> {
748 let mut ancestors = self.parent()?.ancestors();
749 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
750 let mut parent_loop = None;
751 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
754 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
756 parent_loop.get_or_insert(loop_.syntax().clone());
760 let (is_const, expr, ty) = loop {
761 let anc = ancestors.next()?;
764 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
765 ast::BlockExpr(block_expr) => {
766 let (constness, block) = match block_expr.modifier() {
767 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
768 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
769 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
772 let expr = Some(ast::Expr::BlockExpr(block));
773 (constness, expr.clone(), infer_expr_opt(expr))
776 let func = sema.to_def(&fn_)?;
777 let mut ret_ty = func.ret_type(sema.db);
778 if func.is_async(sema.db) {
779 if let Some(async_ret) = func.async_ret_type(sema.db) {
783 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty))
785 ast::Static(statik) => {
786 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
788 ast::ConstArg(ca) => {
789 (true, ca.expr(), infer_expr_opt(ca.expr()))
791 ast::Const(konst) => {
792 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
794 ast::ConstParam(cp) => {
795 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
797 ast::ConstBlockPat(cbp) => {
798 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
799 (true, expr.clone(), infer_expr_opt(expr))
801 ast::Variant(__) => return None,
802 ast::Meta(__) => return None,
803 ast::LoopExpr(it) => {
804 set_parent_loop(&it);
807 ast::ForExpr(it) => {
808 set_parent_loop(&it);
811 ast::WhileExpr(it) => {
812 set_parent_loop(&it);
819 let container_tail = match expr? {
820 ast::Expr::BlockExpr(block) => block.tail_expr(),
824 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
825 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
828 let parent = self.parent()?;
829 let parents = generic_parents(&parent);
830 let generic_param_lists = parents.iter().filter_map(|it| it.generic_param_list()).collect();
831 let where_clauses = parents.iter().filter_map(|it| it.where_clause()).collect();
843 fn return_ty(&self, ctx: &AssistContext<'_>) -> Option<RetType> {
844 match self.tail_expr() {
845 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
846 None => Some(RetType::Stmt),
850 /// Local variables defined inside `body` that are accessed outside of it
853 ctx: &'a AssistContext<'_>,
855 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
856 let parent = parent.clone();
857 let range = self.text_range();
858 locals_defined_in_body(&ctx.sema, self)
860 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
863 /// Analyses the function body for external control flow.
864 fn external_control_flow(
866 ctx: &AssistContext<'_>,
867 container_info: &ContainerInfo,
868 ) -> Option<ControlFlow> {
869 let mut ret_expr = None;
870 let mut try_expr = None;
871 let mut break_expr = None;
872 let mut continue_expr = None;
873 let mut is_async = false;
874 let mut _is_unsafe = false;
876 let mut unsafe_depth = 0;
877 let mut loop_depth = 0;
879 self.preorder_expr(&mut |expr| {
880 let expr = match expr {
881 WalkEvent::Enter(e) => e,
882 WalkEvent::Leave(expr) => {
884 ast::Expr::LoopExpr(_)
885 | ast::Expr::ForExpr(_)
886 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
887 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
896 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
899 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
902 ast::Expr::ReturnExpr(it) => {
905 ast::Expr::TryExpr(it) => {
908 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
909 break_expr = Some(it);
911 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
912 continue_expr = Some(it);
914 ast::Expr::AwaitExpr(_) => is_async = true,
915 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
916 // to just lift that out of there
917 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
923 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
924 (Some(_), _, None, None) => {
925 let ret_ty = container_info.ret_type.clone()?;
926 let kind = TryKind::of_ty(ret_ty, ctx)?;
928 Some(FlowKind::Try { kind })
930 (Some(_), _, _, _) => {
931 cov_mark::hit!(external_control_flow_try_and_bc);
934 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
935 (None, Some(_), _, _) => {
936 cov_mark::hit!(external_control_flow_return_and_bc);
939 (None, None, Some(_), Some(_)) => {
940 cov_mark::hit!(external_control_flow_break_and_continue);
943 (None, None, Some(b), None) => Some(FlowKind::Break(b.lifetime(), b.expr())),
944 (None, None, None, Some(c)) => Some(FlowKind::Continue(c.lifetime())),
945 (None, None, None, None) => None,
948 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
951 /// find variables that should be extracted as params
953 /// Computes additional info that affects param type and mutability
954 fn extracted_function_params(
956 ctx: &AssistContext<'_>,
957 container_info: &ContainerInfo,
958 locals: impl Iterator<Item = Local>,
961 .map(|local| (local, local.source(ctx.db())))
962 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
963 .filter_map(|(local, src)| match src.value {
964 Either::Left(src) => Some((local, src)),
965 Either::Right(_) => {
966 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
971 let usages = LocalUsages::find_local_usages(ctx, var);
972 let ty = var.ty(ctx.db());
974 let defined_outside_parent_loop = container_info
977 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
979 let is_copy = ty.is_copy(ctx.db());
980 let has_usages = self.has_usages_after_body(&usages);
982 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
983 // We can move the value into the function call if it's not used after the call,
984 // if the var is not used but defined outside a loop we are extracting from we can't move it either
985 // as the function will reuse it in the next iteration.
986 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
987 Param { var, ty, move_local, requires_mut, is_copy }
992 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
993 usages.iter().any(|reference| self.precedes_range(reference.range))
1003 impl GenericParent {
1004 fn generic_param_list(&self) -> Option<ast::GenericParamList> {
1006 GenericParent::Fn(fn_) => fn_.generic_param_list(),
1007 GenericParent::Impl(impl_) => impl_.generic_param_list(),
1008 GenericParent::Trait(trait_) => trait_.generic_param_list(),
1012 fn where_clause(&self) -> Option<ast::WhereClause> {
1014 GenericParent::Fn(fn_) => fn_.where_clause(),
1015 GenericParent::Impl(impl_) => impl_.where_clause(),
1016 GenericParent::Trait(trait_) => trait_.where_clause(),
1021 /// Search `parent`'s ancestors for items with potentially applicable generic parameters
1022 fn generic_parents(parent: &SyntaxNode) -> Vec<GenericParent> {
1023 let mut list = Vec::new();
1024 if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) {
1026 ast::Item::Fn(ref fn_) => {
1027 if let Some(parent_parent) = parent_item
1030 .and_then(|it| it.parent())
1031 .and_then(ast::Item::cast)
1033 match parent_parent {
1034 ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)),
1035 ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)),
1039 list.push(GenericParent::Fn(fn_.clone()));
1047 /// checks if relevant var is used with `&mut` access inside body
1048 fn has_exclusive_usages(
1049 ctx: &AssistContext<'_>,
1050 usages: &LocalUsages,
1051 body: &FunctionBody,
1055 .filter(|reference| body.contains_range(reference.range))
1056 .any(|reference| reference_is_exclusive(reference, body, ctx))
1059 /// checks if this reference requires `&mut` access inside node
1060 fn reference_is_exclusive(
1061 reference: &FileReference,
1062 node: &dyn HasTokenAtOffset,
1063 ctx: &AssistContext<'_>,
1065 // we directly modify variable with set: `n = 0`, `n += 1`
1066 if reference.category == Some(ReferenceCategory::Write) {
1070 // we take `&mut` reference to variable: `&mut v`
1071 let path = match path_element_of_reference(node, reference) {
1073 None => return false,
1076 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
1079 /// checks if this expr requires `&mut` access, recurses on field access
1080 fn expr_require_exclusive_access(ctx: &AssistContext<'_>, expr: &ast::Expr) -> Option<bool> {
1081 if let ast::Expr::MacroExpr(_) = expr {
1082 // FIXME: expand macro and check output for mutable usages of the variable?
1086 let parent = expr.syntax().parent()?;
1088 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
1089 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
1090 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
1095 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
1096 return Some(ref_expr.mut_token().is_some());
1099 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
1100 let func = ctx.sema.resolve_method_call(&method_call)?;
1101 let self_param = func.self_param(ctx.db())?;
1102 let access = self_param.access(ctx.db());
1104 return Some(matches!(access, hir::Access::Exclusive));
1107 if let Some(field) = ast::FieldExpr::cast(parent) {
1108 return expr_require_exclusive_access(ctx, &field.into());
1114 trait HasTokenAtOffset {
1115 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
1118 impl HasTokenAtOffset for SyntaxNode {
1119 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1120 SyntaxNode::token_at_offset(self, offset)
1124 impl HasTokenAtOffset for FunctionBody {
1125 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1127 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
1128 FunctionBody::Span { parent, text_range } => {
1129 match parent.syntax().token_at_offset(offset) {
1130 TokenAtOffset::None => TokenAtOffset::None,
1131 TokenAtOffset::Single(t) => {
1132 if text_range.contains_range(t.text_range()) {
1133 TokenAtOffset::Single(t)
1138 TokenAtOffset::Between(a, b) => {
1140 text_range.contains_range(a.text_range()),
1141 text_range.contains_range(b.text_range()),
1143 (true, true) => TokenAtOffset::Between(a, b),
1144 (true, false) => TokenAtOffset::Single(a),
1145 (false, true) => TokenAtOffset::Single(b),
1146 (false, false) => TokenAtOffset::None,
1155 /// find relevant `ast::Expr` for reference
1159 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1160 fn path_element_of_reference(
1161 node: &dyn HasTokenAtOffset,
1162 reference: &FileReference,
1163 ) -> Option<ast::Expr> {
1164 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1165 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1168 let path = token.parent_ancestors().find_map(ast::Expr::cast).or_else(|| {
1169 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1173 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroExpr(_)),
1174 "unexpected expression type for variable usage: {:?}",
1180 /// list local variables defined inside `body`
1181 fn locals_defined_in_body(
1182 sema: &Semantics<'_, RootDatabase>,
1183 body: &FunctionBody,
1184 ) -> FxIndexSet<Local> {
1185 // FIXME: this doesn't work well with macros
1186 // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550
1187 let mut res = FxIndexSet::default();
1188 body.walk_pat(&mut |pat| {
1189 if let ast::Pat::IdentPat(pat) = pat {
1190 if let Some(local) = sema.to_def(&pat) {
1198 /// Returns usage details if local variable is used after(outside of) body
1199 fn local_outlives_body(
1200 ctx: &AssistContext<'_>,
1201 body_range: TextRange,
1203 parent: &SyntaxNode,
1204 ) -> Option<OutlivedLocal> {
1205 let usages = LocalUsages::find_local_usages(ctx, local);
1206 let mut has_mut_usages = false;
1207 let mut any_outlives = false;
1208 for usage in usages.iter() {
1209 if body_range.end() <= usage.range.start() {
1210 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1211 any_outlives |= true;
1213 break; // no need to check more elements we have all the info we wanted
1220 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1223 /// checks if the relevant local was defined before(outside of) body
1224 fn is_defined_outside_of_body(
1225 ctx: &AssistContext<'_>,
1226 body: &FunctionBody,
1227 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1229 src.file_id.original_file(ctx.db()) == ctx.file_id()
1230 && !body.contains_node(either_syntax(&src.value))
1233 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1235 Either::Left(pat) => pat.syntax(),
1236 Either::Right(it) => it.syntax(),
1240 /// find where to put extracted function definition
1242 /// Function should be put right after returned node
1243 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1244 let node = body.node();
1245 let mut ancestors = node.ancestors().peekable();
1246 let mut last_ancestor = None;
1247 while let Some(next_ancestor) = ancestors.next() {
1248 match next_ancestor.kind() {
1249 SyntaxKind::SOURCE_FILE => break,
1250 SyntaxKind::IMPL => {
1251 if body.extracted_from_trait_impl() && matches!(anchor, Anchor::Method) {
1252 let impl_node = find_non_trait_impl(&next_ancestor);
1253 let target_node = impl_node.as_ref().and_then(last_impl_member);
1254 if target_node.is_some() {
1259 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1260 SyntaxKind::ITEM_LIST => {
1261 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1265 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => continue,
1266 SyntaxKind::ASSOC_ITEM_LIST if body.extracted_from_trait_impl() => continue,
1267 SyntaxKind::ASSOC_ITEM_LIST => {
1268 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1274 last_ancestor = Some(next_ancestor);
1279 fn find_non_trait_impl(trait_impl: &SyntaxNode) -> Option<SyntaxNode> {
1280 let impl_type = Some(impl_type_name(trait_impl)?);
1282 let mut sibblings = trait_impl.parent()?.children();
1283 sibblings.find(|s| impl_type_name(s) == impl_type && !is_trait_impl(s))
1286 fn last_impl_member(impl_node: &SyntaxNode) -> Option<SyntaxNode> {
1287 impl_node.children().find(|c| c.kind() == SyntaxKind::ASSOC_ITEM_LIST)?.last_child()
1290 fn is_trait_impl(node: &SyntaxNode) -> bool {
1291 if !ast::Impl::can_cast(node.kind()) {
1294 match ast::Impl::cast(node.clone()) {
1295 Some(c) => c.trait_().is_some(),
1300 fn impl_type_name(impl_node: &SyntaxNode) -> Option<String> {
1301 if !ast::Impl::can_cast(impl_node.kind()) {
1304 Some(ast::Impl::cast(impl_node.clone())?.self_ty()?.to_string())
1307 fn make_call(ctx: &AssistContext<'_>, fun: &Function, indent: IndentLevel) -> String {
1308 let ret_ty = fun.return_type(ctx);
1310 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1311 let name = fun.name.clone();
1312 let mut call_expr = if fun.self_param.is_some() {
1313 let self_arg = make::expr_path(make::ext::ident_path("self"));
1314 make::expr_method_call(self_arg, name, args)
1316 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1317 make::expr_call(func, args)
1320 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1322 if fun.control_flow.is_async {
1323 call_expr = make::expr_await(call_expr);
1325 let expr = handler.make_call_expr(call_expr).indent(indent);
1327 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1329 let mut buf = String::new();
1330 match fun.outliving_locals.as_slice() {
1333 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()))
1336 buf.push_str("let (");
1337 let bindings = vars.iter().format_with(", ", |local, f| {
1338 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db())))
1340 format_to!(buf, "{}", bindings);
1341 buf.push_str(") = ");
1345 format_to!(buf, "{}", expr);
1346 let insert_comma = fun
1349 .and_then(ast::MatchArm::cast)
1350 .map_or(false, |it| it.comma_token().is_none());
1353 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1361 Try { kind: TryKind },
1362 If { action: FlowKind },
1363 IfOption { action: FlowKind },
1364 MatchOption { none: FlowKind },
1365 MatchResult { err: FlowKind },
1369 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1370 match &fun.control_flow.kind {
1371 None => FlowHandler::None,
1372 Some(flow_kind) => {
1373 let action = flow_kind.clone();
1374 if *ret_ty == FunType::Unit {
1376 FlowKind::Return(None)
1377 | FlowKind::Break(_, None)
1378 | FlowKind::Continue(_) => FlowHandler::If { action },
1379 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1380 FlowHandler::IfOption { action }
1382 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1386 FlowKind::Return(None)
1387 | FlowKind::Break(_, None)
1388 | FlowKind::Continue(_) => FlowHandler::MatchOption { none: action },
1389 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1390 FlowHandler::MatchResult { err: action }
1392 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1399 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1401 FlowHandler::None => call_expr,
1402 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1403 FlowHandler::If { action } => {
1404 let action = action.make_result_handler(None);
1405 let stmt = make::expr_stmt(action);
1406 let block = make::block_expr(iter::once(stmt.into()), None);
1407 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1408 let condition = make::expr_let(
1409 make::tuple_struct_pat(
1410 controlflow_break_path,
1411 iter::once(make::wildcard_pat().into()),
1416 make::expr_if(condition.into(), block, None)
1418 FlowHandler::IfOption { action } => {
1419 let path = make::ext::ident_path("Some");
1420 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1421 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1422 let cond = make::expr_let(pattern.into(), call_expr);
1423 let value = make::expr_path(make::ext::ident_path("value"));
1424 let action_expr = action.make_result_handler(Some(value));
1425 let action_stmt = make::expr_stmt(action_expr);
1426 let then = make::block_expr(iter::once(action_stmt.into()), None);
1427 make::expr_if(cond.into(), then, None)
1429 FlowHandler::MatchOption { none } => {
1430 let some_name = "value";
1433 let path = make::ext::ident_path("Some");
1434 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1435 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1436 let value = make::expr_path(make::ext::ident_path(some_name));
1437 make::match_arm(iter::once(pat.into()), None, value)
1440 let path = make::ext::ident_path("None");
1441 let pat = make::path_pat(path);
1442 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1444 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1445 make::expr_match(call_expr, arms)
1447 FlowHandler::MatchResult { err } => {
1448 let ok_name = "value";
1449 let err_name = "value";
1452 let path = make::ext::ident_path("Ok");
1453 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1454 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1455 let value = make::expr_path(make::ext::ident_path(ok_name));
1456 make::match_arm(iter::once(pat.into()), None, value)
1459 let path = make::ext::ident_path("Err");
1460 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1461 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1462 let value = make::expr_path(make::ext::ident_path(err_name));
1464 iter::once(pat.into()),
1466 err.make_result_handler(Some(value)),
1469 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1470 make::expr_match(call_expr, arms)
1476 fn path_expr_from_local(ctx: &AssistContext<'_>, var: Local) -> ast::Expr {
1477 let name = var.name(ctx.db()).to_string();
1478 make::expr_path(make::ext::ident_path(&name))
1482 ctx: &AssistContext<'_>,
1483 module: hir::Module,
1485 old_indent: IndentLevel,
1486 new_indent: IndentLevel,
1488 let mut fn_def = String::new();
1489 let params = fun.make_param_list(ctx, module);
1490 let ret_ty = fun.make_ret_ty(ctx, module);
1491 let body = make_body(ctx, old_indent, new_indent, fun);
1492 let const_kw = if fun.mods.is_const { "const " } else { "" };
1493 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1494 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1495 let (generic_params, where_clause) = make_generic_params_and_where_clause(ctx, fun);
1496 match ctx.config.snippet_cap {
1497 Some(_) => format_to!(
1499 "\n\n{}{}{}{}fn $0{}",
1508 "\n\n{}{}{}{}fn {}",
1517 if let Some(generic_params) = generic_params {
1518 format_to!(fn_def, "{}", generic_params);
1521 format_to!(fn_def, "{}", params);
1523 if let Some(ret_ty) = ret_ty {
1524 format_to!(fn_def, " {}", ret_ty);
1527 if let Some(where_clause) = where_clause {
1528 format_to!(fn_def, " {}", where_clause);
1531 format_to!(fn_def, " {}", body);
1536 fn make_generic_params_and_where_clause(
1537 ctx: &AssistContext<'_>,
1539 ) -> (Option<ast::GenericParamList>, Option<ast::WhereClause>) {
1540 let used_type_params = fun.type_params(ctx);
1542 let generic_param_list = make_generic_param_list(ctx, fun, &used_type_params);
1543 let where_clause = make_where_clause(ctx, fun, &used_type_params);
1545 (generic_param_list, where_clause)
1548 fn make_generic_param_list(
1549 ctx: &AssistContext<'_>,
1551 used_type_params: &[TypeParam],
1552 ) -> Option<ast::GenericParamList> {
1553 let mut generic_params = fun
1555 .generic_param_lists
1557 .flat_map(|parent_params| {
1560 .filter(|param| param_is_required(ctx, param, used_type_params))
1564 if generic_params.peek().is_some() {
1565 Some(make::generic_param_list(generic_params))
1571 fn param_is_required(
1572 ctx: &AssistContext<'_>,
1573 param: &ast::GenericParam,
1574 used_type_params: &[TypeParam],
1577 ast::GenericParam::ConstParam(_) | ast::GenericParam::LifetimeParam(_) => false,
1578 ast::GenericParam::TypeParam(type_param) => match &ctx.sema.to_def(type_param) {
1579 Some(def) => used_type_params.contains(def),
1585 fn make_where_clause(
1586 ctx: &AssistContext<'_>,
1588 used_type_params: &[TypeParam],
1589 ) -> Option<ast::WhereClause> {
1590 let mut predicates = fun
1594 .flat_map(|parent_where_clause| {
1597 .filter(|pred| pred_is_required(ctx, pred, used_type_params))
1601 if predicates.peek().is_some() {
1602 Some(make::where_clause(predicates))
1608 fn pred_is_required(
1609 ctx: &AssistContext<'_>,
1610 pred: &ast::WherePred,
1611 used_type_params: &[TypeParam],
1613 match resolved_type_param(ctx, pred) {
1614 Some(it) => used_type_params.contains(&it),
1619 fn resolved_type_param(ctx: &AssistContext<'_>, pred: &ast::WherePred) -> Option<TypeParam> {
1620 let path = match pred.ty()? {
1621 ast::Type::PathType(path_type) => path_type.path(),
1625 match ctx.sema.resolve_path(&path)? {
1626 PathResolution::TypeParam(type_param) => Some(type_param),
1632 /// Collect all the `TypeParam`s used in the `body` and `params`.
1633 fn type_params(&self, ctx: &AssistContext<'_>) -> Vec<TypeParam> {
1634 let type_params_in_descendant_paths =
1635 self.body.descendant_paths().filter_map(|it| match ctx.sema.resolve_path(&it) {
1636 Some(PathResolution::TypeParam(type_param)) => Some(type_param),
1639 let type_params_in_params = self.params.iter().filter_map(|p| p.ty.as_type_param(ctx.db()));
1640 type_params_in_descendant_paths.chain(type_params_in_params).collect()
1643 fn make_param_list(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::ParamList {
1644 let self_param = self.self_param.clone();
1645 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1646 make::param_list(self_param, params)
1649 fn make_ret_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> Option<ast::RetType> {
1650 let fun_ty = self.return_type(ctx);
1651 let handler = if self.mods.is_in_tail {
1654 FlowHandler::from_ret_ty(self, &fun_ty)
1656 let ret_ty = match &handler {
1657 FlowHandler::None => {
1658 if matches!(fun_ty, FunType::Unit) {
1661 fun_ty.make_ty(ctx, module)
1663 FlowHandler::Try { kind: TryKind::Option } => {
1664 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1666 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1667 let handler_ty = parent_ret_ty
1670 .map(|ty| make_ty(&ty, ctx, module))
1671 .unwrap_or_else(make::ty_placeholder);
1672 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1674 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1675 FlowHandler::IfOption { action } => {
1676 let handler_ty = action
1678 .map(|ty| make_ty(&ty, ctx, module))
1679 .unwrap_or_else(make::ty_placeholder);
1680 make::ext::ty_option(handler_ty)
1682 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1683 FlowHandler::MatchResult { err } => {
1684 let handler_ty = err
1686 .map(|ty| make_ty(&ty, ctx, module))
1687 .unwrap_or_else(make::ty_placeholder);
1688 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1691 Some(make::ret_type(ret_ty))
1696 fn make_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1698 FunType::Unit => make::ty_unit(),
1699 FunType::Single(ty) => make_ty(ty, ctx, module),
1700 FunType::Tuple(types) => match types.as_slice() {
1702 stdx::never!("tuple type with 0 elements");
1706 stdx::never!("tuple type with 1 element");
1707 make_ty(ty, ctx, module)
1710 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1711 make::ty_tuple(types)
1719 ctx: &AssistContext<'_>,
1720 old_indent: IndentLevel,
1721 new_indent: IndentLevel,
1723 ) -> ast::BlockExpr {
1724 let ret_ty = fun.return_type(ctx);
1725 let handler = if fun.mods.is_in_tail {
1728 FlowHandler::from_ret_ty(fun, &ret_ty)
1731 let block = match &fun.body {
1732 FunctionBody::Expr(expr) => {
1733 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1734 let expr = ast::Expr::cast(expr).unwrap();
1736 ast::Expr::BlockExpr(block) => {
1737 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1738 let block = block.dedent(old_indent);
1739 // Recreate the block for formatting consistency with other extracted functions.
1740 make::block_expr(block.statements(), block.tail_expr())
1743 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1745 make::block_expr(Vec::new(), Some(expr))
1749 FunctionBody::Span { parent, text_range } => {
1750 let mut elements: Vec<_> = parent
1752 .children_with_tokens()
1753 .filter(|it| text_range.contains_range(it.text_range()))
1754 .map(|it| match &it {
1755 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1756 rewrite_body_segment(ctx, &fun.params, &handler, n),
1762 let mut tail_expr = match &elements.last() {
1763 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1764 ast::Expr::cast(node.clone())
1773 None => match fun.outliving_locals.as_slice() {
1776 tail_expr = Some(path_expr_from_local(ctx, var.local));
1779 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1780 let expr = make::expr_tuple(exprs);
1781 tail_expr = Some(expr);
1786 let body_indent = IndentLevel(1);
1787 let elements = elements
1789 .map(|node_or_token| match &node_or_token {
1790 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1792 let indented = stmt.dedent(old_indent).indent(body_indent);
1793 let ast_node = indented.syntax().clone_subtree();
1794 syntax::NodeOrToken::Node(ast_node)
1800 .collect::<Vec<SyntaxElement>>();
1801 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1803 make::hacky_block_expr_with_comments(elements, tail_expr)
1807 let block = match &handler {
1808 FlowHandler::None => block,
1809 FlowHandler::Try { kind } => {
1810 let block = with_default_tail_expr(block, make::expr_unit());
1811 map_tail_expr(block, |tail_expr| {
1812 let constructor = match kind {
1813 TryKind::Option => "Some",
1814 TryKind::Result { .. } => "Ok",
1816 let func = make::expr_path(make::ext::ident_path(constructor));
1817 let args = make::arg_list(iter::once(tail_expr));
1818 make::expr_call(func, args)
1821 FlowHandler::If { .. } => {
1822 let controlflow_continue = make::expr_call(
1823 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1824 make::arg_list(iter::once(make::expr_unit())),
1826 with_tail_expr(block, controlflow_continue)
1828 FlowHandler::IfOption { .. } => {
1829 let none = make::expr_path(make::ext::ident_path("None"));
1830 with_tail_expr(block, none)
1832 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1833 let some = make::expr_path(make::ext::ident_path("Some"));
1834 let args = make::arg_list(iter::once(tail_expr));
1835 make::expr_call(some, args)
1837 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1838 let ok = make::expr_path(make::ext::ident_path("Ok"));
1839 let args = make::arg_list(iter::once(tail_expr));
1840 make::expr_call(ok, args)
1844 block.indent(new_indent)
1847 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1848 let tail_expr = match block.tail_expr() {
1849 Some(tail_expr) => tail_expr,
1850 None => return block,
1852 make::block_expr(block.statements(), Some(f(tail_expr)))
1855 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1856 match block.tail_expr() {
1858 None => make::block_expr(block.statements(), Some(tail_expr)),
1862 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1863 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1864 let stmts = block.statements().chain(stmt_tail);
1865 make::block_expr(stmts, Some(tail_expr))
1868 fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String {
1869 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1872 fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1873 let ty_str = format_type(ty, ctx, module);
1877 fn rewrite_body_segment(
1878 ctx: &AssistContext<'_>,
1880 handler: &FlowHandler,
1881 syntax: &SyntaxNode,
1883 let syntax = fix_param_usages(ctx, params, syntax);
1884 update_external_control_flow(handler, &syntax);
1888 /// change all usages to account for added `&`/`&mut` for some params
1889 fn fix_param_usages(ctx: &AssistContext<'_>, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1890 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1892 let tm = TreeMutator::new(syntax);
1894 for param in params {
1895 if !param.kind().is_ref() {
1899 let usages = LocalUsages::find_local_usages(ctx, param.var);
1902 .filter(|reference| syntax.text_range().contains_range(reference.range))
1903 .filter_map(|reference| path_element_of_reference(syntax, reference))
1904 .map(|expr| tm.make_mut(&expr));
1906 usages_for_param.push((param, usages.collect()));
1909 let res = tm.make_syntax_mut(syntax);
1911 for (param, usages) in usages_for_param {
1912 for usage in usages {
1913 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1914 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1917 Some(ast::Expr::RefExpr(node))
1918 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1920 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1922 Some(ast::Expr::RefExpr(node))
1923 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1925 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1928 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1929 ted::replace(usage.syntax(), p.syntax())
1938 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1939 let mut nested_loop = None;
1940 let mut nested_scope = None;
1941 for event in syntax.preorder() {
1943 WalkEvent::Enter(e) => match e.kind() {
1944 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1945 if nested_loop.is_none() {
1946 nested_loop = Some(e.clone());
1951 | SyntaxKind::STATIC
1953 | SyntaxKind::MODULE => {
1954 if nested_scope.is_none() {
1955 nested_scope = Some(e.clone());
1960 WalkEvent::Leave(e) => {
1961 if nested_scope.is_none() {
1962 if let Some(expr) = ast::Expr::cast(e.clone()) {
1964 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1965 let expr = return_expr.expr();
1966 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1967 ted::replace(return_expr.syntax(), replacement.syntax())
1970 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1971 let expr = break_expr.expr();
1972 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1973 ted::replace(break_expr.syntax(), replacement.syntax())
1976 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1977 if let Some(replacement) = make_rewritten_flow(handler, None) {
1978 ted::replace(continue_expr.syntax(), replacement.syntax())
1988 if nested_loop.as_ref() == Some(&e) {
1991 if nested_scope.as_ref() == Some(&e) {
1992 nested_scope = None;
1999 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
2000 let value = match handler {
2001 FlowHandler::None | FlowHandler::Try { .. } => return None,
2002 FlowHandler::If { .. } => make::expr_call(
2003 make::expr_path(make::path_from_text("ControlFlow::Break")),
2004 make::arg_list(iter::once(make::expr_unit())),
2006 FlowHandler::IfOption { .. } => {
2007 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
2008 let args = make::arg_list(iter::once(expr));
2009 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
2011 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
2012 FlowHandler::MatchResult { .. } => {
2013 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
2014 let args = make::arg_list(iter::once(expr));
2015 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
2018 Some(make::expr_return(Some(value)).clone_for_update())
2023 use crate::tests::{check_assist, check_assist_not_applicable};
2028 fn no_args_from_binary_expr() {
2041 fn $0fun_name() -> i32 {
2049 fn no_args_from_binary_expr_in_module() {
2065 fn $0fun_name() -> i32 {
2074 fn no_args_from_binary_expr_indented() {
2087 fn $0fun_name() -> i32 {
2095 fn no_args_from_stmt_with_last_expr() {
2111 fn $0fun_name() -> i32 {
2120 fn no_args_from_stmt_unit() {
2168 fn no_args_if_else() {
2173 $0if true { 1 } else { 2 }$0
2181 fn $0fun_name() -> i32 {
2182 if true { 1 } else { 2 }
2189 fn no_args_if_let_else() {
2194 $0if let true = false { 1 } else { 2 }$0
2202 fn $0fun_name() -> i32 {
2203 if let true = false { 1 } else { 2 }
2210 fn no_args_match() {
2226 fn $0fun_name() -> i32 {
2237 fn no_args_while() {
2263 $0for v in &[0, 1] { }$0
2272 for v in &[0, 1] { }
2279 fn no_args_from_loop_unit() {
2294 fn $0fun_name() -> ! {
2304 fn no_args_from_loop_with_return() {
2320 fn $0fun_name() -> i32 {
2331 fn no_args_from_match() {
2336 let v: i32 = $0match Some(1) {
2344 let v: i32 = fun_name();
2347 fn $0fun_name() -> i32 {
2358 fn extract_partial_block_single_line() {
2364 let mut v = $0n * n;$0
2371 let mut v = fun_name(n);
2375 fn $0fun_name(n: i32) -> i32 {
2384 fn extract_partial_block() {
2391 let mut v = m $0* n;
2401 let (mut v, mut w) = fun_name(m, n);
2406 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2416 fn argument_form_expr() {
2431 fn $0fun_name(n: u32) -> u32 {
2439 fn argument_used_twice_form_expr() {
2454 fn $0fun_name(n: u32) -> u32 {
2462 fn two_arguments_form_expr() {
2479 fn $0fun_name(n: u32, m: u32) -> u32 {
2487 fn argument_and_locals() {
2503 fn $0fun_name(n: u32) -> u32 {
2512 fn in_comment_is_not_applicable() {
2513 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2514 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2518 fn part_of_expr_stmt() {
2531 fn $0fun_name() -> i32 {
2539 fn function_expr() {
2560 fn extract_from_nested() {
2566 let tuple = match x {
2567 true => ($02 + 2$0, true)
2575 let tuple = match x {
2576 true => (fun_name(), true)
2581 fn $0fun_name() -> i32 {
2589 fn param_from_closure() {
2594 let lambda = |x: u32| $0x * 2$0;
2599 let lambda = |x: u32| fun_name(x);
2602 fn $0fun_name(x: u32) -> u32 {
2610 fn extract_return_stmt() {
2623 fn $0fun_name() -> u32 {
2631 fn does_not_add_extra_whitespace() {
2648 fn $0fun_name() -> u32 {
2673 fn $0fun_name() -> i32 {
2686 let v = $00f32 as u32$0;
2694 fn $0fun_name() -> u32 {
2702 fn return_not_applicable() {
2703 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2707 fn method_to_freestanding() {
2714 fn foo(&self) -> i32 {
2723 fn foo(&self) -> i32 {
2728 fn $0fun_name() -> i32 {
2736 fn method_with_reference() {
2740 struct S { f: i32 };
2743 fn foo(&self) -> i32 {
2749 struct S { f: i32 };
2752 fn foo(&self) -> i32 {
2756 fn $0fun_name(&self) -> i32 {
2765 fn method_with_mut() {
2769 struct S { f: i32 };
2778 struct S { f: i32 };
2785 fn $0fun_name(&mut self) {
2794 fn variable_defined_inside_and_used_after_no_ret() {
2807 let k = fun_name(n);
2811 fn $0fun_name(n: i32) -> i32 {
2820 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2826 $0let mut k = n * n;$0
2833 let mut k = fun_name(n);
2837 fn $0fun_name(n: i32) -> i32 {
2846 fn two_variables_defined_inside_and_used_after_no_ret() {
2860 let (k, m) = fun_name(n);
2864 fn $0fun_name(n: i32) -> (i32, i32) {
2874 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2880 $0let mut k = n * n;
2891 let (mut k, mut m, o) = fun_name(n);
2896 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2908 fn nontrivial_patterns_define_variables() {
2912 struct Counter(i32);
2914 $0let Counter(n) = Counter(0);$0
2919 struct Counter(i32);
2925 fn $0fun_name() -> i32 {
2926 let Counter(n) = Counter(0);
2934 fn struct_with_two_fields_pattern_define_variables() {
2938 struct Counter { n: i32, m: i32 };
2940 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2945 struct Counter { n: i32, m: i32 };
2947 let (n, k) = fun_name();
2951 fn $0fun_name() -> (i32, i32) {
2952 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2960 fn mut_var_from_outer_scope() {
2977 fn $0fun_name(n: &mut i32) {
2985 fn mut_field_from_outer_scope() {
2991 let mut c = C { n: 0 };
2999 let mut c = C { n: 0 };
3004 fn $0fun_name(c: &mut C) {
3012 fn mut_nested_field_from_outer_scope() {
3019 let mut c = C { p: P { n: 0 } };
3020 let mut v = C { p: P { n: 0 } };
3021 let u = C { p: P { n: 0 } };
3023 let r = &mut v.p.n;$0
3024 let m = c.p.n + v.p.n + u.p.n;
3031 let mut c = C { p: P { n: 0 } };
3032 let mut v = C { p: P { n: 0 } };
3033 let u = C { p: P { n: 0 } };
3034 fun_name(&mut c, &u, &mut v);
3035 let m = c.p.n + v.p.n + u.p.n;
3038 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
3047 fn mut_param_many_usages_stmt() {
3053 fn succ(&self) -> Self;
3054 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3057 fn succ(&self) -> Self { *self + 1 }
3076 fn succ(&self) -> Self;
3077 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3080 fn succ(&self) -> Self { *self + 1 }
3088 fn $0fun_name(n: &mut i32) {
3104 fn mut_param_many_usages_expr() {
3110 fn succ(&self) -> Self;
3111 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3114 fn succ(&self) -> Self { *self + 1 }
3135 fn succ(&self) -> Self;
3136 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3139 fn succ(&self) -> Self { *self + 1 }
3147 fn $0fun_name(n: &mut i32) {
3163 fn mut_param_by_value() {
3178 fn $0fun_name(mut n: i32) {
3186 fn mut_param_because_of_mut_ref() {
3204 fn $0fun_name(n: &mut i32) {
3213 fn mut_param_by_value_because_of_mut_ref() {
3229 fn $0fun_name(mut n: i32) {
3238 fn mut_method_call() {
3246 fn inc(&mut self) { *self += 1 }
3258 fn inc(&mut self) { *self += 1 }
3265 fn $0fun_name(mut n: i32) {
3273 fn shared_method_call() {
3281 fn succ(&self) { *self + 1 }
3293 fn succ(&self) { *self + 1 }
3300 fn $0fun_name(n: i32) {
3308 fn mut_method_call_with_other_receiver() {
3313 fn inc(&mut self, n: i32);
3316 fn inc(&mut self, n: i32) { *self += n }
3326 fn inc(&mut self, n: i32);
3329 fn inc(&mut self, n: i32) { *self += n }
3336 fn $0fun_name(n: i32) {
3345 fn non_copy_without_usages_after() {
3349 struct Counter(i32);
3356 struct Counter(i32);
3362 fn $0fun_name(c: Counter) {
3370 fn non_copy_used_after() {
3374 struct Counter(i32);
3382 struct Counter(i32);
3389 fn $0fun_name(c: &Counter) {
3397 fn copy_used_after() {
3415 fn $0fun_name(n: i32) {
3423 fn copy_custom_used_after() {
3427 //- minicore: copy, derive
3428 #[derive(Clone, Copy)]
3429 struct Counter(i32);
3437 #[derive(Clone, Copy)]
3438 struct Counter(i32);
3445 fn $0fun_name(c: Counter) {
3453 fn indented_stmts() {
3484 fn indented_stmts_inside_mod() {
3523 //- minicore: option
3538 let k = match fun_name(n) {
3539 Some(value) => value,
3546 fn $0fun_name(n: i32) -> Option<i32> {
3557 fn return_to_parent() {
3561 //- minicore: copy, result
3573 let k = match fun_name(n) {
3575 Err(value) => return value,
3580 fn $0fun_name(n: i32) -> Result<i32, i64> {
3591 fn break_and_continue() {
3592 cov_mark::check!(external_control_flow_break_and_continue);
3593 check_assist_not_applicable(
3612 fn return_and_break() {
3613 cov_mark::check!(external_control_flow_return_and_bc);
3614 check_assist_not_applicable(
3633 fn break_loop_with_if() {
3649 use core::ops::ControlFlow;
3654 if let ControlFlow::Break(_) = fun_name(&mut n) {
3661 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3663 return ControlFlow::Break(());
3665 ControlFlow::Continue(())
3672 fn break_loop_nested() {
3689 use core::ops::ControlFlow;
3694 if let ControlFlow::Break(_) = fun_name(n) {
3701 fn $0fun_name(n: i32) -> ControlFlow<()> {
3704 return ControlFlow::Break(());
3706 ControlFlow::Continue(())
3713 fn break_loop_nested_labeled() {
3727 use core::ops::ControlFlow;
3732 if let ControlFlow::Break(_) = fun_name() {
3739 fn $0fun_name() -> ControlFlow<()> {
3740 return ControlFlow::Break(());
3741 ControlFlow::Continue(())
3748 fn continue_loop_nested_labeled() {
3762 use core::ops::ControlFlow;
3767 if let ControlFlow::Break(_) = fun_name() {
3774 fn $0fun_name() -> ControlFlow<()> {
3775 return ControlFlow::Break(());
3776 ControlFlow::Continue(())
3783 fn return_from_nested_loop() {
3803 let m = match fun_name() {
3804 Some(value) => value,
3811 fn $0fun_name() -> Option<i32> {
3824 fn break_from_nested_loop() {
3849 fn $0fun_name() -> i32 {
3862 fn break_from_nested_and_outer_loops() {
3885 let m = match fun_name() {
3886 Some(value) => value,
3893 fn $0fun_name() -> Option<i32> {
3909 fn return_from_nested_fn() {
3934 fn $0fun_name() -> i32 {
3947 fn break_with_value() {
3967 if let Some(value) = fun_name() {
3974 fn $0fun_name() -> Option<i32> {
3987 fn break_with_value_and_label() {
4007 if let Some(value) = fun_name() {
4014 fn $0fun_name() -> Option<i32> {
4027 fn break_with_value_and_return() {
4047 let m = match fun_name() {
4049 Err(value) => break value,
4055 fn $0fun_name() -> Result<i32, i64> {
4072 //- minicore: option
4073 fn bar() -> Option<i32> { None }
4074 fn foo() -> Option<()> {
4083 fn bar() -> Option<i32> { None }
4084 fn foo() -> Option<()> {
4086 let m = fun_name()?;
4091 fn $0fun_name() -> Option<i32> {
4101 fn try_option_unit() {
4105 //- minicore: option
4106 fn foo() -> Option<()> {
4115 fn foo() -> Option<()> {
4122 fn $0fun_name() -> Option<()> {
4136 //- minicore: result
4137 fn foo() -> Result<(), i64> {
4146 fn foo() -> Result<(), i64> {
4148 let m = fun_name()?;
4153 fn $0fun_name() -> Result<i32, i64> {
4163 fn try_option_with_return() {
4167 //- minicore: option
4168 fn foo() -> Option<()> {
4180 fn foo() -> Option<()> {
4182 let m = fun_name()?;
4187 fn $0fun_name() -> Option<i32> {
4200 fn try_result_with_return() {
4204 //- minicore: result
4205 fn foo() -> Result<(), i64> {
4217 fn foo() -> Result<(), i64> {
4219 let m = fun_name()?;
4224 fn $0fun_name() -> Result<i32, i64> {
4237 fn try_and_break() {
4238 cov_mark::check!(external_control_flow_try_and_bc);
4239 check_assist_not_applicable(
4242 //- minicore: option
4243 fn foo() -> Option<()> {
4259 fn try_and_return_ok() {
4263 //- minicore: result
4264 fn foo() -> Result<(), i64> {
4276 fn foo() -> Result<(), i64> {
4278 let m = fun_name()?;
4283 fn $0fun_name() -> Result<i32, i64> {
4296 fn param_usage_in_macro() {
4301 ($val:expr) => { $val };
4306 $0let k = n * m!(n);$0
4312 ($val:expr) => { $val };
4317 let k = fun_name(n);
4321 fn $0fun_name(n: i32) -> i32 {
4330 fn extract_with_await() {
4334 //- minicore: future
4336 $0some_function().await;$0
4339 async fn some_function() {
4348 async fn $0fun_name() {
4349 some_function().await;
4352 async fn some_function() {
4360 fn extract_with_await_and_result_not_producing_match_expr() {
4364 //- minicore: future, result
4365 async fn foo() -> Result<(), ()> {
4371 async fn foo() -> Result<(), ()> {
4375 async fn $0fun_name() -> Result<(), ()> {
4384 fn extract_with_await_and_result_producing_match_expr() {
4388 //- minicore: future
4389 async fn foo() -> i32 {
4392 let k = async { 1 }.await;
4402 async fn foo() -> i32 {
4405 let m = match fun_name().await {
4407 Err(value) => break value,
4413 async fn $0fun_name() -> Result<i32, i32> {
4414 let k = async { 1 }.await;
4426 fn extract_with_await_in_args() {
4430 //- minicore: future
4432 $0function_call("a", some_function().await);$0
4435 async fn some_function() {
4444 async fn $0fun_name() {
4445 function_call("a", some_function().await);
4448 async fn some_function() {
4456 fn extract_does_not_extract_standalone_blocks() {
4457 check_assist_not_applicable(
4466 fn extract_adds_comma_for_match_arm() {
4485 fn $0fun_name() -> i32 {
4508 fn $0fun_name() -> i32 {
4516 fn extract_does_not_tear_comments_apart() {
4543 fn extract_does_not_tear_body_apart() {
4564 fn extract_does_not_wrap_res_in_res() {
4568 //- minicore: result
4569 fn foo() -> Result<(), i64> {
4570 $0Result::<i32, i64>::Ok(0)?;
4575 fn foo() -> Result<(), i64> {
4579 fn $0fun_name() -> Result<(), i64> {
4580 Result::<i32, i64>::Ok(0)?;
4588 fn extract_knows_const() {
4601 const fn $0fun_name() {
4618 const fn $0fun_name() {
4626 fn extract_does_not_move_outer_loop_vars() {
4645 fn $0fun_name(x: &mut i32) {
4668 fn $0fun_name(mut x: i32) {
4695 fn $0fun_name(x: &mut i32) {
4702 // regression test for #9822
4704 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4710 fn foo(&mut self) {}
4724 fn foo(&mut self) {}
4735 fn $0fun_name(y: &mut Foo) {
4743 fn extract_with_macro_arg() {
4748 ($val:expr) => { $val };
4757 ($val:expr) => { $val };
4764 fn $0fun_name(bar: &str) {
4772 fn unresolveable_types_default_to_placeholder() {
4777 let a = __unresolved;
4783 let a = __unresolved;
4784 let _ = fun_name(a);
4787 fn $0fun_name(a: _) -> _ {
4795 fn reference_mutable_param_with_further_usages() {
4803 pub fn testfn(arg: &mut Foo) {
4805 // Simulating access after the extracted portion
4814 pub fn testfn(arg: &mut Foo) {
4816 // Simulating access after the extracted portion
4820 fn $0fun_name(arg: &mut Foo) {
4828 fn reference_mutable_param_without_further_usages() {
4836 pub fn testfn(arg: &mut Foo) {
4845 pub fn testfn(arg: &mut Foo) {
4849 fn $0fun_name(arg: &mut Foo) {
4857 fn extract_function_copies_comment_at_start() {
4882 fn extract_function_copies_comment_in_between() {
4909 fn extract_function_copies_comment_at_end() {
4934 fn extract_function_copies_comment_indented() {
4962 // FIXME: we do want to preserve whitespace
4964 fn extract_function_does_not_preserve_whitespace() {
4990 fn extract_function_long_form_comment() {
5015 fn it_should_not_generate_duplicate_function_names() {
5036 fn should_increment_suffix_until_it_finds_space() {
5065 fn extract_method_from_trait_impl() {
5071 fn bar(&self) -> i32;
5074 impl Trait for Struct {
5075 fn bar(&self) -> i32 {
5083 fn bar(&self) -> i32;
5086 impl Trait for Struct {
5087 fn bar(&self) -> i32 {
5093 fn $0fun_name(&self) -> i32 {
5102 fn extract_method_from_trait_with_existing_non_empty_impl_block() {
5108 fn bar(&self) -> i32;
5115 impl Trait for Struct {
5116 fn bar(&self) -> i32 {
5124 fn bar(&self) -> i32;
5130 fn $0fun_name(&self) -> i32 {
5135 impl Trait for Struct {
5136 fn bar(&self) -> i32 {
5145 fn extract_function_from_trait_with_existing_non_empty_impl_block() {
5151 fn bar(&self) -> i32;
5158 impl Trait for Struct {
5159 fn bar(&self) -> i32 {
5160 let three_squared = $03 * 3$0;
5161 self.0 + three_squared
5168 fn bar(&self) -> i32;
5175 impl Trait for Struct {
5176 fn bar(&self) -> i32 {
5177 let three_squared = fun_name();
5178 self.0 + three_squared
5182 fn $0fun_name() -> i32 {
5190 fn extract_method_from_trait_with_multiple_existing_impl_blocks() {
5195 struct StructBefore(i32);
5196 struct StructAfter(i32);
5198 fn bar(&self) -> i32;
5213 impl Trait for Struct {
5214 fn bar(&self) -> i32 {
5221 struct StructBefore(i32);
5222 struct StructAfter(i32);
5224 fn bar(&self) -> i32;
5234 fn $0fun_name(&self) -> i32 {
5243 impl Trait for Struct {
5244 fn bar(&self) -> i32 {
5253 fn extract_method_from_trait_with_multiple_existing_trait_impl_blocks() {
5259 fn bar(&self) -> i32;
5262 fn before(&self) -> i32;
5265 fn after(&self) -> i32;
5268 impl TraitBefore for Struct {
5269 fn before(&self) -> i32 {
5278 impl TraitAfter for Struct {
5279 fn after(&self) -> i32 {
5284 impl Trait for Struct {
5285 fn bar(&self) -> i32 {
5293 fn bar(&self) -> i32;
5296 fn before(&self) -> i32;
5299 fn after(&self) -> i32;
5302 impl TraitBefore for Struct {
5303 fn before(&self) -> i32 {
5311 fn $0fun_name(&self) -> i32 {
5316 impl TraitAfter for Struct {
5317 fn after(&self) -> i32 {
5322 impl Trait for Struct {
5323 fn bar(&self) -> i32 {
5332 fn closure_arguments() {
5336 fn parent(factor: i32) {
5339 $0v.iter().map(|it| it * factor);$0
5343 fn parent(factor: i32) {
5346 fun_name(v, factor);
5349 fn $0fun_name(v: &[i32; 3], factor: i32) {
5350 v.iter().map(|it| it * factor);
5357 fn preserve_generics() {
5361 fn func<T: Debug>(i: T) {
5366 fn func<T: Debug>(i: T) {
5370 fn $0fun_name<T: Debug>(i: T) {
5378 fn preserve_generics_from_body() {
5382 fn func<T: Default>() -> T {
5387 fn func<T: Default>() -> T {
5391 fn $0fun_name<T: Default>() -> T {
5399 fn filter_unused_generics() {
5403 fn func<T: Debug, U: Copy>(i: T, u: U) {
5409 fn func<T: Debug, U: Copy>(i: T, u: U) {
5414 fn $0fun_name<T: Debug>(i: T) {
5422 fn empty_generic_param_list() {
5426 fn func<T: Debug>(t: T, i: u32) {
5432 fn func<T: Debug>(t: T, i: u32) {
5437 fn $0fun_name(i: u32) {
5445 fn preserve_where_clause() {
5449 fn func<T>(i: T) where T: Debug {
5454 fn func<T>(i: T) where T: Debug {
5458 fn $0fun_name<T>(i: T) where T: Debug {
5466 fn filter_unused_where_clause() {
5470 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5476 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5481 fn $0fun_name<T>(i: T) where T: Debug {
5489 fn nested_generics() {
5493 struct Struct<T: Into<i32>>(T);
5494 impl <T: Into<i32> + Copy> Struct<T> {
5495 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5497 $0t.into() + v.into()$0
5502 struct Struct<T: Into<i32>>(T);
5503 impl <T: Into<i32> + Copy> Struct<T> {
5504 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5510 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5518 fn filters_unused_nested_generics() {
5522 struct Struct<T: Into<i32>, U: Debug>(T, U);
5523 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5524 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5526 $0t.into() + v.into()$0
5531 struct Struct<T: Into<i32>, U: Debug>(T, U);
5532 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5533 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5539 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5547 fn nested_where_clauses() {
5551 struct Struct<T>(T) where T: Into<i32>;
5552 impl <T> Struct<T> where T: Into<i32> + Copy {
5553 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5555 $0t.into() + v.into()$0
5560 struct Struct<T>(T) where T: Into<i32>;
5561 impl <T> Struct<T> where T: Into<i32> + Copy {
5562 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5568 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
5576 fn filters_unused_nested_where_clauses() {
5580 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5581 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5582 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5584 $0t.into() + v.into()$0
5589 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5590 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5591 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5597 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {