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 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()))
1297 buf.push_str("let (");
1298 let bindings = vars.iter().format_with(", ", |local, f| {
1299 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db())))
1301 format_to!(buf, "{}", bindings);
1302 buf.push_str(") = ");
1306 format_to!(buf, "{}", expr);
1307 let insert_comma = fun
1310 .and_then(ast::MatchArm::cast)
1311 .map_or(false, |it| it.comma_token().is_none());
1314 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1322 Try { kind: TryKind },
1323 If { action: FlowKind },
1324 IfOption { action: FlowKind },
1325 MatchOption { none: FlowKind },
1326 MatchResult { err: FlowKind },
1330 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1331 match &fun.control_flow.kind {
1332 None => FlowHandler::None,
1333 Some(flow_kind) => {
1334 let action = flow_kind.clone();
1335 if *ret_ty == FunType::Unit {
1337 FlowKind::Return(None)
1338 | FlowKind::Break(_, None)
1339 | FlowKind::Continue(_) => FlowHandler::If { action },
1340 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1341 FlowHandler::IfOption { action }
1343 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1347 FlowKind::Return(None)
1348 | FlowKind::Break(_, None)
1349 | FlowKind::Continue(_) => FlowHandler::MatchOption { none: action },
1350 FlowKind::Return(_) | FlowKind::Break(_, _) => {
1351 FlowHandler::MatchResult { err: action }
1353 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1360 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1362 FlowHandler::None => call_expr,
1363 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1364 FlowHandler::If { action } => {
1365 let action = action.make_result_handler(None);
1366 let stmt = make::expr_stmt(action);
1367 let block = make::block_expr(iter::once(stmt.into()), None);
1368 let controlflow_break_path = make::path_from_text("ControlFlow::Break");
1369 let condition = make::expr_let(
1370 make::tuple_struct_pat(
1371 controlflow_break_path,
1372 iter::once(make::wildcard_pat().into()),
1377 make::expr_if(condition.into(), block, None)
1379 FlowHandler::IfOption { action } => {
1380 let path = make::ext::ident_path("Some");
1381 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1382 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1383 let cond = make::expr_let(pattern.into(), call_expr);
1384 let value = make::expr_path(make::ext::ident_path("value"));
1385 let action_expr = action.make_result_handler(Some(value));
1386 let action_stmt = make::expr_stmt(action_expr);
1387 let then = make::block_expr(iter::once(action_stmt.into()), None);
1388 make::expr_if(cond.into(), then, None)
1390 FlowHandler::MatchOption { none } => {
1391 let some_name = "value";
1394 let path = make::ext::ident_path("Some");
1395 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1396 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1397 let value = make::expr_path(make::ext::ident_path(some_name));
1398 make::match_arm(iter::once(pat.into()), None, value)
1401 let path = make::ext::ident_path("None");
1402 let pat = make::path_pat(path);
1403 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1405 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1406 make::expr_match(call_expr, arms)
1408 FlowHandler::MatchResult { err } => {
1409 let ok_name = "value";
1410 let err_name = "value";
1413 let path = make::ext::ident_path("Ok");
1414 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1415 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1416 let value = make::expr_path(make::ext::ident_path(ok_name));
1417 make::match_arm(iter::once(pat.into()), None, value)
1420 let path = make::ext::ident_path("Err");
1421 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1422 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1423 let value = make::expr_path(make::ext::ident_path(err_name));
1425 iter::once(pat.into()),
1427 err.make_result_handler(Some(value)),
1430 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1431 make::expr_match(call_expr, arms)
1437 fn path_expr_from_local(ctx: &AssistContext<'_>, var: Local) -> ast::Expr {
1438 let name = var.name(ctx.db()).to_string();
1439 make::expr_path(make::ext::ident_path(&name))
1443 ctx: &AssistContext<'_>,
1444 module: hir::Module,
1446 old_indent: IndentLevel,
1447 new_indent: IndentLevel,
1449 let mut fn_def = String::new();
1450 let params = fun.make_param_list(ctx, module);
1451 let ret_ty = fun.make_ret_ty(ctx, module);
1452 let body = make_body(ctx, old_indent, new_indent, fun);
1453 let const_kw = if fun.mods.is_const { "const " } else { "" };
1454 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1455 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1456 let (generic_params, where_clause) = make_generic_params_and_where_clause(ctx, fun);
1457 match ctx.config.snippet_cap {
1458 Some(_) => format_to!(
1460 "\n\n{}{}{}{}fn $0{}",
1469 "\n\n{}{}{}{}fn {}",
1478 if let Some(generic_params) = generic_params {
1479 format_to!(fn_def, "{}", generic_params);
1482 format_to!(fn_def, "{}", params);
1484 if let Some(ret_ty) = ret_ty {
1485 format_to!(fn_def, " {}", ret_ty);
1488 if let Some(where_clause) = where_clause {
1489 format_to!(fn_def, " {}", where_clause);
1492 format_to!(fn_def, " {}", body);
1497 fn make_generic_params_and_where_clause(
1498 ctx: &AssistContext<'_>,
1500 ) -> (Option<ast::GenericParamList>, Option<ast::WhereClause>) {
1501 let used_type_params = fun.type_params(ctx);
1503 let generic_param_list = make_generic_param_list(ctx, fun, &used_type_params);
1504 let where_clause = make_where_clause(ctx, fun, &used_type_params);
1506 (generic_param_list, where_clause)
1509 fn make_generic_param_list(
1510 ctx: &AssistContext<'_>,
1512 used_type_params: &[TypeParam],
1513 ) -> Option<ast::GenericParamList> {
1514 let mut generic_params = fun
1516 .generic_param_lists
1518 .flat_map(|parent_params| {
1521 .filter(|param| param_is_required(ctx, param, used_type_params))
1525 if generic_params.peek().is_some() {
1526 Some(make::generic_param_list(generic_params))
1532 fn param_is_required(
1533 ctx: &AssistContext<'_>,
1534 param: &ast::GenericParam,
1535 used_type_params: &[TypeParam],
1538 ast::GenericParam::ConstParam(_) | ast::GenericParam::LifetimeParam(_) => false,
1539 ast::GenericParam::TypeParam(type_param) => match &ctx.sema.to_def(type_param) {
1540 Some(def) => used_type_params.contains(def),
1546 fn make_where_clause(
1547 ctx: &AssistContext<'_>,
1549 used_type_params: &[TypeParam],
1550 ) -> Option<ast::WhereClause> {
1551 let mut predicates = fun
1555 .flat_map(|parent_where_clause| {
1558 .filter(|pred| pred_is_required(ctx, pred, used_type_params))
1562 if predicates.peek().is_some() {
1563 Some(make::where_clause(predicates))
1569 fn pred_is_required(
1570 ctx: &AssistContext<'_>,
1571 pred: &ast::WherePred,
1572 used_type_params: &[TypeParam],
1574 match resolved_type_param(ctx, pred) {
1575 Some(it) => used_type_params.contains(&it),
1580 fn resolved_type_param(ctx: &AssistContext<'_>, pred: &ast::WherePred) -> Option<TypeParam> {
1581 let path = match pred.ty()? {
1582 ast::Type::PathType(path_type) => path_type.path(),
1586 match ctx.sema.resolve_path(&path)? {
1587 PathResolution::TypeParam(type_param) => Some(type_param),
1593 /// Collect all the `TypeParam`s used in the `body` and `params`.
1594 fn type_params(&self, ctx: &AssistContext<'_>) -> Vec<TypeParam> {
1595 let type_params_in_descendant_paths =
1596 self.body.descendant_paths().filter_map(|it| match ctx.sema.resolve_path(&it) {
1597 Some(PathResolution::TypeParam(type_param)) => Some(type_param),
1600 let type_params_in_params = self.params.iter().filter_map(|p| p.ty.as_type_param(ctx.db()));
1601 type_params_in_descendant_paths.chain(type_params_in_params).collect()
1604 fn make_param_list(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::ParamList {
1605 let self_param = self.self_param.clone();
1606 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1607 make::param_list(self_param, params)
1610 fn make_ret_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> Option<ast::RetType> {
1611 let fun_ty = self.return_type(ctx);
1612 let handler = if self.mods.is_in_tail {
1615 FlowHandler::from_ret_ty(self, &fun_ty)
1617 let ret_ty = match &handler {
1618 FlowHandler::None => {
1619 if matches!(fun_ty, FunType::Unit) {
1622 fun_ty.make_ty(ctx, module)
1624 FlowHandler::Try { kind: TryKind::Option } => {
1625 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1627 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1628 let handler_ty = parent_ret_ty
1631 .map(|ty| make_ty(&ty, ctx, module))
1632 .unwrap_or_else(make::ty_placeholder);
1633 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1635 FlowHandler::If { .. } => make::ty("ControlFlow<()>"),
1636 FlowHandler::IfOption { action } => {
1637 let handler_ty = action
1639 .map(|ty| make_ty(&ty, ctx, module))
1640 .unwrap_or_else(make::ty_placeholder);
1641 make::ext::ty_option(handler_ty)
1643 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1644 FlowHandler::MatchResult { err } => {
1645 let handler_ty = err
1647 .map(|ty| make_ty(&ty, ctx, module))
1648 .unwrap_or_else(make::ty_placeholder);
1649 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1652 Some(make::ret_type(ret_ty))
1657 fn make_ty(&self, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1659 FunType::Unit => make::ty_unit(),
1660 FunType::Single(ty) => make_ty(ty, ctx, module),
1661 FunType::Tuple(types) => match types.as_slice() {
1663 stdx::never!("tuple type with 0 elements");
1667 stdx::never!("tuple type with 1 element");
1668 make_ty(ty, ctx, module)
1671 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1672 make::ty_tuple(types)
1680 ctx: &AssistContext<'_>,
1681 old_indent: IndentLevel,
1682 new_indent: IndentLevel,
1684 ) -> ast::BlockExpr {
1685 let ret_ty = fun.return_type(ctx);
1686 let handler = if fun.mods.is_in_tail {
1689 FlowHandler::from_ret_ty(fun, &ret_ty)
1692 let block = match &fun.body {
1693 FunctionBody::Expr(expr) => {
1694 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1695 let expr = ast::Expr::cast(expr).unwrap();
1697 ast::Expr::BlockExpr(block) => {
1698 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1699 let block = block.dedent(old_indent);
1700 // Recreate the block for formatting consistency with other extracted functions.
1701 make::block_expr(block.statements(), block.tail_expr())
1704 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1706 make::block_expr(Vec::new(), Some(expr))
1710 FunctionBody::Span { parent, text_range } => {
1711 let mut elements: Vec<_> = parent
1713 .children_with_tokens()
1714 .filter(|it| text_range.contains_range(it.text_range()))
1715 .map(|it| match &it {
1716 syntax::NodeOrToken::Node(n) => syntax::NodeOrToken::Node(
1717 rewrite_body_segment(ctx, &fun.params, &handler, n),
1723 let mut tail_expr = match &elements.last() {
1724 Some(syntax::NodeOrToken::Node(node)) if ast::Expr::can_cast(node.kind()) => {
1725 ast::Expr::cast(node.clone())
1734 None => match fun.outliving_locals.as_slice() {
1737 tail_expr = Some(path_expr_from_local(ctx, var.local));
1740 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1741 let expr = make::expr_tuple(exprs);
1742 tail_expr = Some(expr);
1747 let body_indent = IndentLevel(1);
1748 let elements = elements
1750 .map(|node_or_token| match &node_or_token {
1751 syntax::NodeOrToken::Node(node) => match ast::Stmt::cast(node.clone()) {
1753 let indented = stmt.dedent(old_indent).indent(body_indent);
1754 let ast_node = indented.syntax().clone_subtree();
1755 syntax::NodeOrToken::Node(ast_node)
1761 .collect::<Vec<SyntaxElement>>();
1762 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1764 make::hacky_block_expr_with_comments(elements, tail_expr)
1768 let block = match &handler {
1769 FlowHandler::None => block,
1770 FlowHandler::Try { kind } => {
1771 let block = with_default_tail_expr(block, make::expr_unit());
1772 map_tail_expr(block, |tail_expr| {
1773 let constructor = match kind {
1774 TryKind::Option => "Some",
1775 TryKind::Result { .. } => "Ok",
1777 let func = make::expr_path(make::ext::ident_path(constructor));
1778 let args = make::arg_list(iter::once(tail_expr));
1779 make::expr_call(func, args)
1782 FlowHandler::If { .. } => {
1783 let controlflow_continue = make::expr_call(
1784 make::expr_path(make::path_from_text("ControlFlow::Continue")),
1785 make::arg_list(iter::once(make::expr_unit())),
1787 with_tail_expr(block, controlflow_continue)
1789 FlowHandler::IfOption { .. } => {
1790 let none = make::expr_path(make::ext::ident_path("None"));
1791 with_tail_expr(block, none)
1793 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1794 let some = make::expr_path(make::ext::ident_path("Some"));
1795 let args = make::arg_list(iter::once(tail_expr));
1796 make::expr_call(some, args)
1798 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1799 let ok = make::expr_path(make::ext::ident_path("Ok"));
1800 let args = make::arg_list(iter::once(tail_expr));
1801 make::expr_call(ok, args)
1805 block.indent(new_indent)
1808 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1809 let tail_expr = match block.tail_expr() {
1810 Some(tail_expr) => tail_expr,
1811 None => return block,
1813 make::block_expr(block.statements(), Some(f(tail_expr)))
1816 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1817 match block.tail_expr() {
1819 None => make::block_expr(block.statements(), Some(tail_expr)),
1823 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1824 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1825 let stmts = block.statements().chain(stmt_tail);
1826 make::block_expr(stmts, Some(tail_expr))
1829 fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String {
1830 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1833 fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type {
1834 let ty_str = format_type(ty, ctx, module);
1838 fn rewrite_body_segment(
1839 ctx: &AssistContext<'_>,
1841 handler: &FlowHandler,
1842 syntax: &SyntaxNode,
1844 let syntax = fix_param_usages(ctx, params, syntax);
1845 update_external_control_flow(handler, &syntax);
1849 /// change all usages to account for added `&`/`&mut` for some params
1850 fn fix_param_usages(ctx: &AssistContext<'_>, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1851 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1853 let tm = TreeMutator::new(syntax);
1855 for param in params {
1856 if !param.kind().is_ref() {
1860 let usages = LocalUsages::find_local_usages(ctx, param.var);
1863 .filter(|reference| syntax.text_range().contains_range(reference.range))
1864 .filter_map(|reference| path_element_of_reference(syntax, reference))
1865 .map(|expr| tm.make_mut(&expr));
1867 usages_for_param.push((param, usages.collect()));
1870 let res = tm.make_syntax_mut(syntax);
1872 for (param, usages) in usages_for_param {
1873 for usage in usages {
1874 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1875 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1878 Some(ast::Expr::RefExpr(node))
1879 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1881 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1883 Some(ast::Expr::RefExpr(node))
1884 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1886 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1889 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1890 ted::replace(usage.syntax(), p.syntax())
1899 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1900 let mut nested_loop = None;
1901 let mut nested_scope = None;
1902 for event in syntax.preorder() {
1904 WalkEvent::Enter(e) => match e.kind() {
1905 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1906 if nested_loop.is_none() {
1907 nested_loop = Some(e.clone());
1912 | SyntaxKind::STATIC
1914 | SyntaxKind::MODULE => {
1915 if nested_scope.is_none() {
1916 nested_scope = Some(e.clone());
1921 WalkEvent::Leave(e) => {
1922 if nested_scope.is_none() {
1923 if let Some(expr) = ast::Expr::cast(e.clone()) {
1925 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1926 let expr = return_expr.expr();
1927 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1928 ted::replace(return_expr.syntax(), replacement.syntax())
1931 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1932 let expr = break_expr.expr();
1933 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1934 ted::replace(break_expr.syntax(), replacement.syntax())
1937 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1938 if let Some(replacement) = make_rewritten_flow(handler, None) {
1939 ted::replace(continue_expr.syntax(), replacement.syntax())
1949 if nested_loop.as_ref() == Some(&e) {
1952 if nested_scope.as_ref() == Some(&e) {
1953 nested_scope = None;
1960 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1961 let value = match handler {
1962 FlowHandler::None | FlowHandler::Try { .. } => return None,
1963 FlowHandler::If { .. } => make::expr_call(
1964 make::expr_path(make::path_from_text("ControlFlow::Break")),
1965 make::arg_list(iter::once(make::expr_unit())),
1967 FlowHandler::IfOption { .. } => {
1968 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1969 let args = make::arg_list(iter::once(expr));
1970 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1972 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1973 FlowHandler::MatchResult { .. } => {
1974 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1975 let args = make::arg_list(iter::once(expr));
1976 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1979 Some(make::expr_return(Some(value)).clone_for_update())
1984 use crate::tests::{check_assist, check_assist_not_applicable};
1989 fn no_args_from_binary_expr() {
2002 fn $0fun_name() -> i32 {
2010 fn no_args_from_binary_expr_in_module() {
2026 fn $0fun_name() -> i32 {
2035 fn no_args_from_binary_expr_indented() {
2048 fn $0fun_name() -> i32 {
2056 fn no_args_from_stmt_with_last_expr() {
2072 fn $0fun_name() -> i32 {
2081 fn no_args_from_stmt_unit() {
2129 fn no_args_if_else() {
2134 $0if true { 1 } else { 2 }$0
2142 fn $0fun_name() -> i32 {
2143 if true { 1 } else { 2 }
2150 fn no_args_if_let_else() {
2155 $0if let true = false { 1 } else { 2 }$0
2163 fn $0fun_name() -> i32 {
2164 if let true = false { 1 } else { 2 }
2171 fn no_args_match() {
2187 fn $0fun_name() -> i32 {
2198 fn no_args_while() {
2224 $0for v in &[0, 1] { }$0
2233 for v in &[0, 1] { }
2240 fn no_args_from_loop_unit() {
2255 fn $0fun_name() -> ! {
2265 fn no_args_from_loop_with_return() {
2281 fn $0fun_name() -> i32 {
2292 fn no_args_from_match() {
2297 let v: i32 = $0match Some(1) {
2305 let v: i32 = fun_name();
2308 fn $0fun_name() -> i32 {
2319 fn extract_partial_block_single_line() {
2325 let mut v = $0n * n;$0
2332 let mut v = fun_name(n);
2336 fn $0fun_name(n: i32) -> i32 {
2345 fn extract_partial_block() {
2352 let mut v = m $0* n;
2362 let (mut v, mut w) = fun_name(m, n);
2367 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2377 fn argument_form_expr() {
2392 fn $0fun_name(n: u32) -> u32 {
2400 fn argument_used_twice_form_expr() {
2415 fn $0fun_name(n: u32) -> u32 {
2423 fn two_arguments_form_expr() {
2440 fn $0fun_name(n: u32, m: u32) -> u32 {
2448 fn argument_and_locals() {
2464 fn $0fun_name(n: u32) -> u32 {
2473 fn in_comment_is_not_applicable() {
2474 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2475 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2479 fn part_of_expr_stmt() {
2492 fn $0fun_name() -> i32 {
2500 fn function_expr() {
2521 fn extract_from_nested() {
2527 let tuple = match x {
2528 true => ($02 + 2$0, true)
2536 let tuple = match x {
2537 true => (fun_name(), true)
2542 fn $0fun_name() -> i32 {
2550 fn param_from_closure() {
2555 let lambda = |x: u32| $0x * 2$0;
2560 let lambda = |x: u32| fun_name(x);
2563 fn $0fun_name(x: u32) -> u32 {
2571 fn extract_return_stmt() {
2584 fn $0fun_name() -> u32 {
2592 fn does_not_add_extra_whitespace() {
2609 fn $0fun_name() -> u32 {
2634 fn $0fun_name() -> i32 {
2647 let v = $00f32 as u32$0;
2655 fn $0fun_name() -> u32 {
2663 fn return_not_applicable() {
2664 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2668 fn method_to_freestanding() {
2675 fn foo(&self) -> i32 {
2684 fn foo(&self) -> i32 {
2689 fn $0fun_name() -> i32 {
2697 fn method_with_reference() {
2701 struct S { f: i32 };
2704 fn foo(&self) -> i32 {
2710 struct S { f: i32 };
2713 fn foo(&self) -> i32 {
2717 fn $0fun_name(&self) -> i32 {
2726 fn method_with_mut() {
2730 struct S { f: i32 };
2739 struct S { f: i32 };
2746 fn $0fun_name(&mut self) {
2755 fn variable_defined_inside_and_used_after_no_ret() {
2768 let k = fun_name(n);
2772 fn $0fun_name(n: i32) -> i32 {
2781 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2787 $0let mut k = n * n;$0
2794 let mut k = fun_name(n);
2798 fn $0fun_name(n: i32) -> i32 {
2807 fn two_variables_defined_inside_and_used_after_no_ret() {
2821 let (k, m) = fun_name(n);
2825 fn $0fun_name(n: i32) -> (i32, i32) {
2835 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2841 $0let mut k = n * n;
2852 let (mut k, mut m, o) = fun_name(n);
2857 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2869 fn nontrivial_patterns_define_variables() {
2873 struct Counter(i32);
2875 $0let Counter(n) = Counter(0);$0
2880 struct Counter(i32);
2886 fn $0fun_name() -> i32 {
2887 let Counter(n) = Counter(0);
2895 fn struct_with_two_fields_pattern_define_variables() {
2899 struct Counter { n: i32, m: i32 };
2901 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2906 struct Counter { n: i32, m: i32 };
2908 let (n, k) = fun_name();
2912 fn $0fun_name() -> (i32, i32) {
2913 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2921 fn mut_var_from_outer_scope() {
2938 fn $0fun_name(n: &mut i32) {
2946 fn mut_field_from_outer_scope() {
2952 let mut c = C { n: 0 };
2960 let mut c = C { n: 0 };
2965 fn $0fun_name(c: &mut C) {
2973 fn mut_nested_field_from_outer_scope() {
2980 let mut c = C { p: P { n: 0 } };
2981 let mut v = C { p: P { n: 0 } };
2982 let u = C { p: P { n: 0 } };
2984 let r = &mut v.p.n;$0
2985 let m = c.p.n + v.p.n + u.p.n;
2992 let mut c = C { p: P { n: 0 } };
2993 let mut v = C { p: P { n: 0 } };
2994 let u = C { p: P { n: 0 } };
2995 fun_name(&mut c, &u, &mut v);
2996 let m = c.p.n + v.p.n + u.p.n;
2999 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
3008 fn mut_param_many_usages_stmt() {
3014 fn succ(&self) -> Self;
3015 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3018 fn succ(&self) -> Self { *self + 1 }
3037 fn succ(&self) -> Self;
3038 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3041 fn succ(&self) -> Self { *self + 1 }
3049 fn $0fun_name(n: &mut i32) {
3065 fn mut_param_many_usages_expr() {
3071 fn succ(&self) -> Self;
3072 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3075 fn succ(&self) -> Self { *self + 1 }
3096 fn succ(&self) -> Self;
3097 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
3100 fn succ(&self) -> Self { *self + 1 }
3108 fn $0fun_name(n: &mut i32) {
3124 fn mut_param_by_value() {
3139 fn $0fun_name(mut n: i32) {
3147 fn mut_param_because_of_mut_ref() {
3165 fn $0fun_name(n: &mut i32) {
3174 fn mut_param_by_value_because_of_mut_ref() {
3190 fn $0fun_name(mut n: i32) {
3199 fn mut_method_call() {
3207 fn inc(&mut self) { *self += 1 }
3219 fn inc(&mut self) { *self += 1 }
3226 fn $0fun_name(mut n: i32) {
3234 fn shared_method_call() {
3242 fn succ(&self) { *self + 1 }
3254 fn succ(&self) { *self + 1 }
3261 fn $0fun_name(n: i32) {
3269 fn mut_method_call_with_other_receiver() {
3274 fn inc(&mut self, n: i32);
3277 fn inc(&mut self, n: i32) { *self += n }
3287 fn inc(&mut self, n: i32);
3290 fn inc(&mut self, n: i32) { *self += n }
3297 fn $0fun_name(n: i32) {
3306 fn non_copy_without_usages_after() {
3310 struct Counter(i32);
3317 struct Counter(i32);
3323 fn $0fun_name(c: Counter) {
3331 fn non_copy_used_after() {
3335 struct Counter(i32);
3343 struct Counter(i32);
3350 fn $0fun_name(c: &Counter) {
3358 fn copy_used_after() {
3376 fn $0fun_name(n: i32) {
3384 fn copy_custom_used_after() {
3388 //- minicore: copy, derive
3389 #[derive(Clone, Copy)]
3390 struct Counter(i32);
3398 #[derive(Clone, Copy)]
3399 struct Counter(i32);
3406 fn $0fun_name(c: Counter) {
3414 fn indented_stmts() {
3445 fn indented_stmts_inside_mod() {
3484 //- minicore: option
3499 let k = match fun_name(n) {
3500 Some(value) => value,
3507 fn $0fun_name(n: i32) -> Option<i32> {
3518 fn return_to_parent() {
3522 //- minicore: copy, result
3534 let k = match fun_name(n) {
3536 Err(value) => return value,
3541 fn $0fun_name(n: i32) -> Result<i32, i64> {
3552 fn break_and_continue() {
3553 cov_mark::check!(external_control_flow_break_and_continue);
3554 check_assist_not_applicable(
3573 fn return_and_break() {
3574 cov_mark::check!(external_control_flow_return_and_bc);
3575 check_assist_not_applicable(
3594 fn break_loop_with_if() {
3610 use core::ops::ControlFlow;
3615 if let ControlFlow::Break(_) = fun_name(&mut n) {
3622 fn $0fun_name(n: &mut i32) -> ControlFlow<()> {
3624 return ControlFlow::Break(());
3626 ControlFlow::Continue(())
3633 fn break_loop_nested() {
3650 use core::ops::ControlFlow;
3655 if let ControlFlow::Break(_) = fun_name(n) {
3662 fn $0fun_name(n: i32) -> ControlFlow<()> {
3665 return ControlFlow::Break(());
3667 ControlFlow::Continue(())
3674 fn break_loop_nested_labeled() {
3688 use core::ops::ControlFlow;
3693 if let ControlFlow::Break(_) = fun_name() {
3700 fn $0fun_name() -> ControlFlow<()> {
3701 return ControlFlow::Break(());
3702 ControlFlow::Continue(())
3709 fn continue_loop_nested_labeled() {
3723 use core::ops::ControlFlow;
3728 if let ControlFlow::Break(_) = fun_name() {
3735 fn $0fun_name() -> ControlFlow<()> {
3736 return ControlFlow::Break(());
3737 ControlFlow::Continue(())
3744 fn return_from_nested_loop() {
3764 let m = match fun_name() {
3765 Some(value) => value,
3772 fn $0fun_name() -> Option<i32> {
3785 fn break_from_nested_loop() {
3810 fn $0fun_name() -> i32 {
3823 fn break_from_nested_and_outer_loops() {
3846 let m = match fun_name() {
3847 Some(value) => value,
3854 fn $0fun_name() -> Option<i32> {
3870 fn return_from_nested_fn() {
3895 fn $0fun_name() -> i32 {
3908 fn break_with_value() {
3928 if let Some(value) = fun_name() {
3935 fn $0fun_name() -> Option<i32> {
3948 fn break_with_value_and_label() {
3968 if let Some(value) = fun_name() {
3975 fn $0fun_name() -> Option<i32> {
3988 fn break_with_value_and_return() {
4008 let m = match fun_name() {
4010 Err(value) => break value,
4016 fn $0fun_name() -> Result<i32, i64> {
4033 //- minicore: option
4034 fn bar() -> Option<i32> { None }
4035 fn foo() -> Option<()> {
4044 fn bar() -> Option<i32> { None }
4045 fn foo() -> Option<()> {
4047 let m = fun_name()?;
4052 fn $0fun_name() -> Option<i32> {
4062 fn try_option_unit() {
4066 //- minicore: option
4067 fn foo() -> Option<()> {
4076 fn foo() -> Option<()> {
4083 fn $0fun_name() -> Option<()> {
4097 //- minicore: result
4098 fn foo() -> Result<(), i64> {
4107 fn foo() -> Result<(), i64> {
4109 let m = fun_name()?;
4114 fn $0fun_name() -> Result<i32, i64> {
4124 fn try_option_with_return() {
4128 //- minicore: option
4129 fn foo() -> Option<()> {
4141 fn foo() -> Option<()> {
4143 let m = fun_name()?;
4148 fn $0fun_name() -> Option<i32> {
4161 fn try_result_with_return() {
4165 //- minicore: result
4166 fn foo() -> Result<(), i64> {
4178 fn foo() -> Result<(), i64> {
4180 let m = fun_name()?;
4185 fn $0fun_name() -> Result<i32, i64> {
4198 fn try_and_break() {
4199 cov_mark::check!(external_control_flow_try_and_bc);
4200 check_assist_not_applicable(
4203 //- minicore: option
4204 fn foo() -> Option<()> {
4220 fn try_and_return_ok() {
4224 //- minicore: result
4225 fn foo() -> Result<(), i64> {
4237 fn foo() -> Result<(), i64> {
4239 let m = fun_name()?;
4244 fn $0fun_name() -> Result<i32, i64> {
4257 fn param_usage_in_macro() {
4262 ($val:expr) => { $val };
4267 $0let k = n * m!(n);$0
4273 ($val:expr) => { $val };
4278 let k = fun_name(n);
4282 fn $0fun_name(n: i32) -> i32 {
4291 fn extract_with_await() {
4295 //- minicore: future
4297 $0some_function().await;$0
4300 async fn some_function() {
4309 async fn $0fun_name() {
4310 some_function().await;
4313 async fn some_function() {
4321 fn extract_with_await_and_result_not_producing_match_expr() {
4325 //- minicore: future, result
4326 async fn foo() -> Result<(), ()> {
4332 async fn foo() -> Result<(), ()> {
4336 async fn $0fun_name() -> Result<(), ()> {
4345 fn extract_with_await_and_result_producing_match_expr() {
4349 //- minicore: future
4350 async fn foo() -> i32 {
4353 let k = async { 1 }.await;
4363 async fn foo() -> i32 {
4366 let m = match fun_name().await {
4368 Err(value) => break value,
4374 async fn $0fun_name() -> Result<i32, i32> {
4375 let k = async { 1 }.await;
4387 fn extract_with_await_in_args() {
4391 //- minicore: future
4393 $0function_call("a", some_function().await);$0
4396 async fn some_function() {
4405 async fn $0fun_name() {
4406 function_call("a", some_function().await);
4409 async fn some_function() {
4417 fn extract_does_not_extract_standalone_blocks() {
4418 check_assist_not_applicable(
4427 fn extract_adds_comma_for_match_arm() {
4446 fn $0fun_name() -> i32 {
4469 fn $0fun_name() -> i32 {
4477 fn extract_does_not_tear_comments_apart() {
4504 fn extract_does_not_tear_body_apart() {
4525 fn extract_does_not_wrap_res_in_res() {
4529 //- minicore: result
4530 fn foo() -> Result<(), i64> {
4531 $0Result::<i32, i64>::Ok(0)?;
4536 fn foo() -> Result<(), i64> {
4540 fn $0fun_name() -> Result<(), i64> {
4541 Result::<i32, i64>::Ok(0)?;
4549 fn extract_knows_const() {
4562 const fn $0fun_name() {
4579 const fn $0fun_name() {
4587 fn extract_does_not_move_outer_loop_vars() {
4606 fn $0fun_name(x: &mut i32) {
4629 fn $0fun_name(mut x: i32) {
4656 fn $0fun_name(x: &mut i32) {
4663 // regression test for #9822
4665 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4671 fn foo(&mut self) {}
4685 fn foo(&mut self) {}
4696 fn $0fun_name(y: &mut Foo) {
4704 fn extract_with_macro_arg() {
4709 ($val:expr) => { $val };
4718 ($val:expr) => { $val };
4725 fn $0fun_name(bar: &str) {
4733 fn unresolveable_types_default_to_placeholder() {
4738 let a = __unresolved;
4744 let a = __unresolved;
4745 let _ = fun_name(a);
4748 fn $0fun_name(a: _) -> _ {
4756 fn reference_mutable_param_with_further_usages() {
4764 pub fn testfn(arg: &mut Foo) {
4766 // Simulating access after the extracted portion
4775 pub fn testfn(arg: &mut Foo) {
4777 // Simulating access after the extracted portion
4781 fn $0fun_name(arg: &mut Foo) {
4789 fn reference_mutable_param_without_further_usages() {
4797 pub fn testfn(arg: &mut Foo) {
4806 pub fn testfn(arg: &mut Foo) {
4810 fn $0fun_name(arg: &mut Foo) {
4818 fn extract_function_copies_comment_at_start() {
4843 fn extract_function_copies_comment_in_between() {
4870 fn extract_function_copies_comment_at_end() {
4895 fn extract_function_copies_comment_indented() {
4923 // FIXME: we do want to preserve whitespace
4925 fn extract_function_does_not_preserve_whitespace() {
4951 fn extract_function_long_form_comment() {
4976 fn it_should_not_generate_duplicate_function_names() {
4997 fn should_increment_suffix_until_it_finds_space() {
5026 fn extract_method_from_trait_impl() {
5032 fn bar(&self) -> i32;
5035 impl Trait for Struct {
5036 fn bar(&self) -> i32 {
5044 fn bar(&self) -> i32;
5047 impl Trait for Struct {
5048 fn bar(&self) -> i32 {
5054 fn $0fun_name(&self) -> i32 {
5063 fn closure_arguments() {
5067 fn parent(factor: i32) {
5070 $0v.iter().map(|it| it * factor);$0
5074 fn parent(factor: i32) {
5077 fun_name(v, factor);
5080 fn $0fun_name(v: &[i32; 3], factor: i32) {
5081 v.iter().map(|it| it * factor);
5088 fn preserve_generics() {
5092 fn func<T: Debug>(i: T) {
5097 fn func<T: Debug>(i: T) {
5101 fn $0fun_name<T: Debug>(i: T) {
5109 fn preserve_generics_from_body() {
5113 fn func<T: Default>() -> T {
5118 fn func<T: Default>() -> T {
5122 fn $0fun_name<T: Default>() -> T {
5130 fn filter_unused_generics() {
5134 fn func<T: Debug, U: Copy>(i: T, u: U) {
5140 fn func<T: Debug, U: Copy>(i: T, u: U) {
5145 fn $0fun_name<T: Debug>(i: T) {
5153 fn empty_generic_param_list() {
5157 fn func<T: Debug>(t: T, i: u32) {
5163 fn func<T: Debug>(t: T, i: u32) {
5168 fn $0fun_name(i: u32) {
5176 fn preserve_where_clause() {
5180 fn func<T>(i: T) where T: Debug {
5185 fn func<T>(i: T) where T: Debug {
5189 fn $0fun_name<T>(i: T) where T: Debug {
5197 fn filter_unused_where_clause() {
5201 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5207 fn func<T, U>(i: T, u: U) where T: Debug, U: Copy {
5212 fn $0fun_name<T>(i: T) where T: Debug {
5220 fn nested_generics() {
5224 struct Struct<T: Into<i32>>(T);
5225 impl <T: Into<i32> + Copy> Struct<T> {
5226 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5228 $0t.into() + v.into()$0
5233 struct Struct<T: Into<i32>>(T);
5234 impl <T: Into<i32> + Copy> Struct<T> {
5235 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5241 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5249 fn filters_unused_nested_generics() {
5253 struct Struct<T: Into<i32>, U: Debug>(T, U);
5254 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5255 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5257 $0t.into() + v.into()$0
5262 struct Struct<T: Into<i32>, U: Debug>(T, U);
5263 impl <T: Into<i32> + Copy, U: Debug> Struct<T, U> {
5264 fn func<V: Into<i32>>(&self, v: V) -> i32 {
5270 fn $0fun_name<T: Into<i32> + Copy, V: Into<i32>>(t: T, v: V) -> i32 {
5278 fn nested_where_clauses() {
5282 struct Struct<T>(T) where T: Into<i32>;
5283 impl <T> Struct<T> where T: Into<i32> + Copy {
5284 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5286 $0t.into() + v.into()$0
5291 struct Struct<T>(T) where T: Into<i32>;
5292 impl <T> Struct<T> where T: Into<i32> + Copy {
5293 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5299 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {
5307 fn filters_unused_nested_where_clauses() {
5311 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5312 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5313 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5315 $0t.into() + v.into()$0
5320 struct Struct<T, U>(T, U) where T: Into<i32>, U: Debug;
5321 impl <T, U> Struct<T, U> where T: Into<i32> + Copy, U: Debug {
5322 fn func<V>(&self, v: V) -> i32 where V: Into<i32> {
5328 fn $0fun_name<T, V>(t: T, v: V) -> i32 where T: Into<i32> + Copy, V: Into<i32> {