5 use hir::{HirDisplay, Local};
7 defs::{Definition, NameRefClass},
8 search::{FileReference, ReferenceAccess, SearchScope},
10 use itertools::Itertools;
16 edit::{AstNodeEdit, IndentLevel},
19 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR},
20 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
24 assist_context::{AssistContext, Assists},
28 // Assist: extract_function
30 // Extracts selected statements into new function.
48 // fn $0fun_name(n: i32) {
53 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
54 if ctx.frange.range.is_empty() {
58 let node = ctx.covering_element();
59 if node.kind() == COMMENT {
60 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
64 let node = match node {
65 syntax::NodeOrToken::Node(n) => n,
66 syntax::NodeOrToken::Token(t) => t.parent()?,
69 let body = extraction_target(&node, ctx.frange.range)?;
71 let vars_used_in_body = vars_used_in_body(ctx, &body);
72 let self_param = self_param_from_usages(ctx, &body, &vars_used_in_body);
74 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
75 let insert_after = scope_for_fn_insertion(&body, anchor)?;
76 let module = ctx.sema.scope(&insert_after).module()?;
78 let vars_defined_in_body_and_outlive = vars_defined_in_body_and_outlive(ctx, &body);
79 let ret_ty = body_return_ty(ctx, &body)?;
81 // FIXME: we compute variables that outlive here just to check `never!` condition
82 // this requires traversing whole `body` (cheap) and finding all references (expensive)
83 // maybe we can move this check to `edit` closure somehow?
84 if stdx::never!(!vars_defined_in_body_and_outlive.is_empty() && !ret_ty.is_unit()) {
85 // We should not have variables that outlive body if we have expression block
88 let control_flow = external_control_flow(ctx, &body)?;
90 let target_range = body.text_range();
93 AssistId("extract_function", crate::AssistKind::RefactorExtract),
94 "Extract into function",
97 let params = extracted_function_params(ctx, &body, &vars_used_in_body);
100 name: "fun_name".to_string(),
101 self_param: self_param.map(|(_, pat)| pat),
106 vars_defined_in_body_and_outlive,
109 let new_indent = IndentLevel::from_node(&insert_after);
110 let old_indent = fun.body.indent_level();
112 builder.replace(target_range, format_replacement(ctx, &fun, old_indent));
114 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
115 let insert_offset = insert_after.text_range().end();
116 match ctx.config.snippet_cap {
117 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
118 None => builder.insert(insert_offset, fn_def),
124 fn external_control_flow(ctx: &AssistContext, body: &FunctionBody) -> Option<ControlFlow> {
125 let mut ret_expr = None;
126 let mut try_expr = None;
127 let mut break_expr = None;
128 let mut continue_expr = None;
129 let (syntax, text_range) = match body {
130 FunctionBody::Expr(expr) => (expr.syntax(), expr.syntax().text_range()),
131 FunctionBody::Span { parent, text_range } => (parent.syntax(), *text_range),
134 let mut nested_loop = None;
135 let mut nested_scope = None;
137 for e in syntax.preorder() {
139 WalkEvent::Enter(e) => e,
140 WalkEvent::Leave(e) => {
141 if nested_loop.as_ref() == Some(&e) {
144 if nested_scope.as_ref() == Some(&e) {
150 if nested_scope.is_some() {
153 if !text_range.contains_range(e.text_range()) {
157 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
158 if nested_loop.is_none() {
159 nested_loop = Some(e);
166 | SyntaxKind::MODULE => {
167 if nested_scope.is_none() {
168 nested_scope = Some(e);
171 SyntaxKind::RETURN_EXPR => {
172 ret_expr = Some(ast::ReturnExpr::cast(e).unwrap());
174 SyntaxKind::TRY_EXPR => {
175 try_expr = Some(ast::TryExpr::cast(e).unwrap());
177 SyntaxKind::BREAK_EXPR if nested_loop.is_none() => {
178 break_expr = Some(ast::BreakExpr::cast(e).unwrap());
180 SyntaxKind::CONTINUE_EXPR if nested_loop.is_none() => {
181 continue_expr = Some(ast::ContinueExpr::cast(e).unwrap());
187 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
188 (Some(e), None, None, None) => {
189 let func = e.syntax().ancestors().find_map(ast::Fn::cast)?;
190 let def = ctx.sema.to_def(&func)?;
191 let ret_ty = def.ret_type(ctx.db());
192 let kind = try_kind_of_ty(ret_ty, ctx)?;
194 Some(FlowKind::Try { kind })
196 (Some(_), Some(r), None, None) => match r.expr() {
198 if let Some(kind) = expr_err_kind(&expr, ctx) {
199 Some(FlowKind::TryReturn { expr, kind })
201 cov_mark::hit!(external_control_flow_try_and_return_non_err);
207 (Some(_), _, _, _) => {
208 cov_mark::hit!(external_control_flow_try_and_bc);
211 (None, Some(r), None, None) => match r.expr() {
212 Some(expr) => Some(FlowKind::ReturnValue(expr)),
213 None => Some(FlowKind::Return),
215 (None, Some(_), _, _) => {
216 cov_mark::hit!(external_control_flow_return_and_bc);
219 (None, None, Some(_), Some(_)) => {
220 cov_mark::hit!(external_control_flow_break_and_continue);
223 (None, None, Some(b), None) => match b.expr() {
224 Some(expr) => Some(FlowKind::BreakValue(expr)),
225 None => Some(FlowKind::Break),
227 (None, None, None, Some(_)) => Some(FlowKind::Continue),
228 (None, None, None, None) => None,
231 Some(ControlFlow { kind })
234 /// Checks is expr is `Err(_)` or `None`
235 fn expr_err_kind(expr: &ast::Expr, ctx: &AssistContext) -> Option<TryKind> {
236 let func_name = match expr {
237 ast::Expr::CallExpr(call_expr) => call_expr.expr()?,
238 ast::Expr::PathExpr(_) => expr.clone(),
241 let text = func_name.syntax().text();
244 Some(TryKind::Result { ty: ctx.sema.type_of_expr(expr)? })
245 } else if text == "None" {
246 Some(TryKind::Option)
255 self_param: Option<ast::SelfParam>,
257 control_flow: ControlFlow,
260 vars_defined_in_body_and_outlive: Vec<Local>,
267 has_usages_afterwards: bool,
268 has_mut_inside_body: bool,
274 kind: Option<FlowKind>,
277 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
285 #[derive(Debug, Eq, PartialEq)]
289 Tuple(Vec<hir::Type>),
293 fn return_type(&self, ctx: &AssistContext) -> FunType {
295 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
296 RetType::Expr(ty) => FunType::Single(ty.clone()),
297 RetType::Stmt => match self.vars_defined_in_body_and_outlive.as_slice() {
299 [var] => FunType::Single(var.ty(ctx.db())),
301 let types = vars.iter().map(|v| v.ty(ctx.db())).collect();
302 FunType::Tuple(types)
310 fn is_ref(&self) -> bool {
311 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
316 fn kind(&self) -> ParamKind {
317 match (self.has_usages_afterwards, self.has_mut_inside_body, self.is_copy) {
318 (true, true, _) => ParamKind::MutRef,
319 (true, false, false) => ParamKind::SharedRef,
320 (false, true, _) => ParamKind::MutValue,
321 (true, false, true) | (false, false, _) => ParamKind::Value,
325 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
326 let var = path_expr_from_local(ctx, self.var);
328 ParamKind::Value | ParamKind::MutValue => var,
329 ParamKind::SharedRef => make::expr_ref(var, false),
330 ParamKind::MutRef => make::expr_ref(var, true),
334 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
335 let var = self.var.name(ctx.db()).unwrap().to_string();
336 let var_name = make::name(&var);
337 let pat = match self.kind() {
338 ParamKind::MutValue => make::ident_mut_pat(var_name),
339 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
340 make::ident_pat(var_name)
344 let ty = make_ty(&self.ty, ctx, module);
345 let ty = match self.kind() {
346 ParamKind::Value | ParamKind::MutValue => ty,
347 ParamKind::SharedRef => make::ty_ref(ty, false),
348 ParamKind::MutRef => make::ty_ref(ty, true),
351 make::param(pat.into(), ty)
355 /// Control flow that is exported from extracted function
367 #[derive(Debug, Clone)]
369 /// Return without value (`return;`)
371 /// Return with value (`return $expr;`)
372 ReturnValue(ast::Expr),
380 /// Break without value (`return;`)
382 /// Break with value (`break $expr;`)
383 BreakValue(ast::Expr),
388 #[derive(Debug, Clone)]
391 Result { ty: hir::Type },
395 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
397 FlowKind::Return | FlowKind::ReturnValue(_) => make::expr_return(expr),
398 FlowKind::Break | FlowKind::BreakValue(_) => make::expr_break(expr),
399 FlowKind::Try { .. } | FlowKind::TryReturn { .. } => {
400 stdx::never!("cannot have result handler with try");
401 expr.unwrap_or_else(|| make::expr_return(None))
403 FlowKind::Continue => {
404 stdx::always!(expr.is_none(), "continue with value is not possible");
405 make::expr_continue()
410 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
412 FlowKind::ReturnValue(expr)
413 | FlowKind::BreakValue(expr)
414 | FlowKind::TryReturn { expr, .. } => ctx.sema.type_of_expr(expr),
415 FlowKind::Try { .. } => {
416 stdx::never!("try does not have defined expr_ty");
419 FlowKind::Return | FlowKind::Break | FlowKind::Continue => None,
424 fn try_kind_of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
426 // We favour Result for `expr?`
427 return Some(TryKind::Result { ty });
429 let adt = ty.as_adt()?;
430 let name = adt.name(ctx.db());
431 // FIXME: use lang items to determine if it is std type or user defined
432 // E.g. if user happens to define type named `Option`, we would have false positive
433 match name.to_string().as_str() {
434 "Option" => Some(TryKind::Option),
435 "Result" => Some(TryKind::Result { ty }),
447 fn is_unit(&self) -> bool {
449 RetType::Expr(ty) => ty.is_unit(),
450 RetType::Stmt => true,
455 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
459 Span { parent: ast::BlockExpr, text_range: TextRange },
463 fn from_whole_node(node: SyntaxNode) -> Option<Self> {
466 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
467 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
468 BLOCK_EXPR => ast::BlockExpr::cast(node)
469 .filter(|it| it.is_standalone())
472 _ => ast::Expr::cast(node).map(Self::Expr),
476 fn from_range(node: SyntaxNode, text_range: TextRange) -> Option<FunctionBody> {
477 let block = ast::BlockExpr::cast(node)?;
478 Some(Self::Span { parent: block, text_range })
481 fn indent_level(&self) -> IndentLevel {
483 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
484 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
488 fn tail_expr(&self) -> Option<ast::Expr> {
490 FunctionBody::Expr(expr) => Some(expr.clone()),
491 FunctionBody::Span { parent, text_range } => {
492 let tail_expr = parent.tail_expr()?;
493 if text_range.contains_range(tail_expr.syntax().text_range()) {
502 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
504 FunctionBody::Expr(expr) => Either::Right(expr.syntax().descendants()),
505 FunctionBody::Span { parent, text_range } => Either::Left(
509 .filter(move |it| text_range.contains_range(it.text_range())),
514 fn text_range(&self) -> TextRange {
516 FunctionBody::Expr(expr) => expr.syntax().text_range(),
517 FunctionBody::Span { parent: _, text_range } => *text_range,
521 fn contains_range(&self, range: TextRange) -> bool {
522 self.text_range().contains_range(range)
525 fn preceedes_range(&self, range: TextRange) -> bool {
526 self.text_range().end() <= range.start()
529 fn contains_node(&self, node: &SyntaxNode) -> bool {
530 self.contains_range(node.text_range())
534 impl HasTokenAtOffset for FunctionBody {
535 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
537 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
538 FunctionBody::Span { parent, text_range } => {
539 match parent.syntax().token_at_offset(offset) {
540 TokenAtOffset::None => TokenAtOffset::None,
541 TokenAtOffset::Single(t) => {
542 if text_range.contains_range(t.text_range()) {
543 TokenAtOffset::Single(t)
548 TokenAtOffset::Between(a, b) => {
550 text_range.contains_range(a.text_range()),
551 text_range.contains_range(b.text_range()),
553 (true, true) => TokenAtOffset::Between(a, b),
554 (true, false) => TokenAtOffset::Single(a),
555 (false, true) => TokenAtOffset::Single(b),
556 (false, false) => TokenAtOffset::None,
565 /// Try to guess what user wants to extract
567 /// We have basically have two cases:
568 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
569 /// Then we can use `ast::Expr`
570 /// * We want a few statements for a block. E.g.
572 /// fn foo() -> i32 {
582 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
583 // we have selected exactly the expr node
584 // wrap it before anything else
585 if node.text_range() == selection_range {
586 let body = FunctionBody::from_whole_node(node.clone());
592 // we have selected a few statements in a block
593 // so covering_element returns the whole block
594 if node.kind() == BLOCK_EXPR {
595 let body = FunctionBody::from_range(node.clone(), selection_range);
601 // we have selected single statement
602 // `from_whole_node` failed because (let) statement is not and expression
603 // so we try to expand covering_element to parent and repeat the previous
604 if let Some(parent) = node.parent() {
605 if parent.kind() == BLOCK_EXPR {
606 let body = FunctionBody::from_range(parent, selection_range);
613 // select the closest containing expr (both ifs are used)
614 std::iter::once(node.clone()).chain(node.ancestors()).find_map(FunctionBody::from_whole_node)
617 /// list local variables that are referenced in `body`
618 fn vars_used_in_body(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
619 // FIXME: currently usages inside macros are not found
621 .filter_map(ast::NameRef::cast)
622 .filter_map(|name_ref| NameRefClass::classify(&ctx.sema, &name_ref))
623 .map(|name_kind| name_kind.referenced(ctx.db()))
624 .filter_map(|definition| match definition {
625 Definition::Local(local) => Some(local),
632 /// find `self` param, that was not defined inside `body`
634 /// It should skip `self` params from impls inside `body`
635 fn self_param_from_usages(
638 vars_used_in_body: &[Local],
639 ) -> Option<(Local, ast::SelfParam)> {
640 let mut iter = vars_used_in_body
642 .filter(|var| var.is_self(ctx.db()))
643 .map(|var| (var, var.source(ctx.db())))
644 .filter(|(_, src)| is_defined_before(ctx, body, src))
645 .filter_map(|(&node, src)| match src.value {
646 Either::Right(it) => Some((node, it)),
648 stdx::never!(false, "Local::is_self returned true, but source is IdentPat");
653 let self_param = iter.next();
655 iter.next().is_none(),
656 "body references two different self params, both defined outside"
662 /// find variables that should be extracted as params
664 /// Computes additional info that affects param type and mutability
665 fn extracted_function_params(
668 vars_used_in_body: &[Local],
672 .filter(|var| !var.is_self(ctx.db()))
673 .map(|node| (node, node.source(ctx.db())))
674 .filter(|(_, src)| is_defined_before(ctx, body, src))
675 .filter_map(|(&node, src)| {
676 if src.value.is_left() {
679 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
684 let usages = LocalUsages::find(ctx, var);
685 let ty = var.ty(ctx.db());
686 let is_copy = ty.is_copy(ctx.db());
690 has_usages_afterwards: has_usages_after_body(&usages, body),
691 has_mut_inside_body: has_exclusive_usages(ctx, &usages, body),
698 fn has_usages_after_body(usages: &LocalUsages, body: &FunctionBody) -> bool {
699 usages.iter().any(|reference| body.preceedes_range(reference.range))
702 /// checks if relevant var is used with `&mut` access inside body
703 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
706 .filter(|reference| body.contains_range(reference.range))
707 .any(|reference| reference_is_exclusive(reference, body, ctx))
710 /// checks if this reference requires `&mut` access inside body
711 fn reference_is_exclusive(
712 reference: &FileReference,
716 // we directly modify variable with set: `n = 0`, `n += 1`
717 if reference.access == Some(ReferenceAccess::Write) {
721 // we take `&mut` reference to variable: `&mut v`
722 let path = match path_element_of_reference(body, reference) {
724 None => return false,
727 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
730 /// checks if this expr requires `&mut` access, recurses on field access
731 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
732 let parent = expr.syntax().parent()?;
734 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
735 if bin_expr.op_kind()?.is_assignment() {
736 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
741 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
742 return Some(ref_expr.mut_token().is_some());
745 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
746 let func = ctx.sema.resolve_method_call(&method_call)?;
747 let self_param = func.self_param(ctx.db())?;
748 let access = self_param.access(ctx.db());
750 return Some(matches!(access, hir::Access::Exclusive));
753 if let Some(field) = ast::FieldExpr::cast(parent) {
754 return expr_require_exclusive_access(ctx, &field.into());
760 /// Container of local varaible usages
762 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
763 struct LocalUsages(ide_db::search::UsageSearchResult);
766 fn find(ctx: &AssistContext, var: Local) -> Self {
768 Definition::Local(var)
770 .in_scope(SearchScope::single_file(ctx.frange.file_id))
775 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
776 self.0.iter().flat_map(|(_, rs)| rs.iter())
780 trait HasTokenAtOffset {
781 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
784 impl HasTokenAtOffset for SyntaxNode {
785 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
786 SyntaxNode::token_at_offset(&self, offset)
790 /// find relevant `ast::PathExpr` for reference
794 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
795 fn path_element_of_reference(
796 node: &dyn HasTokenAtOffset,
797 reference: &FileReference,
798 ) -> Option<ast::Expr> {
799 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
800 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
803 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
804 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
807 stdx::always!(matches!(path, ast::Expr::PathExpr(_)));
811 /// list local variables defined inside `body`
812 fn vars_defined_in_body(body: &FunctionBody, ctx: &AssistContext) -> Vec<Local> {
813 // FIXME: this doesn't work well with macros
814 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
816 .filter_map(ast::IdentPat::cast)
817 .filter_map(|let_stmt| ctx.sema.to_def(&let_stmt))
822 /// list local variables defined inside `body` that should be returned from extracted function
823 fn vars_defined_in_body_and_outlive(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
824 let mut vars_defined_in_body = vars_defined_in_body(&body, ctx);
825 vars_defined_in_body.retain(|var| var_outlives_body(ctx, body, var));
829 /// checks if the relevant local was defined before(outside of) body
830 fn is_defined_before(
833 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
835 src.file_id.original_file(ctx.db()) == ctx.frange.file_id
836 && !body.contains_node(&either_syntax(&src.value))
839 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
841 Either::Left(pat) => pat.syntax(),
842 Either::Right(it) => it.syntax(),
846 /// checks if local variable is used after(outside of) body
847 fn var_outlives_body(ctx: &AssistContext, body: &FunctionBody, var: &Local) -> bool {
848 let usages = LocalUsages::find(ctx, *var);
849 let has_usages = usages.iter().any(|reference| body.preceedes_range(reference.range));
853 fn body_return_ty(ctx: &AssistContext, body: &FunctionBody) -> Option<RetType> {
854 match body.tail_expr() {
856 let ty = ctx.sema.type_of_expr(&expr)?;
857 Some(RetType::Expr(ty))
859 None => Some(RetType::Stmt),
862 /// Where to put extracted function definition
865 /// Extract free function and put right after current top-level function
867 /// Extract method and put right after current function in the impl-block
871 /// find where to put extracted function definition
873 /// Function should be put right after returned node
874 fn scope_for_fn_insertion(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
876 FunctionBody::Expr(e) => scope_for_fn_insertion_node(e.syntax(), anchor),
877 FunctionBody::Span { parent, .. } => scope_for_fn_insertion_node(parent.syntax(), anchor),
881 fn scope_for_fn_insertion_node(node: &SyntaxNode, anchor: Anchor) -> Option<SyntaxNode> {
882 let mut ancestors = node.ancestors().peekable();
883 let mut last_ancestor = None;
884 while let Some(next_ancestor) = ancestors.next() {
885 match next_ancestor.kind() {
886 SyntaxKind::SOURCE_FILE => break,
887 SyntaxKind::ITEM_LIST => {
888 if !matches!(anchor, Anchor::Freestanding) {
891 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
895 SyntaxKind::ASSOC_ITEM_LIST => {
896 if !matches!(anchor, Anchor::Method) {
899 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
905 last_ancestor = Some(next_ancestor);
910 fn format_replacement(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
911 let ret_ty = fun.return_type(ctx);
913 let args = fun.params.iter().map(|param| param.to_arg(ctx));
914 let args = make::arg_list(args);
915 let call_expr = if fun.self_param.is_some() {
916 let self_arg = make::expr_path(make_path_from_text("self"));
917 make::expr_method_call(self_arg, &fun.name, args)
919 let func = make::expr_path(make_path_from_text(&fun.name));
920 make::expr_call(func, args)
923 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
925 let expr = handler.make_call_expr(call_expr).indent(indent);
927 let mut buf = String::new();
928 match fun.vars_defined_in_body_and_outlive.as_slice() {
930 [var] => format_to!(buf, "let {} = ", var.name(ctx.db()).unwrap()),
932 buf.push_str("let (");
933 format_to!(buf, "{}", v0.name(ctx.db()).unwrap());
935 format_to!(buf, ", {}", var.name(ctx.db()).unwrap());
937 buf.push_str(") = ");
940 format_to!(buf, "{}", expr);
941 if fun.ret_ty.is_unit()
942 && (!fun.vars_defined_in_body_and_outlive.is_empty() || !expr.is_block_like())
951 Try { kind: TryKind },
952 If { action: FlowKind },
953 IfOption { action: FlowKind },
954 MatchOption { none: FlowKind },
955 MatchResult { err: FlowKind },
959 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
960 match &fun.control_flow.kind {
961 None => FlowHandler::None,
963 let action = flow_kind.clone();
964 if *ret_ty == FunType::Unit {
966 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
967 FlowHandler::If { action }
969 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
970 FlowHandler::IfOption { action }
972 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
973 FlowHandler::Try { kind: kind.clone() }
978 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
979 FlowHandler::MatchOption { none: action }
981 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
982 FlowHandler::MatchResult { err: action }
984 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
985 FlowHandler::Try { kind: kind.clone() }
993 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
995 FlowHandler::None => call_expr,
996 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
997 FlowHandler::If { action } => {
998 let action = action.make_result_handler(None);
999 let stmt = make::expr_stmt(action);
1000 let block = make::block_expr(iter::once(stmt.into()), None);
1001 let condition = make::condition(call_expr, None);
1002 make::expr_if(condition, block, None)
1004 FlowHandler::IfOption { action } => {
1005 let path = make_path_from_text("Some");
1006 let value_pat = make::ident_pat(make::name("value"));
1007 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1008 let cond = make::condition(call_expr, Some(pattern.into()));
1009 let value = make::expr_path(make_path_from_text("value"));
1010 let action_expr = action.make_result_handler(Some(value));
1011 let action_stmt = make::expr_stmt(action_expr);
1012 let then = make::block_expr(iter::once(action_stmt.into()), None);
1013 make::expr_if(cond, then, None)
1015 FlowHandler::MatchOption { none } => {
1016 let some_name = "value";
1019 let path = make_path_from_text("Some");
1020 let value_pat = make::ident_pat(make::name(some_name));
1021 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1022 let value = make::expr_path(make_path_from_text(some_name));
1023 make::match_arm(iter::once(pat.into()), value)
1026 let path = make_path_from_text("None");
1027 let pat = make::path_pat(path);
1028 make::match_arm(iter::once(pat), none.make_result_handler(None))
1030 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1031 make::expr_match(call_expr, arms)
1033 FlowHandler::MatchResult { err } => {
1034 let ok_name = "value";
1035 let err_name = "value";
1038 let path = make_path_from_text("Ok");
1039 let value_pat = make::ident_pat(make::name(ok_name));
1040 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1041 let value = make::expr_path(make_path_from_text(ok_name));
1042 make::match_arm(iter::once(pat.into()), value)
1045 let path = make_path_from_text("Err");
1046 let value_pat = make::ident_pat(make::name(err_name));
1047 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1048 let value = make::expr_path(make_path_from_text(err_name));
1049 make::match_arm(iter::once(pat.into()), err.make_result_handler(Some(value)))
1051 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1052 make::expr_match(call_expr, arms)
1058 fn make_path_from_text(text: &str) -> ast::Path {
1059 make::path_unqualified(make::path_segment(make::name_ref(text)))
1062 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1063 let name = var.name(ctx.db()).unwrap().to_string();
1064 make::expr_path(make_path_from_text(&name))
1068 ctx: &AssistContext,
1069 module: hir::Module,
1071 old_indent: IndentLevel,
1072 new_indent: IndentLevel,
1074 let mut fn_def = String::new();
1075 let params = make_param_list(ctx, module, fun);
1076 let ret_ty = make_ret_ty(ctx, module, fun);
1077 let body = make_body(ctx, old_indent, new_indent, fun);
1078 match ctx.config.snippet_cap {
1079 Some(_) => format_to!(fn_def, "\n\n{}fn $0{}{}", new_indent, fun.name, params),
1080 None => format_to!(fn_def, "\n\n{}fn {}{}", new_indent, fun.name, params),
1082 if let Some(ret_ty) = ret_ty {
1083 format_to!(fn_def, " {}", ret_ty);
1085 format_to!(fn_def, " {}", body);
1090 fn make_param_list(ctx: &AssistContext, module: hir::Module, fun: &Function) -> ast::ParamList {
1091 let self_param = fun.self_param.clone();
1092 let params = fun.params.iter().map(|param| param.to_param(ctx, module));
1093 make::param_list(self_param, params)
1097 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1099 FunType::Unit => make::ty_unit(),
1100 FunType::Single(ty) => make_ty(ty, ctx, module),
1101 FunType::Tuple(types) => match types.as_slice() {
1103 stdx::never!("tuple type with 0 elements");
1107 stdx::never!("tuple type with 1 element");
1108 make_ty(ty, ctx, module)
1111 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1112 make::ty_tuple(types)
1119 fn make_ret_ty(ctx: &AssistContext, module: hir::Module, fun: &Function) -> Option<ast::RetType> {
1120 let fun_ty = fun.return_type(ctx);
1121 let handler = FlowHandler::from_ret_ty(fun, &fun_ty);
1122 let ret_ty = match &handler {
1123 FlowHandler::None => {
1124 if matches!(fun_ty, FunType::Unit) {
1127 fun_ty.make_ty(ctx, module)
1129 FlowHandler::Try { kind: TryKind::Option } => {
1130 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1132 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1133 let handler_ty = parent_ret_ty
1136 .map(|ty| make_ty(&ty, ctx, module))
1137 .unwrap_or_else(make::ty_unit);
1139 make::name_ref("Result"),
1140 vec![fun_ty.make_ty(ctx, module), handler_ty],
1143 FlowHandler::If { .. } => make::ty("bool"),
1144 FlowHandler::IfOption { action } => {
1145 let handler_ty = action
1147 .map(|ty| make_ty(&ty, ctx, module))
1148 .unwrap_or_else(make::ty_unit);
1149 make::ty_generic(make::name_ref("Option"), iter::once(handler_ty))
1151 FlowHandler::MatchOption { .. } => {
1152 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1154 FlowHandler::MatchResult { err } => {
1156 err.expr_ty(ctx).map(|ty| make_ty(&ty, ctx, module)).unwrap_or_else(make::ty_unit);
1158 make::name_ref("Result"),
1159 vec![fun_ty.make_ty(ctx, module), handler_ty],
1163 Some(make::ret_type(ret_ty))
1167 ctx: &AssistContext,
1168 old_indent: IndentLevel,
1169 new_indent: IndentLevel,
1171 ) -> ast::BlockExpr {
1172 let ret_ty = fun.return_type(ctx);
1173 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1174 let block = match &fun.body {
1175 FunctionBody::Expr(expr) => {
1176 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1177 let expr = ast::Expr::cast(expr).unwrap();
1178 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1180 make::block_expr(Vec::new(), Some(expr))
1182 FunctionBody::Span { parent, text_range } => {
1183 let mut elements: Vec<_> = parent
1186 .filter(|it| text_range.contains_range(it.text_range()))
1187 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1190 let mut tail_expr = match elements.pop() {
1191 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1192 elements.push(node);
1198 if tail_expr.is_none() {
1199 match fun.vars_defined_in_body_and_outlive.as_slice() {
1202 tail_expr = Some(path_expr_from_local(ctx, *var));
1205 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, *var));
1206 let expr = make::expr_tuple(exprs);
1207 tail_expr = Some(expr);
1212 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1213 Some(stmt) => Some(stmt),
1215 stdx::never!("block contains non-statement");
1220 let body_indent = IndentLevel(1);
1221 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1222 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1224 make::block_expr(elements, tail_expr)
1228 let block = match &handler {
1229 FlowHandler::None => block,
1230 FlowHandler::Try { kind } => {
1231 let block = with_default_tail_expr(block, make::expr_unit());
1232 map_tail_expr(block, |tail_expr| {
1233 let constructor = match kind {
1234 TryKind::Option => "Some",
1235 TryKind::Result { .. } => "Ok",
1237 let func = make::expr_path(make_path_from_text(constructor));
1238 let args = make::arg_list(iter::once(tail_expr));
1239 make::expr_call(func, args)
1242 FlowHandler::If { .. } => {
1243 let lit_false = make::expr_literal("false");
1244 with_tail_expr(block, lit_false.into())
1246 FlowHandler::IfOption { .. } => {
1247 let none = make::expr_path(make_path_from_text("None"));
1248 with_tail_expr(block, none)
1250 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1251 let some = make::expr_path(make_path_from_text("Some"));
1252 let args = make::arg_list(iter::once(tail_expr));
1253 make::expr_call(some, args)
1255 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1256 let ok = make::expr_path(make_path_from_text("Ok"));
1257 let args = make::arg_list(iter::once(tail_expr));
1258 make::expr_call(ok, args)
1262 block.indent(new_indent)
1265 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1266 let tail_expr = match block.tail_expr() {
1267 Some(tail_expr) => tail_expr,
1268 None => return block,
1270 make::block_expr(block.statements(), Some(f(tail_expr)))
1273 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1274 match block.tail_expr() {
1276 None => make::block_expr(block.statements(), Some(tail_expr)),
1280 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1281 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1282 let stmts = block.statements().chain(stmt_tail);
1283 make::block_expr(stmts, Some(tail_expr))
1286 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1287 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "()".to_string())
1290 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1291 let ty_str = format_type(ty, ctx, module);
1295 fn rewrite_body_segment(
1296 ctx: &AssistContext,
1298 handler: &FlowHandler,
1299 syntax: &SyntaxNode,
1301 let syntax = fix_param_usages(ctx, params, syntax);
1302 update_external_control_flow(handler, &syntax)
1305 /// change all usages to account for added `&`/`&mut` for some params
1306 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1307 let mut rewriter = SyntaxRewriter::default();
1308 for param in params {
1309 if !param.kind().is_ref() {
1313 let usages = LocalUsages::find(ctx, param.var);
1316 .filter(|reference| syntax.text_range().contains_range(reference.range))
1317 .filter_map(|reference| path_element_of_reference(syntax, reference));
1318 for path in usages {
1319 match path.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1320 Some(ast::Expr::MethodCallExpr(_)) | Some(ast::Expr::FieldExpr(_)) => {
1323 Some(ast::Expr::RefExpr(node))
1324 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1326 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1328 Some(ast::Expr::RefExpr(node))
1329 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1331 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1334 rewriter.replace_ast(&path, &make::expr_prefix(T![*], path.clone()));
1340 rewriter.rewrite(syntax)
1343 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> SyntaxNode {
1344 let mut rewriter = SyntaxRewriter::default();
1346 let mut nested_loop = None;
1347 let mut nested_scope = None;
1348 for event in syntax.preorder() {
1349 let node = match event {
1350 WalkEvent::Enter(e) => {
1352 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1353 if nested_loop.is_none() {
1354 nested_loop = Some(e.clone());
1359 | SyntaxKind::STATIC
1361 | SyntaxKind::MODULE => {
1362 if nested_scope.is_none() {
1363 nested_scope = Some(e.clone());
1370 WalkEvent::Leave(e) => {
1371 if nested_loop.as_ref() == Some(&e) {
1374 if nested_scope.as_ref() == Some(&e) {
1375 nested_scope = None;
1380 if nested_scope.is_some() {
1383 let expr = match ast::Expr::cast(node) {
1388 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1389 let expr = return_expr.expr();
1390 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1391 rewriter.replace_ast(&return_expr.into(), &replacement);
1394 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1395 let expr = break_expr.expr();
1396 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1397 rewriter.replace_ast(&break_expr.into(), &replacement);
1400 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1401 if let Some(replacement) = make_rewritten_flow(handler, None) {
1402 rewriter.replace_ast(&continue_expr.into(), &replacement);
1411 rewriter.rewrite(syntax)
1414 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1415 let value = match handler {
1416 FlowHandler::None | FlowHandler::Try { .. } => return None,
1417 FlowHandler::If { .. } => make::expr_literal("true").into(),
1418 FlowHandler::IfOption { .. } => {
1419 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1420 let args = make::arg_list(iter::once(expr));
1421 make::expr_call(make::expr_path(make_path_from_text("Some")), args)
1423 FlowHandler::MatchOption { .. } => make::expr_path(make_path_from_text("None")),
1424 FlowHandler::MatchResult { .. } => {
1425 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1426 let args = make::arg_list(iter::once(expr));
1427 make::expr_call(make::expr_path(make_path_from_text("Err")), args)
1430 Some(make::expr_return(Some(value)))
1435 use crate::tests::{check_assist, check_assist_not_applicable};
1440 fn no_args_from_binary_expr() {
1452 fn $0fun_name() -> i32 {
1459 fn no_args_from_binary_expr_in_module() {
1474 fn $0fun_name() -> i32 {
1482 fn no_args_from_binary_expr_indented() {
1494 fn $0fun_name() -> i32 {
1501 fn no_args_from_stmt_with_last_expr() {
1516 fn $0fun_name() -> i32 {
1524 fn no_args_from_stmt_unit() {
1568 fn no_args_if_else() {
1573 $0if true { 1 } else { 2 }$0
1580 fn $0fun_name() -> i32 {
1581 if true { 1 } else { 2 }
1587 fn no_args_if_let_else() {
1592 $0if let true = false { 1 } else { 2 }$0
1599 fn $0fun_name() -> i32 {
1600 if let true = false { 1 } else { 2 }
1606 fn no_args_match() {
1621 fn $0fun_name() -> i32 {
1631 fn no_args_while() {
1655 $0for v in &[0, 1] { }$0
1663 for v in &[0, 1] { }
1669 fn no_args_from_loop_unit() {
1683 fn $0fun_name() -> ! {
1692 fn no_args_from_loop_with_return() {
1707 fn $0fun_name() -> i32 {
1717 fn no_args_from_match() {
1722 let v: i32 = $0match Some(1) {
1729 let v: i32 = fun_name();
1732 fn $0fun_name() -> i32 {
1742 fn argument_form_expr() {
1756 fn $0fun_name(n: u32) -> u32 {
1763 fn argument_used_twice_form_expr() {
1777 fn $0fun_name(n: u32) -> u32 {
1784 fn two_arguments_form_expr() {
1800 fn $0fun_name(n: u32, m: u32) -> u32 {
1807 fn argument_and_locals() {
1822 fn $0fun_name(n: u32) -> u32 {
1830 fn in_comment_is_not_applicable() {
1831 cov_mark::check!(extract_function_in_comment_is_not_applicable);
1832 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
1836 fn part_of_expr_stmt() {
1848 fn $0fun_name() -> i32 {
1855 fn function_expr() {
1874 fn extract_from_nested() {
1880 let tuple = match x {
1881 true => ($02 + 2$0, true)
1888 let tuple = match x {
1889 true => (fun_name(), true)
1894 fn $0fun_name() -> i32 {
1901 fn param_from_closure() {
1906 let lambda = |x: u32| $0x * 2$0;
1910 let lambda = |x: u32| fun_name(x);
1913 fn $0fun_name(x: u32) -> u32 {
1920 fn extract_return_stmt() {
1932 fn $0fun_name() -> u32 {
1939 fn does_not_add_extra_whitespace() {
1955 fn $0fun_name() -> u32 {
1978 fn $0fun_name() -> i32 {
1990 let v = $00f32 as u32$0;
1997 fn $0fun_name() -> u32 {
2004 fn return_not_applicable() {
2005 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2009 fn method_to_freestanding() {
2016 fn foo(&self) -> i32 {
2024 fn foo(&self) -> i32 {
2029 fn $0fun_name() -> i32 {
2036 fn method_with_reference() {
2040 struct S { f: i32 };
2043 fn foo(&self) -> i32 {
2048 struct S { f: i32 };
2051 fn foo(&self) -> i32 {
2055 fn $0fun_name(&self) -> i32 {
2063 fn method_with_mut() {
2067 struct S { f: i32 };
2075 struct S { f: i32 };
2082 fn $0fun_name(&mut self) {
2090 fn variable_defined_inside_and_used_after_no_ret() {
2102 let k = fun_name(n);
2106 fn $0fun_name(n: i32) -> i32 {
2114 fn two_variables_defined_inside_and_used_after_no_ret() {
2127 let (k, m) = fun_name(n);
2131 fn $0fun_name(n: i32) -> (i32, i32) {
2140 fn nontrivial_patterns_define_variables() {
2144 struct Counter(i32);
2146 $0let Counter(n) = Counter(0);$0
2150 struct Counter(i32);
2156 fn $0fun_name() -> i32 {
2157 let Counter(n) = Counter(0);
2164 fn struct_with_two_fields_pattern_define_variables() {
2168 struct Counter { n: i32, m: i32 };
2170 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2174 struct Counter { n: i32, m: i32 };
2176 let (n, k) = fun_name();
2180 fn $0fun_name() -> (i32, i32) {
2181 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2188 fn mut_var_from_outer_scope() {
2204 fn $0fun_name(n: &mut i32) {
2211 fn mut_field_from_outer_scope() {
2217 let mut c = C { n: 0 };
2224 let mut c = C { n: 0 };
2229 fn $0fun_name(c: &mut C) {
2236 fn mut_nested_field_from_outer_scope() {
2243 let mut c = C { p: P { n: 0 } };
2244 let mut v = C { p: P { n: 0 } };
2245 let u = C { p: P { n: 0 } };
2247 let r = &mut v.p.n;$0
2248 let m = c.p.n + v.p.n + u.p.n;
2254 let mut c = C { p: P { n: 0 } };
2255 let mut v = C { p: P { n: 0 } };
2256 let u = C { p: P { n: 0 } };
2257 fun_name(&mut c, &u, &mut v);
2258 let m = c.p.n + v.p.n + u.p.n;
2261 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2269 fn mut_param_many_usages_stmt() {
2275 fn succ(&self) -> Self;
2276 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2279 fn succ(&self) -> Self { *self + 1 }
2297 fn succ(&self) -> Self;
2298 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2301 fn succ(&self) -> Self { *self + 1 }
2309 fn $0fun_name(n: &mut i32) {
2324 fn mut_param_many_usages_expr() {
2330 fn succ(&self) -> Self;
2331 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2334 fn succ(&self) -> Self { *self + 1 }
2354 fn succ(&self) -> Self;
2355 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2358 fn succ(&self) -> Self { *self + 1 }
2366 fn $0fun_name(n: &mut i32) {
2383 fn mut_param_by_value() {
2397 fn $0fun_name(mut n: i32) {
2404 fn mut_param_because_of_mut_ref() {
2421 fn $0fun_name(n: &mut i32) {
2429 fn mut_param_by_value_because_of_mut_ref() {
2444 fn $0fun_name(mut n: i32) {
2452 fn mut_method_call() {
2460 fn inc(&mut self) { *self += 1 }
2471 fn inc(&mut self) { *self += 1 }
2478 fn $0fun_name(mut n: i32) {
2485 fn shared_method_call() {
2493 fn succ(&self) { *self + 1 }
2504 fn succ(&self) { *self + 1 }
2511 fn $0fun_name(n: i32) {
2518 fn mut_method_call_with_other_receiver() {
2523 fn inc(&mut self, n: i32);
2526 fn inc(&mut self, n: i32) { *self += n }
2535 fn inc(&mut self, n: i32);
2538 fn inc(&mut self, n: i32) { *self += n }
2545 fn $0fun_name(n: i32) {
2553 fn non_copy_without_usages_after() {
2557 struct Counter(i32);
2563 struct Counter(i32);
2569 fn $0fun_name(c: Counter) {
2576 fn non_copy_used_after() {
2580 struct Counter(i32);
2587 struct Counter(i32);
2594 fn $0fun_name(c: &Counter) {
2601 fn copy_used_after() {
2607 impl Copy for i32 {}
2616 impl Copy for i32 {}
2623 fn $0fun_name(n: i32) {
2630 fn copy_custom_used_after() {
2636 struct Counter(i32);
2637 impl Copy for Counter {}
2646 struct Counter(i32);
2647 impl Copy for Counter {}
2654 fn $0fun_name(c: Counter) {
2661 fn indented_stmts() {
2690 fn indented_stmts_inside_mod() {
2728 #[lang = "None"] None,
2729 #[lang = "Some"] Some(T),
2743 #[lang = "None"] None,
2744 #[lang = "Some"] Some(T),
2750 let k = match fun_name(n) {
2751 Some(value) => value,
2758 fn $0fun_name(n: i32) -> Option<i32> {
2768 fn return_to_parent() {
2774 impl Copy for i32 {}
2776 #[lang = "Ok"] Ok(T),
2777 #[lang = "Err"] Err(E),
2790 impl Copy for i32 {}
2792 #[lang = "Ok"] Ok(T),
2793 #[lang = "Err"] Err(E),
2798 let k = match fun_name(n) {
2800 Err(value) => return value,
2805 fn $0fun_name(n: i32) -> Result<i32, i64> {
2815 fn break_and_continue() {
2816 cov_mark::check!(external_control_flow_break_and_continue);
2817 check_assist_not_applicable(
2835 fn return_and_break() {
2836 cov_mark::check!(external_control_flow_return_and_bc);
2837 check_assist_not_applicable(
2855 fn break_loop_with_if() {
2872 if fun_name(&mut n) {
2879 fn $0fun_name(n: &mut i32) -> bool {
2889 fn break_loop_nested() {
2914 fn $0fun_name(n: i32) -> bool {
2925 fn return_from_nested_loop() {
2945 let m = match fun_name() {
2946 Some(value) => value,
2953 fn $0fun_name() -> Option<i32> {
2965 fn break_from_nested_loop() {
2989 fn $0fun_name() -> i32 {
3001 fn break_from_nested_and_outer_loops() {
3023 let m = match fun_name() {
3024 Some(value) => value,
3031 fn $0fun_name() -> Option<i32> {
3046 fn return_from_nested_fn() {
3070 fn $0fun_name() -> i32 {
3082 fn break_with_value() {
3101 if let Some(value) = fun_name() {
3108 fn $0fun_name() -> Option<i32> {
3120 fn break_with_value_and_return() {
3140 let m = match fun_name() {
3142 Err(value) => break value,
3148 fn $0fun_name() -> Result<i32, i64> {
3164 enum Option<T> { None, Some(T), }
3166 fn bar() -> Option<i32> { None }
3167 fn foo() -> Option<()> {
3175 enum Option<T> { None, Some(T), }
3177 fn bar() -> Option<i32> { None }
3178 fn foo() -> Option<()> {
3180 let m = fun_name()?;
3185 fn $0fun_name() -> Option<i32> {
3194 fn try_option_unit() {
3198 enum Option<T> { None, Some(T), }
3200 fn foo() -> Option<()> {
3208 enum Option<T> { None, Some(T), }
3210 fn foo() -> Option<()> {
3217 fn $0fun_name() -> Option<()> {
3230 enum Result<T, E> { Ok(T), Err(E), }
3232 fn foo() -> Result<(), i64> {
3240 enum Result<T, E> { Ok(T), Err(E), }
3242 fn foo() -> Result<(), i64> {
3244 let m = fun_name()?;
3249 fn $0fun_name() -> Result<i32, i64> {
3258 fn try_option_with_return() {
3262 enum Option<T> { None, Some(T) }
3264 fn foo() -> Option<()> {
3275 enum Option<T> { None, Some(T) }
3277 fn foo() -> Option<()> {
3279 let m = fun_name()?;
3284 fn $0fun_name() -> Option<i32> {
3296 fn try_result_with_return() {
3300 enum Result<T, E> { Ok(T), Err(E), }
3302 fn foo() -> Result<(), i64> {
3313 enum Result<T, E> { Ok(T), Err(E), }
3315 fn foo() -> Result<(), i64> {
3317 let m = fun_name()?;
3322 fn $0fun_name() -> Result<i32, i64> {
3334 fn try_and_break() {
3335 cov_mark::check!(external_control_flow_try_and_bc);
3336 check_assist_not_applicable(
3339 enum Option<T> { None, Some(T) }
3341 fn foo() -> Option<()> {
3356 fn try_and_return_ok() {
3357 cov_mark::check!(external_control_flow_try_and_return_non_err);
3358 check_assist_not_applicable(
3361 enum Result<T, E> { Ok(T), Err(E), }
3363 fn foo() -> Result<(), i64> {