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,
155 ctx.config.prefer_no_std,
158 if let Some(mod_path) = mod_path {
159 insert_use(&scope, mod_path_to_ast(&mod_path), &ctx.config.insert_use);
164 let insert_offset = insert_after.text_range().end();
166 match ctx.config.snippet_cap {
167 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
168 None => builder.insert(insert_offset, fn_def),
174 fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef {
175 let mut names_in_scope = vec![];
176 semantics_scope.process_all_names(&mut |name, _| names_in_scope.push(name.to_string()));
178 let default_name = "fun_name";
180 let mut name = default_name.to_string();
182 while names_in_scope.contains(&name) {
184 name = format!("{default_name}{counter}")
186 make::name_ref(&name)
189 /// Try to guess what user wants to extract
191 /// We have basically have two cases:
192 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
193 /// Then we can use `ast::Expr`
194 /// * We want a few statements for a block. E.g.
196 /// fn foo() -> i32 {
206 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
207 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
209 ast::Stmt::Item(_) => None,
210 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
211 node.parent().and_then(ast::StmtList::cast)?,
217 // Covering element returned the parent block of one or multiple statements that have been selected
218 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
219 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
220 if block_expr.syntax().text_range() == selection_range {
221 return FunctionBody::from_expr(block_expr.into());
225 // Extract the full statements.
226 return Some(FunctionBody::from_range(stmt_list, selection_range));
229 let expr = ast::Expr::cast(node.clone())?;
230 // A node got selected fully
231 if node.text_range() == selection_range {
232 return FunctionBody::from_expr(expr);
235 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
241 self_param: Option<ast::SelfParam>,
243 control_flow: ControlFlow,
246 outliving_locals: Vec<OutlivedLocal>,
259 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
267 #[derive(Debug, Eq, PartialEq)]
271 Tuple(Vec<hir::Type>),
274 /// Where to put extracted function definition
277 /// Extract free function and put right after current top-level function
279 /// Extract method and put right after current function in the impl-block
283 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
284 // probably be merged somehow.
287 kind: Option<FlowKind>,
292 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
293 #[derive(Clone, Debug)]
294 struct ContainerInfo {
297 parent_loop: Option<SyntaxNode>,
298 /// The function's return type, const's type etc.
299 ret_type: Option<hir::Type>,
300 generic_param_lists: Vec<ast::GenericParamList>,
301 where_clauses: Vec<ast::WhereClause>,
304 /// Control flow that is exported from extracted function
316 #[derive(Debug, Clone)]
318 /// Return with value (`return $expr;`)
319 Return(Option<ast::Expr>),
323 /// Break with label and value (`break 'label $expr;`)
324 Break(Option<ast::Lifetime>, Option<ast::Expr>),
325 /// Continue with label (`continue 'label;`)
326 Continue(Option<ast::Lifetime>),
329 #[derive(Debug, Clone)]
332 Result { ty: hir::Type },
342 fn is_unit(&self) -> bool {
344 RetType::Expr(ty) => ty.is_unit(),
345 RetType::Stmt => true,
350 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
351 /// This is the future function body, the part that is being extracted.
355 Span { parent: ast::StmtList, text_range: TextRange },
359 struct OutlivedLocal {
361 mut_usage_outside_body: bool,
364 /// Container of local variable usages
366 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
367 struct LocalUsages(ide_db::search::UsageSearchResult);
370 fn find_local_usages(ctx: &AssistContext<'_>, var: Local) -> Self {
372 Definition::Local(var)
374 .in_scope(SearchScope::single_file(ctx.file_id()))
379 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
380 self.0.iter().flat_map(|(_, rs)| rs)
385 fn return_type(&self, ctx: &AssistContext<'_>) -> FunType {
387 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
388 RetType::Expr(ty) => FunType::Single(ty.clone()),
389 RetType::Stmt => match self.outliving_locals.as_slice() {
391 [var] => FunType::Single(var.local.ty(ctx.db())),
393 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
394 FunType::Tuple(types)
400 fn self_param_adt(&self, ctx: &AssistContext<'_>) -> Option<ast::Adt> {
401 let self_param = self.self_param.as_ref()?;
402 let def = ctx.sema.to_def(self_param)?;
403 let adt = def.ty(ctx.db()).strip_references().as_adt()?;
404 let InFile { file_id: _, value } = adt.source(ctx.db())?;
410 fn is_ref(&self) -> bool {
411 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
416 fn kind(&self) -> ParamKind {
417 match (self.move_local, self.requires_mut, self.is_copy) {
418 (false, true, _) => ParamKind::MutRef,
419 (false, false, false) => ParamKind::SharedRef,
420 (true, true, _) => ParamKind::MutValue,
421 (_, false, _) => ParamKind::Value,
425 fn to_arg(&self, ctx: &AssistContext<'_>) -> ast::Expr {
426 let var = path_expr_from_local(ctx, self.var);
428 ParamKind::Value | ParamKind::MutValue => var,
429 ParamKind::SharedRef => make::expr_ref(var, false),
430 ParamKind::MutRef => make::expr_ref(var, true),
434 fn to_param(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Param {
435 let var = self.var.name(ctx.db()).to_string();
436 let var_name = make::name(&var);
437 let pat = match self.kind() {
438 ParamKind::MutValue => make::ident_pat(false, true, var_name),
439 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
440 make::ext::simple_ident_pat(var_name)
444 let ty = make_ty(&self.ty, ctx, module);
445 let ty = match self.kind() {
446 ParamKind::Value | ParamKind::MutValue => ty,
447 ParamKind::SharedRef => make::ty_ref(ty, false),
448 ParamKind::MutRef => make::ty_ref(ty, true),
451 make::param(pat.into(), ty)
456 fn of_ty(ty: hir::Type, ctx: &AssistContext<'_>) -> Option<TryKind> {
458 // We favour Result for `expr?`
459 return Some(TryKind::Result { ty });
461 let adt = ty.as_adt()?;
462 let name = adt.name(ctx.db());
463 // FIXME: use lang items to determine if it is std type or user defined
464 // E.g. if user happens to define type named `Option`, we would have false positive
465 match name.to_string().as_str() {
466 "Option" => Some(TryKind::Option),
467 "Result" => Some(TryKind::Result { ty }),
474 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
476 FlowKind::Return(_) => make::expr_return(expr),
477 FlowKind::Break(label, _) => make::expr_break(label.clone(), expr),
478 FlowKind::Try { .. } => {
479 stdx::never!("cannot have result handler with try");
480 expr.unwrap_or_else(|| make::expr_return(None))
482 FlowKind::Continue(label) => {
483 stdx::always!(expr.is_none(), "continue with value is not possible");
484 make::expr_continue(label.clone())
489 fn expr_ty(&self, ctx: &AssistContext<'_>) -> Option<hir::Type> {
491 FlowKind::Return(Some(expr)) | FlowKind::Break(_, Some(expr)) => {
492 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
494 FlowKind::Try { .. } => {
495 stdx::never!("try does not have defined expr_ty");
504 fn parent(&self) -> Option<SyntaxNode> {
506 FunctionBody::Expr(expr) => expr.syntax().parent(),
507 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
511 fn node(&self) -> &SyntaxNode {
513 FunctionBody::Expr(e) => e.syntax(),
514 FunctionBody::Span { parent, .. } => parent.syntax(),
518 fn extracted_from_trait_impl(&self) -> bool {
519 match self.node().ancestors().find_map(ast::Impl::cast) {
520 Some(c) => return c.trait_().is_some(),
525 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
527 FunctionBody::Expr(expr) => expr.syntax().descendants(),
528 FunctionBody::Span { parent, .. } => parent.syntax().descendants(),
532 fn descendant_paths(&self) -> impl Iterator<Item = ast::Path> {
533 self.descendants().filter_map(|node| {
536 ast::Path(it) => Some(it),
543 fn from_expr(expr: ast::Expr) -> Option<Self> {
545 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
546 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
547 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
548 expr => Some(Self::Expr(expr)),
552 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
553 let full_body = parent.syntax().children_with_tokens();
555 let mut text_range = full_body
556 .filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
557 .map(|element| element.text_range())
558 .filter(|&range| selected.intersect(range).filter(|it| !it.is_empty()).is_some())
559 .reduce(|acc, stmt| acc.cover(stmt));
561 if let Some(tail_range) = parent
563 .map(|it| it.syntax().text_range())
564 .filter(|&it| selected.intersect(it).is_some())
566 text_range = Some(match text_range {
567 Some(text_range) => text_range.cover(tail_range),
571 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
574 fn indent_level(&self) -> IndentLevel {
576 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
577 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
581 fn tail_expr(&self) -> Option<ast::Expr> {
583 FunctionBody::Expr(expr) => Some(expr.clone()),
584 FunctionBody::Span { parent, text_range } => {
585 let tail_expr = parent.tail_expr()?;
586 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
591 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
593 FunctionBody::Expr(expr) => walk_expr(expr, cb),
594 FunctionBody::Span { parent, text_range } => {
597 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
598 .filter_map(|stmt| match stmt {
599 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
600 ast::Stmt::Item(_) => None,
601 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
603 .for_each(|expr| walk_expr(&expr, cb));
604 if let Some(expr) = parent
606 .filter(|it| text_range.contains_range(it.syntax().text_range()))
608 walk_expr(&expr, cb);
614 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
616 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
617 FunctionBody::Span { parent, text_range } => {
620 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
621 .filter_map(|stmt| match stmt {
622 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
623 ast::Stmt::Item(_) => None,
624 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
626 .for_each(|expr| preorder_expr(&expr, cb));
627 if let Some(expr) = parent
629 .filter(|it| text_range.contains_range(it.syntax().text_range()))
631 preorder_expr(&expr, cb);
637 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
639 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
640 FunctionBody::Span { parent, text_range } => {
643 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
644 .for_each(|stmt| match stmt {
645 ast::Stmt::ExprStmt(expr_stmt) => {
646 if let Some(expr) = expr_stmt.expr() {
647 walk_patterns_in_expr(&expr, cb)
650 ast::Stmt::Item(_) => (),
651 ast::Stmt::LetStmt(stmt) => {
652 if let Some(pat) = stmt.pat() {
655 if let Some(expr) = stmt.initializer() {
656 walk_patterns_in_expr(&expr, cb);
660 if let Some(expr) = parent
662 .filter(|it| text_range.contains_range(it.syntax().text_range()))
664 walk_patterns_in_expr(&expr, cb);
670 fn text_range(&self) -> TextRange {
672 FunctionBody::Expr(expr) => expr.syntax().text_range(),
673 &FunctionBody::Span { text_range, .. } => text_range,
677 fn contains_range(&self, range: TextRange) -> bool {
678 self.text_range().contains_range(range)
681 fn precedes_range(&self, range: TextRange) -> bool {
682 self.text_range().end() <= range.start()
685 fn contains_node(&self, node: &SyntaxNode) -> bool {
686 self.contains_range(node.text_range())
691 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
692 /// whether it contains an await expression.
695 sema: &Semantics<'_, RootDatabase>,
696 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
697 let mut self_param = None;
698 let mut res = FxIndexSet::default();
699 let mut cb = |name_ref: Option<_>| {
701 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
703 NameRefClass::Definition(Definition::Local(local_ref))
704 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
708 let InFile { file_id, value } = local_ref.source(sema.db);
709 // locals defined inside macros are not relevant to us
710 if !file_id.is_macro() {
712 Either::Right(it) => {
713 self_param.replace(it);
716 res.insert(local_ref);
721 self.walk_expr(&mut |expr| match expr {
722 ast::Expr::PathExpr(path_expr) => {
723 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
725 ast::Expr::ClosureExpr(closure_expr) => {
726 if let Some(body) = closure_expr.body() {
727 body.syntax().descendants().map(ast::NameRef::cast).for_each(|it| cb(it));
730 ast::Expr::MacroExpr(expr) => {
731 if let Some(tt) = expr.macro_call().and_then(|call| call.token_tree()) {
733 .children_with_tokens()
734 .flat_map(SyntaxElement::into_token)
735 .filter(|it| it.kind() == SyntaxKind::IDENT)
736 .flat_map(|t| sema.descend_into_macros(t))
737 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
745 fn analyze_container(&self, sema: &Semantics<'_, RootDatabase>) -> Option<ContainerInfo> {
746 let mut ancestors = self.parent()?.ancestors();
747 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
748 let mut parent_loop = None;
749 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
752 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
754 parent_loop.get_or_insert(loop_.syntax().clone());
758 let (is_const, expr, ty) = loop {
759 let anc = ancestors.next()?;
762 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
763 ast::BlockExpr(block_expr) => {
764 let (constness, block) = match block_expr.modifier() {
765 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
766 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
767 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
770 let expr = Some(ast::Expr::BlockExpr(block));
771 (constness, expr.clone(), infer_expr_opt(expr))
774 let func = sema.to_def(&fn_)?;
775 let mut ret_ty = func.ret_type(sema.db);
776 if func.is_async(sema.db) {
777 if let Some(async_ret) = func.async_ret_type(sema.db) {
781 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty))
783 ast::Static(statik) => {
784 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
786 ast::ConstArg(ca) => {
787 (true, ca.expr(), infer_expr_opt(ca.expr()))
789 ast::Const(konst) => {
790 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
792 ast::ConstParam(cp) => {
793 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
795 ast::ConstBlockPat(cbp) => {
796 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
797 (true, expr.clone(), infer_expr_opt(expr))
799 ast::Variant(__) => return None,
800 ast::Meta(__) => return None,
801 ast::LoopExpr(it) => {
802 set_parent_loop(&it);
805 ast::ForExpr(it) => {
806 set_parent_loop(&it);
809 ast::WhileExpr(it) => {
810 set_parent_loop(&it);
817 let container_tail = match expr? {
818 ast::Expr::BlockExpr(block) => block.tail_expr(),
822 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
823 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
826 let parent = self.parent()?;
827 let parents = generic_parents(&parent);
828 let generic_param_lists = parents.iter().filter_map(|it| it.generic_param_list()).collect();
829 let where_clauses = parents.iter().filter_map(|it| it.where_clause()).collect();
841 fn return_ty(&self, ctx: &AssistContext<'_>) -> Option<RetType> {
842 match self.tail_expr() {
843 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
844 None => Some(RetType::Stmt),
848 /// Local variables defined inside `body` that are accessed outside of it
851 ctx: &'a AssistContext<'_>,
853 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
854 let parent = parent.clone();
855 let range = self.text_range();
856 locals_defined_in_body(&ctx.sema, self)
858 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
861 /// Analyses the function body for external control flow.
862 fn external_control_flow(
864 ctx: &AssistContext<'_>,
865 container_info: &ContainerInfo,
866 ) -> Option<ControlFlow> {
867 let mut ret_expr = None;
868 let mut try_expr = None;
869 let mut break_expr = None;
870 let mut continue_expr = None;
871 let mut is_async = false;
872 let mut _is_unsafe = false;
874 let mut unsafe_depth = 0;
875 let mut loop_depth = 0;
877 self.preorder_expr(&mut |expr| {
878 let expr = match expr {
879 WalkEvent::Enter(e) => e,
880 WalkEvent::Leave(expr) => {
882 ast::Expr::LoopExpr(_)
883 | ast::Expr::ForExpr(_)
884 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
885 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
894 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
897 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
900 ast::Expr::ReturnExpr(it) => {
903 ast::Expr::TryExpr(it) => {
906 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
907 break_expr = Some(it);
909 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
910 continue_expr = Some(it);
912 ast::Expr::AwaitExpr(_) => is_async = true,
913 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
914 // to just lift that out of there
915 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
921 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
922 (Some(_), _, None, None) => {
923 let ret_ty = container_info.ret_type.clone()?;
924 let kind = TryKind::of_ty(ret_ty, ctx)?;
926 Some(FlowKind::Try { kind })
928 (Some(_), _, _, _) => {
929 cov_mark::hit!(external_control_flow_try_and_bc);
932 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
933 (None, Some(_), _, _) => {
934 cov_mark::hit!(external_control_flow_return_and_bc);
937 (None, None, Some(_), Some(_)) => {
938 cov_mark::hit!(external_control_flow_break_and_continue);
941 (None, None, Some(b), None) => Some(FlowKind::Break(b.lifetime(), b.expr())),
942 (None, None, None, Some(c)) => Some(FlowKind::Continue(c.lifetime())),
943 (None, None, None, None) => None,
946 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
949 /// find variables that should be extracted as params
951 /// Computes additional info that affects param type and mutability
952 fn extracted_function_params(
954 ctx: &AssistContext<'_>,
955 container_info: &ContainerInfo,
956 locals: impl Iterator<Item = Local>,
959 .map(|local| (local, local.source(ctx.db())))
960 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
961 .filter_map(|(local, src)| match src.value {
962 Either::Left(src) => Some((local, src)),
963 Either::Right(_) => {
964 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
969 let usages = LocalUsages::find_local_usages(ctx, var);
970 let ty = var.ty(ctx.db());
972 let defined_outside_parent_loop = container_info
975 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
977 let is_copy = ty.is_copy(ctx.db());
978 let has_usages = self.has_usages_after_body(&usages);
980 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
981 // We can move the value into the function call if it's not used after the call,
982 // if the var is not used but defined outside a loop we are extracting from we can't move it either
983 // as the function will reuse it in the next iteration.
984 let move_local = (!has_usages && defined_outside_parent_loop) || ty.is_reference();
985 Param { var, ty, move_local, requires_mut, is_copy }
990 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
991 usages.iter().any(|reference| self.precedes_range(reference.range))
1001 impl GenericParent {
1002 fn generic_param_list(&self) -> Option<ast::GenericParamList> {
1004 GenericParent::Fn(fn_) => fn_.generic_param_list(),
1005 GenericParent::Impl(impl_) => impl_.generic_param_list(),
1006 GenericParent::Trait(trait_) => trait_.generic_param_list(),
1010 fn where_clause(&self) -> Option<ast::WhereClause> {
1012 GenericParent::Fn(fn_) => fn_.where_clause(),
1013 GenericParent::Impl(impl_) => impl_.where_clause(),
1014 GenericParent::Trait(trait_) => trait_.where_clause(),
1019 /// Search `parent`'s ancestors for items with potentially applicable generic parameters
1020 fn generic_parents(parent: &SyntaxNode) -> Vec<GenericParent> {
1021 let mut list = Vec::new();
1022 if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) {
1024 ast::Item::Fn(ref fn_) => {
1025 if let Some(parent_parent) = parent_item
1028 .and_then(|it| it.parent())
1029 .and_then(ast::Item::cast)
1031 match parent_parent {
1032 ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)),
1033 ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)),
1037 list.push(GenericParent::Fn(fn_.clone()));
1045 /// checks if relevant var is used with `&mut` access inside body
1046 fn has_exclusive_usages(
1047 ctx: &AssistContext<'_>,
1048 usages: &LocalUsages,
1049 body: &FunctionBody,
1053 .filter(|reference| body.contains_range(reference.range))
1054 .any(|reference| reference_is_exclusive(reference, body, ctx))
1057 /// checks if this reference requires `&mut` access inside node
1058 fn reference_is_exclusive(
1059 reference: &FileReference,
1060 node: &dyn HasTokenAtOffset,
1061 ctx: &AssistContext<'_>,
1063 // we directly modify variable with set: `n = 0`, `n += 1`
1064 if reference.category == Some(ReferenceCategory::Write) {
1068 // we take `&mut` reference to variable: `&mut v`
1069 let path = match path_element_of_reference(node, reference) {
1071 None => return false,
1074 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
1077 /// checks if this expr requires `&mut` access, recurses on field access
1078 fn expr_require_exclusive_access(ctx: &AssistContext<'_>, expr: &ast::Expr) -> Option<bool> {
1079 if let ast::Expr::MacroExpr(_) = expr {
1080 // FIXME: expand macro and check output for mutable usages of the variable?
1084 let parent = expr.syntax().parent()?;
1086 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
1087 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
1088 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
1093 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
1094 return Some(ref_expr.mut_token().is_some());
1097 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
1098 let func = ctx.sema.resolve_method_call(&method_call)?;
1099 let self_param = func.self_param(ctx.db())?;
1100 let access = self_param.access(ctx.db());
1102 return Some(matches!(access, hir::Access::Exclusive));
1105 if let Some(field) = ast::FieldExpr::cast(parent) {
1106 return expr_require_exclusive_access(ctx, &field.into());
1112 trait HasTokenAtOffset {
1113 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
1116 impl HasTokenAtOffset for SyntaxNode {
1117 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1118 SyntaxNode::token_at_offset(self, offset)
1122 impl HasTokenAtOffset for FunctionBody {
1123 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
1125 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
1126 FunctionBody::Span { parent, text_range } => {
1127 match parent.syntax().token_at_offset(offset) {
1128 TokenAtOffset::None => TokenAtOffset::None,
1129 TokenAtOffset::Single(t) => {
1130 if text_range.contains_range(t.text_range()) {
1131 TokenAtOffset::Single(t)
1136 TokenAtOffset::Between(a, b) => {
1138 text_range.contains_range(a.text_range()),
1139 text_range.contains_range(b.text_range()),
1141 (true, true) => TokenAtOffset::Between(a, b),
1142 (true, false) => TokenAtOffset::Single(a),
1143 (false, true) => TokenAtOffset::Single(b),
1144 (false, false) => TokenAtOffset::None,
1153 /// find relevant `ast::Expr` for reference
1157 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
1158 fn path_element_of_reference(
1159 node: &dyn HasTokenAtOffset,
1160 reference: &FileReference,
1161 ) -> Option<ast::Expr> {
1162 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
1163 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
1166 let path = token.parent_ancestors().find_map(ast::Expr::cast).or_else(|| {
1167 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
1171 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroExpr(_)),
1172 "unexpected expression type for variable usage: {:?}",
1178 /// list local variables defined inside `body`
1179 fn locals_defined_in_body(
1180 sema: &Semantics<'_, RootDatabase>,
1181 body: &FunctionBody,
1182 ) -> FxIndexSet<Local> {
1183 // FIXME: this doesn't work well with macros
1184 // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550
1185 let mut res = FxIndexSet::default();
1186 body.walk_pat(&mut |pat| {
1187 if let ast::Pat::IdentPat(pat) = pat {
1188 if let Some(local) = sema.to_def(&pat) {
1196 /// Returns usage details if local variable is used after(outside of) body
1197 fn local_outlives_body(
1198 ctx: &AssistContext<'_>,
1199 body_range: TextRange,
1201 parent: &SyntaxNode,
1202 ) -> Option<OutlivedLocal> {
1203 let usages = LocalUsages::find_local_usages(ctx, local);
1204 let mut has_mut_usages = false;
1205 let mut any_outlives = false;
1206 for usage in usages.iter() {
1207 if body_range.end() <= usage.range.start() {
1208 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1209 any_outlives |= true;
1211 break; // no need to check more elements we have all the info we wanted
1218 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1221 /// checks if the relevant local was defined before(outside of) body
1222 fn is_defined_outside_of_body(
1223 ctx: &AssistContext<'_>,
1224 body: &FunctionBody,
1225 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1227 src.file_id.original_file(ctx.db()) == ctx.file_id()
1228 && !body.contains_node(either_syntax(&src.value))
1231 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1233 Either::Left(pat) => pat.syntax(),
1234 Either::Right(it) => it.syntax(),
1238 /// find where to put extracted function definition
1240 /// Function should be put right after returned node
1241 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1242 let node = body.node();
1243 let mut ancestors = node.ancestors().peekable();
1244 let mut last_ancestor = None;
1245 while let Some(next_ancestor) = ancestors.next() {
1246 match next_ancestor.kind() {
1247 SyntaxKind::SOURCE_FILE => break,
1248 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1249 SyntaxKind::ITEM_LIST => {
1250 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1254 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => continue,
1255 SyntaxKind::ASSOC_ITEM_LIST if body.extracted_from_trait_impl() => continue,
1256 SyntaxKind::ASSOC_ITEM_LIST => {
1257 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1263 last_ancestor = Some(next_ancestor);
1268 fn make_call(ctx: &AssistContext<'_>, fun: &Function, indent: IndentLevel) -> String {
1269 let ret_ty = fun.return_type(ctx);
1271 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1272 let name = fun.name.clone();
1273 let mut call_expr = if fun.self_param.is_some() {
1274 let self_arg = make::expr_path(make::ext::ident_path("self"));
1275 make::expr_method_call(self_arg, name, args)
1277 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1278 make::expr_call(func, args)
1281 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1283 if fun.control_flow.is_async {
1284 call_expr = make::expr_await(call_expr);
1286 let expr = handler.make_call_expr(call_expr).indent(indent);
1288 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1290 let mut buf = String::new();
1291 match fun.outliving_locals.as_slice() {
1294 let modifier = mut_modifier(var);
1295 let name = var.local.name(ctx.db());
1296 format_to!(buf, "let {modifier}{name} = ")
1299 buf.push_str("let (");
1300 let bindings = vars.iter().format_with(", ", |local, f| {
1301 let modifier = mut_modifier(local);
1302 let name = local.local.name(ctx.db());
1303 f(&format_args!("{modifier}{name}"))
1305 format_to!(buf, "{bindings}");
1306 buf.push_str(") = ");
1310 format_to!(buf, "{expr}");
1311 let insert_comma = fun
1314 .and_then(ast::MatchArm::cast)
1315 .map_or(false, |it| it.comma_token().is_none());
1318 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1326 Try { kind: TryKind },
1327 If { action: FlowKind },
1328 IfOption { action: FlowKind },
1329 MatchOption { none: FlowKind },
1330 MatchResult { err: FlowKind },
1334 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1335 match &fun.control_flow.kind {
1336 None => FlowHandler::None,
1337 Some(flow_kind) => {
1338 let action = flow_kind.clone();
1339 if *ret_ty == FunType::Unit {
1341 FlowKind::Return(None)
1342 | FlowKind::Break(_, None)
1343 | FlowKind::Continue(_) => FlowHandler::If { action },
1344 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1345 FlowHandler::IfOption { action }
1347 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1351 FlowKind::Return(None)
1352 | FlowKind::Break(_, None)
1353 | FlowKind::Continue(_) => FlowHandler::MatchOption { none: action },
1354 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1355 FlowHandler::MatchResult { err: action }
1357 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1364 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1366 FlowHandler::None => call_expr,
1367 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1368 FlowHandler::If { action } => {
1369 let action = action.make_result_handler(None);
1370 let stmt = make::expr_stmt(action);
1371 let block = make::block_expr(iter::once(stmt.into()), None);
1372 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1373 let condition = make::expr_let(
1374 make::tuple_struct_pat(
1375 controlflow_break_path,
1376 iter::once(make::wildcard_pat().into()),
1381 make::expr_if(condition.into(), block, None)
1383 FlowHandler::IfOption { action } => {
1384 let path = make::ext::ident_path("Some");
1385 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1386 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1387 let cond = make::expr_let(pattern.into(), call_expr);
1388 let value = make::expr_path(make::ext::ident_path("value"));
1389 let action_expr = action.make_result_handler(Some(value));
1390 let action_stmt = make::expr_stmt(action_expr);
1391 let then = make::block_expr(iter::once(action_stmt.into()), None);
1392 make::expr_if(cond.into(), then, None)
1394 FlowHandler::MatchOption { none } => {
1395 let some_name = "value";
1398 let path = make::ext::ident_path("Some");
1399 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1400 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1401 let value = make::expr_path(make::ext::ident_path(some_name));
1402 make::match_arm(iter::once(pat.into()), None, value)
1405 let path = make::ext::ident_path("None");
1406 let pat = make::path_pat(path);
1407 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1409 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1410 make::expr_match(call_expr, arms)
1412 FlowHandler::MatchResult { err } => {
1413 let ok_name = "value";
1414 let err_name = "value";
1417 let path = make::ext::ident_path("Ok");
1418 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1419 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1420 let value = make::expr_path(make::ext::ident_path(ok_name));
1421 make::match_arm(iter::once(pat.into()), None, value)
1424 let path = make::ext::ident_path("Err");
1425 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1426 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1427 let value = make::expr_path(make::ext::ident_path(err_name));
1429 iter::once(pat.into()),
1431 err.make_result_handler(Some(value)),
1434 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1435 make::expr_match(call_expr, arms)
1441 fn path_expr_from_local(ctx: &AssistContext<'_>, var: Local) -> ast::Expr {
1442 let name = var.name(ctx.db()).to_string();
1443 make::expr_path(make::ext::ident_path(&name))
1447 ctx: &AssistContext<'_>,
1448 module: hir::Module,
1450 old_indent: IndentLevel,
1451 new_indent: IndentLevel,
1453 let mut fn_def = String::new();
1455 let fun_name = &fun.name;
1456 let params = fun.make_param_list(ctx, module);
1457 let ret_ty = fun.make_ret_ty(ctx, module);
1458 let body = make_body(ctx, old_indent, new_indent, fun);
1459 let const_kw = if fun.mods.is_const { "const " } else { "" };
1460 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1461 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1462 let (generic_params, where_clause) = make_generic_params_and_where_clause(ctx, fun);
1464 format_to!(fn_def, "\n\n{new_indent}{const_kw}{async_kw}{unsafe_kw}");
1465 match ctx.config.snippet_cap {
1466 Some(_) => format_to!(fn_def, "fn $0{fun_name}"),
1467 None => format_to!(fn_def, "fn {fun_name}"),
1470 if let Some(generic_params) = generic_params {
1471 format_to!(fn_def, "{generic_params}");
1474 format_to!(fn_def, "{params}");
1476 if let Some(ret_ty) = ret_ty {
1477 format_to!(fn_def, " {ret_ty}");
1480 if let Some(where_clause) = where_clause {
1481 format_to!(fn_def, " {where_clause}");
1484 format_to!(fn_def, " {body}");
1489 fn make_generic_params_and_where_clause(
1490 ctx: &AssistContext<'_>,
1492 ) -> (Option<ast::GenericParamList>, Option<ast::WhereClause>) {
1493 let used_type_params = fun.type_params(ctx);
1495 let generic_param_list = make_generic_param_list(ctx, fun, &used_type_params);
1496 let where_clause = make_where_clause(ctx, fun, &used_type_params);
1498 (generic_param_list, where_clause)
1501 fn make_generic_param_list(
1502 ctx: &AssistContext<'_>,
1504 used_type_params: &[TypeParam],
1505 ) -> Option<ast::GenericParamList> {
1506 let mut generic_params = fun
1508 .generic_param_lists
1510 .flat_map(|parent_params| {
1513 .filter(|param| param_is_required(ctx, param, used_type_params))
1517 if generic_params.peek().is_some() {
1518 Some(make::generic_param_list(generic_params))
1524 fn param_is_required(
1525 ctx: &AssistContext<'_>,
1526 param: &ast::GenericParam,
1527 used_type_params: &[TypeParam],
1530 ast::GenericParam::ConstParam(_) | ast::GenericParam::LifetimeParam(_) => false,
1531 ast::GenericParam::TypeParam(type_param) => match &ctx.sema.to_def(type_param) {
1532 Some(def) => used_type_params.contains(def),
1538 fn make_where_clause(
1539 ctx: &AssistContext<'_>,
1541 used_type_params: &[TypeParam],
1542 ) -> Option<ast::WhereClause> {
1543 let mut predicates = fun
1547 .flat_map(|parent_where_clause| {
1550 .filter(|pred| pred_is_required(ctx, pred, used_type_params))
1554 if predicates.peek().is_some() {
1555 Some(make::where_clause(predicates))
1561 fn pred_is_required(
1562 ctx: &AssistContext<'_>,
1563 pred: &ast::WherePred,
1564 used_type_params: &[TypeParam],
1566 match resolved_type_param(ctx, pred) {
1567 Some(it) => used_type_params.contains(&it),
1572 fn resolved_type_param(ctx: &AssistContext<'_>, pred: &ast::WherePred) -> Option<TypeParam> {
1573 let path = match pred.ty()? {
1574 ast::Type::PathType(path_type) => path_type.path(),
1578 match ctx.sema.resolve_path(&path)? {
1579 PathResolution::TypeParam(type_param) => Some(type_param),
1585 /// Collect all the `TypeParam`s used in the `body` and `params`.
1586 fn type_params(&self, ctx: &AssistContext<'_>) -> Vec<TypeParam> {
1587 let type_params_in_descendant_paths =
1588 self.body.descendant_paths().filter_map(|it| match ctx.sema.resolve_path(&it) {
1589 Some(PathResolution::TypeParam(type_param)) => Some(type_param),
1592 let type_params_in_params = self.params.iter().filter_map(|p| p.ty.as_type_param(ctx.db()));
1593 type_params_in_descendant_paths.chain(type_params_in_params).collect()
1596 fn make_param_list(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::ParamList {
1597 let self_param = self.self_param.clone();
1598 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1599 make::param_list(self_param, params)
1602 fn make_ret_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> Option<ast::RetType> {
1603 let fun_ty = self.return_type(ctx);
1604 let handler = if self.mods.is_in_tail {
1607 FlowHandler::from_ret_ty(self, &fun_ty)
1609 let ret_ty = match &handler {
1610 FlowHandler::None => {
1611 if matches!(fun_ty, FunType::Unit) {
1614 fun_ty.make_ty(ctx, module)
1616 FlowHandler::Try { kind: TryKind::Option } => {
1617 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1619 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1620 let handler_ty = parent_ret_ty
1623 .map(|ty| make_ty(&ty, ctx, module))
1624 .unwrap_or_else(make::ty_placeholder);
1625 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1627 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1628 FlowHandler::IfOption { action } => {
1629 let handler_ty = action
1631 .map(|ty| make_ty(&ty, ctx, module))
1632 .unwrap_or_else(make::ty_placeholder);
1633 make::ext::ty_option(handler_ty)
1635 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1636 FlowHandler::MatchResult { err } => {
1637 let handler_ty = err
1639 .map(|ty| make_ty(&ty, ctx, module))
1640 .unwrap_or_else(make::ty_placeholder);
1641 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1644 Some(make::ret_type(ret_ty))
1649 fn make_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1651 FunType::Unit => make::ty_unit(),
1652 FunType::Single(ty) => make_ty(ty, ctx, module),
1653 FunType::Tuple(types) => match types.as_slice() {
1655 stdx::never!("tuple type with 0 elements");
1659 stdx::never!("tuple type with 1 element");
1660 make_ty(ty, ctx, module)
1663 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1664 make::ty_tuple(types)
1672 ctx: &AssistContext<'_>,
1673 old_indent: IndentLevel,
1674 new_indent: IndentLevel,
1676 ) -> ast::BlockExpr {
1677 let ret_ty = fun.return_type(ctx);
1678 let handler = if fun.mods.is_in_tail {
1681 FlowHandler::from_ret_ty(fun, &ret_ty)
1684 let block = match &fun.body {
1685 FunctionBody::Expr(expr) => {
1686 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1687 let expr = ast::Expr::cast(expr).unwrap();
1689 ast::Expr::BlockExpr(block) => {
1690 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1691 let block = block.dedent(old_indent);
1692 // Recreate the block for formatting consistency with other extracted functions.
1693 make::block_expr(block.statements(), block.tail_expr())
1696 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1698 make::block_expr(Vec::new(), Some(expr))
1702 FunctionBody::Span { parent, text_range } => {
1703 let mut elements: Vec<_> = parent
1705 .children_with_tokens()
1706 .filter(|it| text_range.contains_range(it.text_range()))
1707 .map(|it| match &it {
1708 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1709 rewrite_body_segment(ctx, &fun.params, &handler, n),
1715 let mut tail_expr = match &elements.last() {
1716 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1717 ast::Expr::cast(node.clone())
1726 None => match fun.outliving_locals.as_slice() {
1729 tail_expr = Some(path_expr_from_local(ctx, var.local));
1732 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1733 let expr = make::expr_tuple(exprs);
1734 tail_expr = Some(expr);
1739 let body_indent = IndentLevel(1);
1740 let elements = elements
1742 .map(|node_or_token| match &node_or_token {
1743 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1745 let indented = stmt.dedent(old_indent).indent(body_indent);
1746 let ast_node = indented.syntax().clone_subtree();
1747 syntax::NodeOrToken::Node(ast_node)
1753 .collect::<Vec<SyntaxElement>>();
1754 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1756 make::hacky_block_expr_with_comments(elements, tail_expr)
1760 let block = match &handler {
1761 FlowHandler::None => block,
1762 FlowHandler::Try { kind } => {
1763 let block = with_default_tail_expr(block, make::expr_unit());
1764 map_tail_expr(block, |tail_expr| {
1765 let constructor = match kind {
1766 TryKind::Option => "Some",
1767 TryKind::Result { .. } => "Ok",
1769 let func = make::expr_path(make::ext::ident_path(constructor));
1770 let args = make::arg_list(iter::once(tail_expr));
1771 make::expr_call(func, args)
1774 FlowHandler::If { .. } => {
1775 let controlflow_continue = make::expr_call(
1776 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1777 make::arg_list(iter::once(make::expr_unit())),
1779 with_tail_expr(block, controlflow_continue)
1781 FlowHandler::IfOption { .. } => {
1782 let none = make::expr_path(make::ext::ident_path("None"));
1783 with_tail_expr(block, none)
1785 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1786 let some = make::expr_path(make::ext::ident_path("Some"));
1787 let args = make::arg_list(iter::once(tail_expr));
1788 make::expr_call(some, args)
1790 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1791 let ok = make::expr_path(make::ext::ident_path("Ok"));
1792 let args = make::arg_list(iter::once(tail_expr));
1793 make::expr_call(ok, args)
1797 block.indent(new_indent)
1800 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1801 let tail_expr = match block.tail_expr() {
1802 Some(tail_expr) => tail_expr,
1803 None => return block,
1805 make::block_expr(block.statements(), Some(f(tail_expr)))
1808 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1809 match block.tail_expr() {
1811 None => make::block_expr(block.statements(), Some(tail_expr)),
1815 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1816 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1817 let stmts = block.statements().chain(stmt_tail);
1818 make::block_expr(stmts, Some(tail_expr))
1821 fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String {
1822 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1825 fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1826 let ty_str = format_type(ty, ctx, module);
1830 fn rewrite_body_segment(
1831 ctx: &AssistContext<'_>,
1833 handler: &FlowHandler,
1834 syntax: &SyntaxNode,
1836 let syntax = fix_param_usages(ctx, params, syntax);
1837 update_external_control_flow(handler, &syntax);
1841 /// change all usages to account for added `&`/`&mut` for some params
1842 fn fix_param_usages(ctx: &AssistContext<'_>, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1843 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1845 let tm = TreeMutator::new(syntax);
1847 for param in params {
1848 if !param.kind().is_ref() {
1852 let usages = LocalUsages::find_local_usages(ctx, param.var);
1855 .filter(|reference| syntax.text_range().contains_range(reference.range))
1856 .filter_map(|reference| path_element_of_reference(syntax, reference))
1857 .map(|expr| tm.make_mut(&expr));
1859 usages_for_param.push((param, usages.collect()));
1862 let res = tm.make_syntax_mut(syntax);
1864 for (param, usages) in usages_for_param {
1865 for usage in usages {
1866 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1867 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1870 Some(ast::Expr::RefExpr(node))
1871 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1873 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1875 Some(ast::Expr::RefExpr(node))
1876 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1878 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1881 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1882 ted::replace(usage.syntax(), p.syntax())
1891 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1892 let mut nested_loop = None;
1893 let mut nested_scope = None;
1894 for event in syntax.preorder() {
1896 WalkEvent::Enter(e) => match e.kind() {
1897 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1898 if nested_loop.is_none() {
1899 nested_loop = Some(e.clone());
1904 | SyntaxKind::STATIC
1906 | SyntaxKind::MODULE => {
1907 if nested_scope.is_none() {
1908 nested_scope = Some(e.clone());
1913 WalkEvent::Leave(e) => {
1914 if nested_scope.is_none() {
1915 if let Some(expr) = ast::Expr::cast(e.clone()) {
1917 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1918 let expr = return_expr.expr();
1919 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1920 ted::replace(return_expr.syntax(), replacement.syntax())
1923 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1924 let expr = break_expr.expr();
1925 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1926 ted::replace(break_expr.syntax(), replacement.syntax())
1929 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1930 if let Some(replacement) = make_rewritten_flow(handler, None) {
1931 ted::replace(continue_expr.syntax(), replacement.syntax())
1941 if nested_loop.as_ref() == Some(&e) {
1944 if nested_scope.as_ref() == Some(&e) {
1945 nested_scope = None;
1952 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1953 let value = match handler {
1954 FlowHandler::None | FlowHandler::Try { .. } => return None,
1955 FlowHandler::If { .. } => make::expr_call(
1956 make::expr_path(make::path_from_text("ControlFlow::Break")),
1957 make::arg_list(iter::once(make::expr_unit())),
1959 FlowHandler::IfOption { .. } => {
1960 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1961 let args = make::arg_list(iter::once(expr));
1962 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1964 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1965 FlowHandler::MatchResult { .. } => {
1966 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1967 let args = make::arg_list(iter::once(expr));
1968 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1971 Some(make::expr_return(Some(value)).clone_for_update())
1976 use crate::tests::{check_assist, check_assist_not_applicable};
1981 fn no_args_from_binary_expr() {
1994 fn $0fun_name() -> i32 {
2002 fn no_args_from_binary_expr_in_module() {
2018 fn $0fun_name() -> i32 {
2027 fn no_args_from_binary_expr_indented() {
2040 fn $0fun_name() -> i32 {
2048 fn no_args_from_stmt_with_last_expr() {
2064 fn $0fun_name() -> i32 {
2073 fn no_args_from_stmt_unit() {
2121 fn no_args_if_else() {
2126 $0if true { 1 } else { 2 }$0
2134 fn $0fun_name() -> i32 {
2135 if true { 1 } else { 2 }
2142 fn no_args_if_let_else() {
2147 $0if let true = false { 1 } else { 2 }$0
2155 fn $0fun_name() -> i32 {
2156 if let true = false { 1 } else { 2 }
2163 fn no_args_match() {
2179 fn $0fun_name() -> i32 {
2190 fn no_args_while() {
2216 $0for v in &[0, 1] { }$0
2225 for v in &[0, 1] { }
2232 fn no_args_from_loop_unit() {
2247 fn $0fun_name() -> ! {
2257 fn no_args_from_loop_with_return() {
2273 fn $0fun_name() -> i32 {
2284 fn no_args_from_match() {
2289 let v: i32 = $0match Some(1) {
2297 let v: i32 = fun_name();
2300 fn $0fun_name() -> i32 {
2311 fn extract_partial_block_single_line() {
2317 let mut v = $0n * n;$0
2324 let mut v = fun_name(n);
2328 fn $0fun_name(n: i32) -> i32 {
2337 fn extract_partial_block() {
2344 let mut v = m $0* n;
2354 let (mut v, mut w) = fun_name(m, n);
2359 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2369 fn argument_form_expr() {
2384 fn $0fun_name(n: u32) -> u32 {
2392 fn argument_used_twice_form_expr() {
2407 fn $0fun_name(n: u32) -> u32 {
2415 fn two_arguments_form_expr() {
2432 fn $0fun_name(n: u32, m: u32) -> u32 {
2440 fn argument_and_locals() {
2456 fn $0fun_name(n: u32) -> u32 {
2465 fn in_comment_is_not_applicable() {
2466 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2467 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2471 fn part_of_expr_stmt() {
2484 fn $0fun_name() -> i32 {
2492 fn function_expr() {
2513 fn extract_from_nested() {
2519 let tuple = match x {
2520 true => ($02 + 2$0, true)
2528 let tuple = match x {
2529 true => (fun_name(), true)
2534 fn $0fun_name() -> i32 {
2542 fn param_from_closure() {
2547 let lambda = |x: u32| $0x * 2$0;
2552 let lambda = |x: u32| fun_name(x);
2555 fn $0fun_name(x: u32) -> u32 {
2563 fn extract_return_stmt() {
2576 fn $0fun_name() -> u32 {
2584 fn does_not_add_extra_whitespace() {
2601 fn $0fun_name() -> u32 {
2626 fn $0fun_name() -> i32 {
2639 let v = $00f32 as u32$0;
2647 fn $0fun_name() -> u32 {
2655 fn return_not_applicable() {
2656 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2660 fn method_to_freestanding() {
2667 fn foo(&self) -> i32 {
2676 fn foo(&self) -> i32 {
2681 fn $0fun_name() -> i32 {
2689 fn method_with_reference() {
2693 struct S { f: i32 };
2696 fn foo(&self) -> i32 {
2702 struct S { f: i32 };
2705 fn foo(&self) -> i32 {
2709 fn $0fun_name(&self) -> i32 {
2718 fn method_with_mut() {
2722 struct S { f: i32 };
2731 struct S { f: i32 };
2738 fn $0fun_name(&mut self) {
2747 fn variable_defined_inside_and_used_after_no_ret() {
2760 let k = fun_name(n);
2764 fn $0fun_name(n: i32) -> i32 {
2773 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2779 $0let mut k = n * n;$0
2786 let mut k = fun_name(n);
2790 fn $0fun_name(n: i32) -> i32 {
2799 fn two_variables_defined_inside_and_used_after_no_ret() {
2813 let (k, m) = fun_name(n);
2817 fn $0fun_name(n: i32) -> (i32, i32) {
2827 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2833 $0let mut k = n * n;
2844 let (mut k, mut m, o) = fun_name(n);
2849 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2861 fn nontrivial_patterns_define_variables() {
2865 struct Counter(i32);
2867 $0let Counter(n) = Counter(0);$0
2872 struct Counter(i32);
2878 fn $0fun_name() -> i32 {
2879 let Counter(n) = Counter(0);
2887 fn struct_with_two_fields_pattern_define_variables() {
2891 struct Counter { n: i32, m: i32 };
2893 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2898 struct Counter { n: i32, m: i32 };
2900 let (n, k) = fun_name();
2904 fn $0fun_name() -> (i32, i32) {
2905 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2913 fn mut_var_from_outer_scope() {
2930 fn $0fun_name(n: &mut i32) {
2938 fn mut_field_from_outer_scope() {
2944 let mut c = C { n: 0 };
2952 let mut c = C { n: 0 };
2957 fn $0fun_name(c: &mut C) {
2965 fn mut_nested_field_from_outer_scope() {
2972 let mut c = C { p: P { n: 0 } };
2973 let mut v = C { p: P { n: 0 } };
2974 let u = C { p: P { n: 0 } };
2976 let r = &mut v.p.n;$0
2977 let m = c.p.n + v.p.n + u.p.n;
2984 let mut c = C { p: P { n: 0 } };
2985 let mut v = C { p: P { n: 0 } };
2986 let u = C { p: P { n: 0 } };
2987 fun_name(&mut c, &u, &mut v);
2988 let m = c.p.n + v.p.n + u.p.n;
2991 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
3000 fn mut_param_many_usages_stmt() {
3006 fn succ(&self) -> Self;
3007 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3010 fn succ(&self) -> Self { *self + 1 }
3029 fn succ(&self) -> Self;
3030 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3033 fn succ(&self) -> Self { *self + 1 }
3041 fn $0fun_name(n: &mut i32) {
3057 fn mut_param_many_usages_expr() {
3063 fn succ(&self) -> Self;
3064 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3067 fn succ(&self) -> Self { *self + 1 }
3088 fn succ(&self) -> Self;
3089 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3092 fn succ(&self) -> Self { *self + 1 }
3100 fn $0fun_name(n: &mut i32) {
3116 fn mut_param_by_value() {
3131 fn $0fun_name(mut n: i32) {
3139 fn mut_param_because_of_mut_ref() {
3157 fn $0fun_name(n: &mut i32) {
3166 fn mut_param_by_value_because_of_mut_ref() {
3182 fn $0fun_name(mut n: i32) {
3191 fn mut_method_call() {
3199 fn inc(&mut self) { *self += 1 }
3211 fn inc(&mut self) { *self += 1 }
3218 fn $0fun_name(mut n: i32) {
3226 fn shared_method_call() {
3234 fn succ(&self) { *self + 1 }
3246 fn succ(&self) { *self + 1 }
3253 fn $0fun_name(n: i32) {
3261 fn mut_method_call_with_other_receiver() {
3266 fn inc(&mut self, n: i32);
3269 fn inc(&mut self, n: i32) { *self += n }
3279 fn inc(&mut self, n: i32);
3282 fn inc(&mut self, n: i32) { *self += n }
3289 fn $0fun_name(n: i32) {
3298 fn non_copy_without_usages_after() {
3302 struct Counter(i32);
3309 struct Counter(i32);
3315 fn $0fun_name(c: Counter) {
3323 fn non_copy_used_after() {
3327 struct Counter(i32);
3335 struct Counter(i32);
3342 fn $0fun_name(c: &Counter) {
3350 fn copy_used_after() {
3368 fn $0fun_name(n: i32) {
3376 fn copy_custom_used_after() {
3380 //- minicore: copy, derive
3381 #[derive(Clone, Copy)]
3382 struct Counter(i32);
3390 #[derive(Clone, Copy)]
3391 struct Counter(i32);
3398 fn $0fun_name(c: Counter) {
3406 fn indented_stmts() {
3437 fn indented_stmts_inside_mod() {
3476 //- minicore: option
3491 let k = match fun_name(n) {
3492 Some(value) => value,
3499 fn $0fun_name(n: i32) -> Option<i32> {
3510 fn return_to_parent() {
3514 //- minicore: copy, result
3526 let k = match fun_name(n) {
3528 Err(value) => return value,
3533 fn $0fun_name(n: i32) -> Result<i32, i64> {
3544 fn break_and_continue() {
3545 cov_mark::check!(external_control_flow_break_and_continue);
3546 check_assist_not_applicable(
3565 fn return_and_break() {
3566 cov_mark::check!(external_control_flow_return_and_bc);
3567 check_assist_not_applicable(
3586 fn break_loop_with_if() {
3602 use core::ops::ControlFlow;
3607 if let ControlFlow::Break(_) = fun_name(&mut n) {
3614 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3616 return ControlFlow::Break(());
3618 ControlFlow::Continue(())
3625 fn break_loop_nested() {
3642 use core::ops::ControlFlow;
3647 if let ControlFlow::Break(_) = fun_name(n) {
3654 fn $0fun_name(n: i32) -> ControlFlow<()> {
3657 return ControlFlow::Break(());
3659 ControlFlow::Continue(())
3666 fn break_loop_nested_labeled() {
3680 use core::ops::ControlFlow;
3685 if let ControlFlow::Break(_) = fun_name() {
3692 fn $0fun_name() -> ControlFlow<()> {
3693 return ControlFlow::Break(());
3694 ControlFlow::Continue(())
3701 fn continue_loop_nested_labeled() {
3715 use core::ops::ControlFlow;
3720 if let ControlFlow::Break(_) = fun_name() {
3727 fn $0fun_name() -> ControlFlow<()> {
3728 return ControlFlow::Break(());
3729 ControlFlow::Continue(())
3736 fn return_from_nested_loop() {
3756 let m = match fun_name() {
3757 Some(value) => value,
3764 fn $0fun_name() -> Option<i32> {
3777 fn break_from_nested_loop() {
3802 fn $0fun_name() -> i32 {
3815 fn break_from_nested_and_outer_loops() {
3838 let m = match fun_name() {
3839 Some(value) => value,
3846 fn $0fun_name() -> Option<i32> {
3862 fn return_from_nested_fn() {
3887 fn $0fun_name() -> i32 {
3900 fn break_with_value() {
3920 if let Some(value) = fun_name() {
3927 fn $0fun_name() -> Option<i32> {
3940 fn break_with_value_and_label() {
3960 if let Some(value) = fun_name() {
3967 fn $0fun_name() -> Option<i32> {
3980 fn break_with_value_and_return() {
4000 let m = match fun_name() {
4002 Err(value) => break value,
4008 fn $0fun_name() -> Result<i32, i64> {
4025 //- minicore: option
4026 fn bar() -> Option<i32> { None }
4027 fn foo() -> Option<()> {
4036 fn bar() -> Option<i32> { None }
4037 fn foo() -> Option<()> {
4039 let m = fun_name()?;
4044 fn $0fun_name() -> Option<i32> {
4054 fn try_option_unit() {
4058 //- minicore: option
4059 fn foo() -> Option<()> {
4068 fn foo() -> Option<()> {
4075 fn $0fun_name() -> Option<()> {
4089 //- minicore: result
4090 fn foo() -> Result<(), i64> {
4099 fn foo() -> Result<(), i64> {
4101 let m = fun_name()?;
4106 fn $0fun_name() -> Result<i32, i64> {
4116 fn try_option_with_return() {
4120 //- minicore: option
4121 fn foo() -> Option<()> {
4133 fn foo() -> Option<()> {
4135 let m = fun_name()?;
4140 fn $0fun_name() -> Option<i32> {
4153 fn try_result_with_return() {
4157 //- minicore: result
4158 fn foo() -> Result<(), i64> {
4170 fn foo() -> Result<(), i64> {
4172 let m = fun_name()?;
4177 fn $0fun_name() -> Result<i32, i64> {
4190 fn try_and_break() {
4191 cov_mark::check!(external_control_flow_try_and_bc);
4192 check_assist_not_applicable(
4195 //- minicore: option
4196 fn foo() -> Option<()> {
4212 fn try_and_return_ok() {
4216 //- minicore: result
4217 fn foo() -> Result<(), i64> {
4229 fn foo() -> Result<(), i64> {
4231 let m = fun_name()?;
4236 fn $0fun_name() -> Result<i32, i64> {
4249 fn param_usage_in_macro() {
4254 ($val:expr) => { $val };
4259 $0let k = n * m!(n);$0
4265 ($val:expr) => { $val };
4270 let k = fun_name(n);
4274 fn $0fun_name(n: i32) -> i32 {
4283 fn extract_with_await() {
4287 //- minicore: future
4289 $0some_function().await;$0
4292 async fn some_function() {
4301 async fn $0fun_name() {
4302 some_function().await;
4305 async fn some_function() {
4313 fn extract_with_await_and_result_not_producing_match_expr() {
4317 //- minicore: future, result
4318 async fn foo() -> Result<(), ()> {
4324 async fn foo() -> Result<(), ()> {
4328 async fn $0fun_name() -> Result<(), ()> {
4337 fn extract_with_await_and_result_producing_match_expr() {
4341 //- minicore: future
4342 async fn foo() -> i32 {
4345 let k = async { 1 }.await;
4355 async fn foo() -> i32 {
4358 let m = match fun_name().await {
4360 Err(value) => break value,
4366 async fn $0fun_name() -> Result<i32, i32> {
4367 let k = async { 1 }.await;
4379 fn extract_with_await_in_args() {
4383 //- minicore: future
4385 $0function_call("a", some_function().await);$0
4388 async fn some_function() {
4397 async fn $0fun_name() {
4398 function_call("a", some_function().await);
4401 async fn some_function() {
4409 fn extract_does_not_extract_standalone_blocks() {
4410 check_assist_not_applicable(
4419 fn extract_adds_comma_for_match_arm() {
4438 fn $0fun_name() -> i32 {
4461 fn $0fun_name() -> i32 {
4469 fn extract_does_not_tear_comments_apart() {
4496 fn extract_does_not_tear_body_apart() {
4517 fn extract_does_not_wrap_res_in_res() {
4521 //- minicore: result
4522 fn foo() -> Result<(), i64> {
4523 $0Result::<i32, i64>::Ok(0)?;
4528 fn foo() -> Result<(), i64> {
4532 fn $0fun_name() -> Result<(), i64> {
4533 Result::<i32, i64>::Ok(0)?;
4541 fn extract_knows_const() {
4554 const fn $0fun_name() {
4571 const fn $0fun_name() {
4579 fn extract_does_not_move_outer_loop_vars() {
4598 fn $0fun_name(x: &mut i32) {
4621 fn $0fun_name(mut x: i32) {
4648 fn $0fun_name(x: &mut i32) {
4655 // regression test for #9822
4657 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4663 fn foo(&mut self) {}
4677 fn foo(&mut self) {}
4688 fn $0fun_name(y: &mut Foo) {
4696 fn extract_with_macro_arg() {
4701 ($val:expr) => { $val };
4710 ($val:expr) => { $val };
4717 fn $0fun_name(bar: &str) {
4725 fn unresolveable_types_default_to_placeholder() {
4730 let a = __unresolved;
4736 let a = __unresolved;
4737 let _ = fun_name(a);
4740 fn $0fun_name(a: _) -> _ {
4748 fn reference_mutable_param_with_further_usages() {
4756 pub fn testfn(arg: &mut Foo) {
4758 // Simulating access after the extracted portion
4767 pub fn testfn(arg: &mut Foo) {
4769 // Simulating access after the extracted portion
4773 fn $0fun_name(arg: &mut Foo) {
4781 fn reference_mutable_param_without_further_usages() {
4789 pub fn testfn(arg: &mut Foo) {
4798 pub fn testfn(arg: &mut Foo) {
4802 fn $0fun_name(arg: &mut Foo) {
4810 fn extract_function_copies_comment_at_start() {
4835 fn extract_function_copies_comment_in_between() {
4862 fn extract_function_copies_comment_at_end() {
4887 fn extract_function_copies_comment_indented() {
4915 // FIXME: we do want to preserve whitespace
4917 fn extract_function_does_not_preserve_whitespace() {
4943 fn extract_function_long_form_comment() {
4968 fn it_should_not_generate_duplicate_function_names() {
4989 fn should_increment_suffix_until_it_finds_space() {
5018 fn extract_method_from_trait_impl() {
5024 fn bar(&self) -> i32;
5027 impl Trait for Struct {
5028 fn bar(&self) -> i32 {
5036 fn bar(&self) -> i32;
5039 impl Trait for Struct {
5040 fn bar(&self) -> i32 {
5046 fn $0fun_name(&self) -> i32 {
5055 fn closure_arguments() {
5059 fn parent(factor: i32) {
5062 $0v.iter().map(|it| it * factor);$0
5066 fn parent(factor: i32) {
5069 fun_name(v, factor);
5072 fn $0fun_name(v: &[i32; 3], factor: i32) {
5073 v.iter().map(|it| it * factor);
5080 fn preserve_generics() {
5084 fn func<T: Debug>(i: T) {
5089 fn func<T: Debug>(i: T) {
5093 fn $0fun_name<T: Debug>(i: T) {
5101 fn preserve_generics_from_body() {
5105 fn func<T: Default>() -> T {
5110 fn func<T: Default>() -> T {
5114 fn $0fun_name<T: Default>() -> T {
5122 fn filter_unused_generics() {
5126 fn func<T: Debug, U: Copy>(i: T, u: U) {
5132 fn func<T: Debug, U: Copy>(i: T, u: U) {
5137 fn $0fun_name<T: Debug>(i: T) {
5145 fn empty_generic_param_list() {
5149 fn func<T: Debug>(t: T, i: u32) {
5155 fn func<T: Debug>(t: T, i: u32) {
5160 fn $0fun_name(i: u32) {
5168 fn preserve_where_clause() {
5172 fn func<T>(i: T) where T: Debug {
5177 fn func<T>(i: T) where T: Debug {
5181 fn $0fun_name<T>(i: T) where T: Debug {
5189 fn filter_unused_where_clause() {
5193 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5199 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5204 fn $0fun_name<T>(i: T) where T: Debug {
5212 fn nested_generics() {
5216 struct Struct<T: Into<i32>>(T);
5217 impl <T: Into<i32> + Copy> Struct<T> {
5218 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5220 $0t.into() + v.into()$0
5225 struct Struct<T: Into<i32>>(T);
5226 impl <T: Into<i32> + Copy> Struct<T> {
5227 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5233 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5241 fn filters_unused_nested_generics() {
5245 struct Struct<T: Into<i32>, U: Debug>(T, U);
5246 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5247 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5249 $0t.into() + v.into()$0
5254 struct Struct<T: Into<i32>, U: Debug>(T, U);
5255 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5256 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5262 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5270 fn nested_where_clauses() {
5274 struct Struct<T>(T) where T: Into<i32>;
5275 impl <T> Struct<T> where T: Into<i32> + Copy {
5276 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5278 $0t.into() + v.into()$0
5283 struct Struct<T>(T) where T: Into<i32>;
5284 impl <T> Struct<T> where T: Into<i32> + Copy {
5285 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5291 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
5299 fn filters_unused_nested_where_clauses() {
5303 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5304 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5305 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5307 $0t.into() + v.into()$0
5312 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5313 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5314 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5320 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {