5 use hir::{HirDisplay, Local};
7 defs::{Definition, NameRefClass},
8 search::{FileReference, ReferenceAccess, SearchScope},
10 use itertools::Itertools;
16 edit::{AstNodeEdit, IndentLevel},
20 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR},
21 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
26 assist_context::{AssistContext, Assists},
30 // Assist: extract_function
32 // Extracts selected statements into new function.
50 // fn $0fun_name(n: i32) {
55 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
56 if ctx.frange.range.is_empty() {
60 let node = ctx.covering_element();
61 if node.kind() == COMMENT {
62 mark::hit!(extract_function_in_comment_is_not_applicable);
66 let node = element_to_node(node);
68 let body = extraction_target(&node, ctx.frange.range)?;
70 let vars_used_in_body = vars_used_in_body(ctx, &body);
71 let self_param = self_param_from_usages(ctx, &body, &vars_used_in_body);
73 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
74 let insert_after = scope_for_fn_insertion(&body, anchor)?;
75 let module = ctx.sema.scope(&insert_after).module()?;
77 let vars_defined_in_body_and_outlive = vars_defined_in_body_and_outlive(ctx, &body);
78 let ret_ty = body_return_ty(ctx, &body)?;
80 // FIXME: we compute variables that outlive here just to check `never!` condition
81 // this requires traversing whole `body` (cheap) and finding all references (expensive)
82 // maybe we can move this check to `edit` closure somehow?
83 if stdx::never!(!vars_defined_in_body_and_outlive.is_empty() && !ret_ty.is_unit()) {
84 // We should not have variables that outlive body if we have expression block
87 let control_flow = external_control_flow(ctx, &body)?;
89 let target_range = body.text_range();
92 AssistId("extract_function", crate::AssistKind::RefactorExtract),
93 "Extract into function",
96 let params = extracted_function_params(ctx, &body, &vars_used_in_body);
99 name: "fun_name".to_string(),
100 self_param: self_param.map(|(_, pat)| pat),
105 vars_defined_in_body_and_outlive,
108 let new_indent = IndentLevel::from_node(&insert_after);
109 let old_indent = fun.body.indent_level();
111 builder.replace(target_range, format_replacement(ctx, &fun, old_indent));
113 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
114 let insert_offset = insert_after.text_range().end();
115 match ctx.config.snippet_cap {
116 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
117 None => builder.insert(insert_offset, fn_def),
123 fn external_control_flow(ctx: &AssistContext, body: &FunctionBody) -> Option<ControlFlow> {
124 let mut ret_expr = None;
125 let mut try_expr = None;
126 let mut break_expr = None;
127 let mut continue_expr = None;
128 let (syntax, text_range) = match body {
129 FunctionBody::Expr(expr) => (expr.syntax(), expr.syntax().text_range()),
130 FunctionBody::Span { parent, text_range } => (parent.syntax(), *text_range),
133 let mut nested_loop = None;
134 let mut nested_scope = None;
136 for e in syntax.preorder() {
138 WalkEvent::Enter(e) => e,
139 WalkEvent::Leave(e) => {
140 if nested_loop.as_ref() == Some(&e) {
143 if nested_scope.as_ref() == Some(&e) {
149 if nested_scope.is_some() {
152 if !text_range.contains_range(e.text_range()) {
156 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
157 if nested_loop.is_none() {
158 nested_loop = Some(e);
165 | SyntaxKind::MODULE => {
166 if nested_scope.is_none() {
167 nested_scope = Some(e);
170 SyntaxKind::RETURN_EXPR => {
171 ret_expr = Some(ast::ReturnExpr::cast(e).unwrap());
173 SyntaxKind::TRY_EXPR => {
174 try_expr = Some(ast::TryExpr::cast(e).unwrap());
176 SyntaxKind::BREAK_EXPR if nested_loop.is_none() => {
177 break_expr = Some(ast::BreakExpr::cast(e).unwrap());
179 SyntaxKind::CONTINUE_EXPR if nested_loop.is_none() => {
180 continue_expr = Some(ast::ContinueExpr::cast(e).unwrap());
186 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
187 (Some(e), None, None, None) => {
188 let func = e.syntax().ancestors().find_map(ast::Fn::cast)?;
189 let def = ctx.sema.to_def(&func)?;
190 let ret_ty = def.ret_type(ctx.db());
191 let kind = try_kind_of_ty(ret_ty, ctx)?;
193 Some(FlowKind::Try { kind })
195 (Some(_), Some(r), None, None) => match r.expr() {
197 if let Some(kind) = expr_err_kind(&expr, ctx) {
198 Some(FlowKind::TryReturn { expr, kind })
200 mark::hit!(external_control_flow_try_and_return_non_err);
206 (Some(_), _, _, _) => {
207 mark::hit!(external_control_flow_try_and_bc);
210 (None, Some(r), None, None) => match r.expr() {
211 Some(expr) => Some(FlowKind::ReturnValue(expr)),
212 None => Some(FlowKind::Return),
214 (None, Some(_), _, _) => {
215 mark::hit!(external_control_flow_return_and_bc);
218 (None, None, Some(_), Some(_)) => {
219 mark::hit!(external_control_flow_break_and_continue);
222 (None, None, Some(b), None) => match b.expr() {
223 Some(expr) => Some(FlowKind::BreakValue(expr)),
224 None => Some(FlowKind::Break),
226 (None, None, None, Some(_)) => Some(FlowKind::Continue),
227 (None, None, None, None) => None,
230 Some(ControlFlow { kind })
233 /// Checks is expr is `Err(_)` or `None`
234 fn expr_err_kind(expr: &ast::Expr, ctx: &AssistContext) -> Option<TryKind> {
235 let func_name = match expr {
236 ast::Expr::CallExpr(call_expr) => call_expr.expr()?,
237 ast::Expr::PathExpr(_) => expr.clone(),
240 let text = func_name.syntax().text();
243 Some(TryKind::Result { ty: ctx.sema.type_of_expr(expr)? })
244 } else if text == "None" {
245 Some(TryKind::Option)
254 self_param: Option<ast::SelfParam>,
256 control_flow: ControlFlow,
259 vars_defined_in_body_and_outlive: Vec<Local>,
266 has_usages_afterwards: bool,
267 has_mut_inside_body: bool,
273 kind: Option<FlowKind>,
276 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
284 #[derive(Debug, Eq, PartialEq)]
288 Tuple(Vec<hir::Type>),
292 fn return_type(&self, ctx: &AssistContext) -> FunType {
294 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
295 RetType::Expr(ty) => FunType::Single(ty.clone()),
296 RetType::Stmt => match self.vars_defined_in_body_and_outlive.as_slice() {
298 [var] => FunType::Single(var.ty(ctx.db())),
300 let types = vars.iter().map(|v| v.ty(ctx.db())).collect();
301 FunType::Tuple(types)
309 fn is_ref(&self) -> bool {
310 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
315 fn kind(&self) -> ParamKind {
316 match (self.has_usages_afterwards, self.has_mut_inside_body, self.is_copy) {
317 (true, true, _) => ParamKind::MutRef,
318 (true, false, false) => ParamKind::SharedRef,
319 (false, true, _) => ParamKind::MutValue,
320 (true, false, true) | (false, false, _) => ParamKind::Value,
324 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
325 let var = path_expr_from_local(ctx, self.var);
327 ParamKind::Value | ParamKind::MutValue => var,
328 ParamKind::SharedRef => make::expr_ref(var, false),
329 ParamKind::MutRef => make::expr_ref(var, true),
333 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
334 let var = self.var.name(ctx.db()).unwrap().to_string();
335 let var_name = make::name(&var);
336 let pat = match self.kind() {
337 ParamKind::MutValue => make::ident_mut_pat(var_name),
338 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
339 make::ident_pat(var_name)
343 let ty = make_ty(&self.ty, ctx, module);
344 let ty = match self.kind() {
345 ParamKind::Value | ParamKind::MutValue => ty,
346 ParamKind::SharedRef => make::ty_ref(ty, false),
347 ParamKind::MutRef => make::ty_ref(ty, true),
350 make::param(pat.into(), ty)
354 /// Control flow that is exported from extracted function
366 #[derive(Debug, Clone)]
368 /// Return without value (`return;`)
370 /// Return with value (`return $expr;`)
371 ReturnValue(ast::Expr),
379 /// Break without value (`return;`)
381 /// Break with value (`break $expr;`)
382 BreakValue(ast::Expr),
387 #[derive(Debug, Clone)]
390 Result { ty: hir::Type },
394 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
396 FlowKind::Return | FlowKind::ReturnValue(_) => make::expr_return(expr),
397 FlowKind::Break | FlowKind::BreakValue(_) => make::expr_break(expr),
398 FlowKind::Try { .. } | FlowKind::TryReturn { .. } => {
399 stdx::never!("cannot have result handler with try");
400 expr.unwrap_or_else(|| make::expr_return(None))
402 FlowKind::Continue => {
403 stdx::always!(expr.is_none(), "continue with value is not possible");
404 make::expr_continue()
409 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
411 FlowKind::ReturnValue(expr)
412 | FlowKind::BreakValue(expr)
413 | FlowKind::TryReturn { expr, .. } => ctx.sema.type_of_expr(expr),
414 FlowKind::Try { .. } => {
415 stdx::never!("try does not have defined expr_ty");
418 FlowKind::Return | FlowKind::Break | FlowKind::Continue => None,
423 fn try_kind_of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
425 // We favour Result for `expr?`
426 return Some(TryKind::Result { ty });
428 let adt = ty.as_adt()?;
429 let name = adt.name(ctx.db());
430 // FIXME: use lang items to determine if it is std type or user defined
431 // E.g. if user happens to define type named `Option`, we would have false positive
432 match name.to_string().as_str() {
433 "Option" => Some(TryKind::Option),
434 "Result" => Some(TryKind::Result { ty }),
446 fn is_unit(&self) -> bool {
448 RetType::Expr(ty) => ty.is_unit(),
449 RetType::Stmt => true,
454 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
458 Span { parent: ast::BlockExpr, text_range: TextRange },
462 fn from_whole_node(node: SyntaxNode) -> Option<Self> {
465 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
466 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()).map(Self::Expr),
467 BLOCK_EXPR => ast::BlockExpr::cast(node)
468 .filter(|it| it.is_standalone())
471 _ => ast::Expr::cast(node).map(Self::Expr),
475 fn from_range(node: SyntaxNode, text_range: TextRange) -> Option<FunctionBody> {
476 let block = ast::BlockExpr::cast(node)?;
477 Some(Self::Span { parent: block, text_range })
480 fn indent_level(&self) -> IndentLevel {
482 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
483 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
487 fn tail_expr(&self) -> Option<ast::Expr> {
489 FunctionBody::Expr(expr) => Some(expr.clone()),
490 FunctionBody::Span { parent, text_range } => {
491 let tail_expr = parent.tail_expr()?;
492 if text_range.contains_range(tail_expr.syntax().text_range()) {
501 fn descendants(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
503 FunctionBody::Expr(expr) => Either::Right(expr.syntax().descendants()),
504 FunctionBody::Span { parent, text_range } => Either::Left(
508 .filter(move |it| text_range.contains_range(it.text_range())),
513 fn text_range(&self) -> TextRange {
515 FunctionBody::Expr(expr) => expr.syntax().text_range(),
516 FunctionBody::Span { parent: _, text_range } => *text_range,
520 fn contains_range(&self, range: TextRange) -> bool {
521 self.text_range().contains_range(range)
524 fn preceedes_range(&self, range: TextRange) -> bool {
525 self.text_range().end() <= range.start()
528 fn contains_node(&self, node: &SyntaxNode) -> bool {
529 self.contains_range(node.text_range())
533 impl HasTokenAtOffset for FunctionBody {
534 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
536 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
537 FunctionBody::Span { parent, text_range } => {
538 match parent.syntax().token_at_offset(offset) {
539 TokenAtOffset::None => TokenAtOffset::None,
540 TokenAtOffset::Single(t) => {
541 if text_range.contains_range(t.text_range()) {
542 TokenAtOffset::Single(t)
547 TokenAtOffset::Between(a, b) => {
549 text_range.contains_range(a.text_range()),
550 text_range.contains_range(b.text_range()),
552 (true, true) => TokenAtOffset::Between(a, b),
553 (true, false) => TokenAtOffset::Single(a),
554 (false, true) => TokenAtOffset::Single(b),
555 (false, false) => TokenAtOffset::None,
564 /// node or token's parent
565 fn element_to_node(node: SyntaxElement) -> SyntaxNode {
567 syntax::NodeOrToken::Node(n) => n,
568 syntax::NodeOrToken::Token(t) => t.parent(),
572 /// Try to guess what user wants to extract
574 /// We have basically have two cases:
575 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
576 /// Then we can use `ast::Expr`
577 /// * We want a few statements for a block. E.g.
579 /// fn foo() -> i32 {
589 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
590 // we have selected exactly the expr node
591 // wrap it before anything else
592 if node.text_range() == selection_range {
593 let body = FunctionBody::from_whole_node(node.clone());
599 // we have selected a few statements in a block
600 // so covering_element returns the whole block
601 if node.kind() == BLOCK_EXPR {
602 let body = FunctionBody::from_range(node.clone(), selection_range);
608 // we have selected single statement
609 // `from_whole_node` failed because (let) statement is not and expression
610 // so we try to expand covering_element to parent and repeat the previous
611 if let Some(parent) = node.parent() {
612 if parent.kind() == BLOCK_EXPR {
613 let body = FunctionBody::from_range(parent, selection_range);
620 // select the closest containing expr (both ifs are used)
621 std::iter::once(node.clone()).chain(node.ancestors()).find_map(FunctionBody::from_whole_node)
624 /// list local variables that are referenced in `body`
625 fn vars_used_in_body(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
626 // FIXME: currently usages inside macros are not found
628 .filter_map(ast::NameRef::cast)
629 .filter_map(|name_ref| NameRefClass::classify(&ctx.sema, &name_ref))
630 .map(|name_kind| name_kind.referenced(ctx.db()))
631 .filter_map(|definition| match definition {
632 Definition::Local(local) => Some(local),
639 /// find `self` param, that was not defined inside `body`
641 /// It should skip `self` params from impls inside `body`
642 fn self_param_from_usages(
645 vars_used_in_body: &[Local],
646 ) -> Option<(Local, ast::SelfParam)> {
647 let mut iter = vars_used_in_body
649 .filter(|var| var.is_self(ctx.db()))
650 .map(|var| (var, var.source(ctx.db())))
651 .filter(|(_, src)| is_defined_before(ctx, body, src))
652 .filter_map(|(&node, src)| match src.value {
653 Either::Right(it) => Some((node, it)),
655 stdx::never!(false, "Local::is_self returned true, but source is IdentPat");
660 let self_param = iter.next();
662 iter.next().is_none(),
663 "body references two different self params, both defined outside"
669 /// find variables that should be extracted as params
671 /// Computes additional info that affects param type and mutability
672 fn extracted_function_params(
675 vars_used_in_body: &[Local],
679 .filter(|var| !var.is_self(ctx.db()))
680 .map(|node| (node, node.source(ctx.db())))
681 .filter(|(_, src)| is_defined_before(ctx, body, src))
682 .filter_map(|(&node, src)| {
683 if src.value.is_left() {
686 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
691 let usages = LocalUsages::find(ctx, var);
692 let ty = var.ty(ctx.db());
693 let is_copy = ty.is_copy(ctx.db());
697 has_usages_afterwards: has_usages_after_body(&usages, body),
698 has_mut_inside_body: has_exclusive_usages(ctx, &usages, body),
705 fn has_usages_after_body(usages: &LocalUsages, body: &FunctionBody) -> bool {
706 usages.iter().any(|reference| body.preceedes_range(reference.range))
709 /// checks if relevant var is used with `&mut` access inside body
710 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
713 .filter(|reference| body.contains_range(reference.range))
714 .any(|reference| reference_is_exclusive(reference, body, ctx))
717 /// checks if this reference requires `&mut` access inside body
718 fn reference_is_exclusive(
719 reference: &FileReference,
723 // we directly modify variable with set: `n = 0`, `n += 1`
724 if reference.access == Some(ReferenceAccess::Write) {
728 // we take `&mut` reference to variable: `&mut v`
729 let path = match path_element_of_reference(body, reference) {
731 None => return false,
734 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
737 /// checks if this expr requires `&mut` access, recurses on field access
738 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
739 let parent = expr.syntax().parent()?;
741 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
742 if bin_expr.op_kind()?.is_assignment() {
743 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
748 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
749 return Some(ref_expr.mut_token().is_some());
752 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
753 let func = ctx.sema.resolve_method_call(&method_call)?;
754 let self_param = func.self_param(ctx.db())?;
755 let access = self_param.access(ctx.db());
757 return Some(matches!(access, hir::Access::Exclusive));
760 if let Some(field) = ast::FieldExpr::cast(parent) {
761 return expr_require_exclusive_access(ctx, &field.into());
767 /// Container of local varaible usages
769 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
770 struct LocalUsages(ide_db::search::UsageSearchResult);
773 fn find(ctx: &AssistContext, var: Local) -> Self {
775 Definition::Local(var)
777 .in_scope(SearchScope::single_file(ctx.frange.file_id))
782 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
783 self.0.iter().flat_map(|(_, rs)| rs.iter())
787 trait HasTokenAtOffset {
788 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
791 impl HasTokenAtOffset for SyntaxNode {
792 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
793 SyntaxNode::token_at_offset(&self, offset)
797 /// find relevant `ast::PathExpr` for reference
801 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
802 fn path_element_of_reference(
803 node: &dyn HasTokenAtOffset,
804 reference: &FileReference,
805 ) -> Option<ast::Expr> {
806 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
807 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
810 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
811 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
814 stdx::always!(matches!(path, ast::Expr::PathExpr(_)));
818 /// list local variables defined inside `body`
819 fn vars_defined_in_body(body: &FunctionBody, ctx: &AssistContext) -> Vec<Local> {
820 // FIXME: this doesn't work well with macros
821 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
823 .filter_map(ast::IdentPat::cast)
824 .filter_map(|let_stmt| ctx.sema.to_def(&let_stmt))
829 /// list local variables defined inside `body` that should be returned from extracted function
830 fn vars_defined_in_body_and_outlive(ctx: &AssistContext, body: &FunctionBody) -> Vec<Local> {
831 let mut vars_defined_in_body = vars_defined_in_body(&body, ctx);
832 vars_defined_in_body.retain(|var| var_outlives_body(ctx, body, var));
836 /// checks if the relevant local was defined before(outside of) body
837 fn is_defined_before(
840 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
842 src.file_id.original_file(ctx.db()) == ctx.frange.file_id
843 && !body.contains_node(&either_syntax(&src.value))
846 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
848 Either::Left(pat) => pat.syntax(),
849 Either::Right(it) => it.syntax(),
853 /// checks if local variable is used after(outside of) body
854 fn var_outlives_body(ctx: &AssistContext, body: &FunctionBody, var: &Local) -> bool {
855 let usages = LocalUsages::find(ctx, *var);
856 let has_usages = usages.iter().any(|reference| body.preceedes_range(reference.range));
860 fn body_return_ty(ctx: &AssistContext, body: &FunctionBody) -> Option<RetType> {
861 match body.tail_expr() {
863 let ty = ctx.sema.type_of_expr(&expr)?;
864 Some(RetType::Expr(ty))
866 None => Some(RetType::Stmt),
869 /// Where to put extracted function definition
872 /// Extract free function and put right after current top-level function
874 /// Extract method and put right after current function in the impl-block
878 /// find where to put extracted function definition
880 /// Function should be put right after returned node
881 fn scope_for_fn_insertion(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
883 FunctionBody::Expr(e) => scope_for_fn_insertion_node(e.syntax(), anchor),
884 FunctionBody::Span { parent, .. } => scope_for_fn_insertion_node(parent.syntax(), anchor),
888 fn scope_for_fn_insertion_node(node: &SyntaxNode, anchor: Anchor) -> Option<SyntaxNode> {
889 let mut ancestors = node.ancestors().peekable();
890 let mut last_ancestor = None;
891 while let Some(next_ancestor) = ancestors.next() {
892 match next_ancestor.kind() {
893 SyntaxKind::SOURCE_FILE => break,
894 SyntaxKind::ITEM_LIST => {
895 if !matches!(anchor, Anchor::Freestanding) {
898 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
902 SyntaxKind::ASSOC_ITEM_LIST => {
903 if !matches!(anchor, Anchor::Method) {
906 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
912 last_ancestor = Some(next_ancestor);
917 fn format_replacement(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
918 let ret_ty = fun.return_type(ctx);
920 let args = fun.params.iter().map(|param| param.to_arg(ctx));
921 let args = make::arg_list(args);
922 let call_expr = if fun.self_param.is_some() {
923 let self_arg = make::expr_path(make_path_from_text("self"));
924 make::expr_method_call(self_arg, &fun.name, args)
926 let func = make::expr_path(make_path_from_text(&fun.name));
927 make::expr_call(func, args)
930 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
932 let expr = handler.make_call_expr(call_expr).indent(indent);
934 let mut buf = String::new();
935 match fun.vars_defined_in_body_and_outlive.as_slice() {
937 [var] => format_to!(buf, "let {} = ", var.name(ctx.db()).unwrap()),
939 buf.push_str("let (");
940 format_to!(buf, "{}", v0.name(ctx.db()).unwrap());
942 format_to!(buf, ", {}", var.name(ctx.db()).unwrap());
944 buf.push_str(") = ");
947 format_to!(buf, "{}", expr);
948 if fun.ret_ty.is_unit()
949 && (!fun.vars_defined_in_body_and_outlive.is_empty() || !expr.is_block_like())
958 Try { kind: TryKind },
959 If { action: FlowKind },
960 IfOption { action: FlowKind },
961 MatchOption { none: FlowKind },
962 MatchResult { err: FlowKind },
966 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
967 match &fun.control_flow.kind {
968 None => FlowHandler::None,
970 let action = flow_kind.clone();
971 if *ret_ty == FunType::Unit {
973 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
974 FlowHandler::If { action }
976 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
977 FlowHandler::IfOption { action }
979 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
980 FlowHandler::Try { kind: kind.clone() }
985 FlowKind::Return | FlowKind::Break | FlowKind::Continue => {
986 FlowHandler::MatchOption { none: action }
988 FlowKind::ReturnValue(_) | FlowKind::BreakValue(_) => {
989 FlowHandler::MatchResult { err: action }
991 FlowKind::Try { kind } | FlowKind::TryReturn { kind, .. } => {
992 FlowHandler::Try { kind: kind.clone() }
1000 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1002 FlowHandler::None => call_expr,
1003 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1004 FlowHandler::If { action } => {
1005 let action = action.make_result_handler(None);
1006 let stmt = make::expr_stmt(action);
1007 let block = make::block_expr(iter::once(stmt.into()), None);
1008 let condition = make::condition(call_expr, None);
1009 make::expr_if(condition, block, None)
1011 FlowHandler::IfOption { action } => {
1012 let path = make_path_from_text("Some");
1013 let value_pat = make::ident_pat(make::name("value"));
1014 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1015 let cond = make::condition(call_expr, Some(pattern.into()));
1016 let value = make::expr_path(make_path_from_text("value"));
1017 let action_expr = action.make_result_handler(Some(value));
1018 let action_stmt = make::expr_stmt(action_expr);
1019 let then = make::block_expr(iter::once(action_stmt.into()), None);
1020 make::expr_if(cond, then, None)
1022 FlowHandler::MatchOption { none } => {
1023 let some_name = "value";
1026 let path = make_path_from_text("Some");
1027 let value_pat = make::ident_pat(make::name(some_name));
1028 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1029 let value = make::expr_path(make_path_from_text(some_name));
1030 make::match_arm(iter::once(pat.into()), value)
1033 let path = make_path_from_text("None");
1034 let pat = make::path_pat(path);
1035 make::match_arm(iter::once(pat), none.make_result_handler(None))
1037 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1038 make::expr_match(call_expr, arms)
1040 FlowHandler::MatchResult { err } => {
1041 let ok_name = "value";
1042 let err_name = "value";
1045 let path = make_path_from_text("Ok");
1046 let value_pat = make::ident_pat(make::name(ok_name));
1047 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1048 let value = make::expr_path(make_path_from_text(ok_name));
1049 make::match_arm(iter::once(pat.into()), value)
1052 let path = make_path_from_text("Err");
1053 let value_pat = make::ident_pat(make::name(err_name));
1054 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1055 let value = make::expr_path(make_path_from_text(err_name));
1056 make::match_arm(iter::once(pat.into()), err.make_result_handler(Some(value)))
1058 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1059 make::expr_match(call_expr, arms)
1065 fn make_path_from_text(text: &str) -> ast::Path {
1066 make::path_unqualified(make::path_segment(make::name_ref(text)))
1069 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1070 let name = var.name(ctx.db()).unwrap().to_string();
1071 make::expr_path(make_path_from_text(&name))
1075 ctx: &AssistContext,
1076 module: hir::Module,
1078 old_indent: IndentLevel,
1079 new_indent: IndentLevel,
1081 let mut fn_def = String::new();
1082 let params = make_param_list(ctx, module, fun);
1083 let ret_ty = make_ret_ty(ctx, module, fun);
1084 let body = make_body(ctx, old_indent, new_indent, fun);
1085 match ctx.config.snippet_cap {
1086 Some(_) => format_to!(fn_def, "\n\n{}fn $0{}{}", new_indent, fun.name, params),
1087 None => format_to!(fn_def, "\n\n{}fn {}{}", new_indent, fun.name, params),
1089 if let Some(ret_ty) = ret_ty {
1090 format_to!(fn_def, " {}", ret_ty);
1092 format_to!(fn_def, " {}", body);
1097 fn make_param_list(ctx: &AssistContext, module: hir::Module, fun: &Function) -> ast::ParamList {
1098 let self_param = fun.self_param.clone();
1099 let params = fun.params.iter().map(|param| param.to_param(ctx, module));
1100 make::param_list(self_param, params)
1104 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1106 FunType::Unit => make::ty_unit(),
1107 FunType::Single(ty) => make_ty(ty, ctx, module),
1108 FunType::Tuple(types) => match types.as_slice() {
1110 stdx::never!("tuple type with 0 elements");
1114 stdx::never!("tuple type with 1 element");
1115 make_ty(ty, ctx, module)
1118 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1119 make::ty_tuple(types)
1126 fn make_ret_ty(ctx: &AssistContext, module: hir::Module, fun: &Function) -> Option<ast::RetType> {
1127 let fun_ty = fun.return_type(ctx);
1128 let handler = FlowHandler::from_ret_ty(fun, &fun_ty);
1129 let ret_ty = match &handler {
1130 FlowHandler::None => {
1131 if matches!(fun_ty, FunType::Unit) {
1134 fun_ty.make_ty(ctx, module)
1136 FlowHandler::Try { kind: TryKind::Option } => {
1137 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1139 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1140 let handler_ty = parent_ret_ty
1143 .map(|ty| make_ty(&ty, ctx, module))
1144 .unwrap_or_else(make::ty_unit);
1146 make::name_ref("Result"),
1147 vec![fun_ty.make_ty(ctx, module), handler_ty],
1150 FlowHandler::If { .. } => make::ty("bool"),
1151 FlowHandler::IfOption { action } => {
1152 let handler_ty = action
1154 .map(|ty| make_ty(&ty, ctx, module))
1155 .unwrap_or_else(make::ty_unit);
1156 make::ty_generic(make::name_ref("Option"), iter::once(handler_ty))
1158 FlowHandler::MatchOption { .. } => {
1159 make::ty_generic(make::name_ref("Option"), iter::once(fun_ty.make_ty(ctx, module)))
1161 FlowHandler::MatchResult { err } => {
1163 err.expr_ty(ctx).map(|ty| make_ty(&ty, ctx, module)).unwrap_or_else(make::ty_unit);
1165 make::name_ref("Result"),
1166 vec![fun_ty.make_ty(ctx, module), handler_ty],
1170 Some(make::ret_type(ret_ty))
1174 ctx: &AssistContext,
1175 old_indent: IndentLevel,
1176 new_indent: IndentLevel,
1178 ) -> ast::BlockExpr {
1179 let ret_ty = fun.return_type(ctx);
1180 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1181 let block = match &fun.body {
1182 FunctionBody::Expr(expr) => {
1183 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1184 let expr = ast::Expr::cast(expr).unwrap();
1185 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1187 make::block_expr(Vec::new(), Some(expr))
1189 FunctionBody::Span { parent, text_range } => {
1190 let mut elements: Vec<_> = parent
1193 .filter(|it| text_range.contains_range(it.text_range()))
1194 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1197 let mut tail_expr = match elements.pop() {
1198 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1199 elements.push(node);
1205 if tail_expr.is_none() {
1206 match fun.vars_defined_in_body_and_outlive.as_slice() {
1209 tail_expr = Some(path_expr_from_local(ctx, *var));
1212 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, *var));
1213 let expr = make::expr_tuple(exprs);
1214 tail_expr = Some(expr);
1219 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1220 Some(stmt) => Some(stmt),
1222 stdx::never!("block contains non-statement");
1227 let body_indent = IndentLevel(1);
1228 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1229 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1231 make::block_expr(elements, tail_expr)
1235 let block = match &handler {
1236 FlowHandler::None => block,
1237 FlowHandler::Try { kind } => {
1238 let block = with_default_tail_expr(block, make::expr_unit());
1239 map_tail_expr(block, |tail_expr| {
1240 let constructor = match kind {
1241 TryKind::Option => "Some",
1242 TryKind::Result { .. } => "Ok",
1244 let func = make::expr_path(make_path_from_text(constructor));
1245 let args = make::arg_list(iter::once(tail_expr));
1246 make::expr_call(func, args)
1249 FlowHandler::If { .. } => {
1250 let lit_false = ast::Literal::cast(make::tokens::literal("false").parent()).unwrap();
1251 with_tail_expr(block, lit_false.into())
1253 FlowHandler::IfOption { .. } => {
1254 let none = make::expr_path(make_path_from_text("None"));
1255 with_tail_expr(block, none)
1257 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1258 let some = make::expr_path(make_path_from_text("Some"));
1259 let args = make::arg_list(iter::once(tail_expr));
1260 make::expr_call(some, args)
1262 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1263 let ok = make::expr_path(make_path_from_text("Ok"));
1264 let args = make::arg_list(iter::once(tail_expr));
1265 make::expr_call(ok, args)
1269 block.indent(new_indent)
1272 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1273 let tail_expr = match block.tail_expr() {
1274 Some(tail_expr) => tail_expr,
1275 None => return block,
1277 make::block_expr(block.statements(), Some(f(tail_expr)))
1280 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1281 match block.tail_expr() {
1283 None => make::block_expr(block.statements(), Some(tail_expr)),
1287 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1288 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1289 let stmts = block.statements().chain(stmt_tail);
1290 make::block_expr(stmts, Some(tail_expr))
1293 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1294 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "()".to_string())
1297 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1298 let ty_str = format_type(ty, ctx, module);
1302 fn rewrite_body_segment(
1303 ctx: &AssistContext,
1305 handler: &FlowHandler,
1306 syntax: &SyntaxNode,
1308 let syntax = fix_param_usages(ctx, params, syntax);
1309 update_external_control_flow(handler, &syntax)
1312 /// change all usages to account for added `&`/`&mut` for some params
1313 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1314 let mut rewriter = SyntaxRewriter::default();
1315 for param in params {
1316 if !param.kind().is_ref() {
1320 let usages = LocalUsages::find(ctx, param.var);
1323 .filter(|reference| syntax.text_range().contains_range(reference.range))
1324 .filter_map(|reference| path_element_of_reference(syntax, reference));
1325 for path in usages {
1326 match path.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1327 Some(ast::Expr::MethodCallExpr(_)) | Some(ast::Expr::FieldExpr(_)) => {
1330 Some(ast::Expr::RefExpr(node))
1331 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1333 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1335 Some(ast::Expr::RefExpr(node))
1336 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1338 rewriter.replace_ast(&node.clone().into(), &node.expr().unwrap());
1341 rewriter.replace_ast(&path, &make::expr_prefix(T![*], path.clone()));
1347 rewriter.rewrite(syntax)
1350 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> SyntaxNode {
1351 let mut rewriter = SyntaxRewriter::default();
1353 let mut nested_loop = None;
1354 let mut nested_scope = None;
1355 for event in syntax.preorder() {
1356 let node = match event {
1357 WalkEvent::Enter(e) => {
1359 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1360 if nested_loop.is_none() {
1361 nested_loop = Some(e.clone());
1366 | SyntaxKind::STATIC
1368 | SyntaxKind::MODULE => {
1369 if nested_scope.is_none() {
1370 nested_scope = Some(e.clone());
1377 WalkEvent::Leave(e) => {
1378 if nested_loop.as_ref() == Some(&e) {
1381 if nested_scope.as_ref() == Some(&e) {
1382 nested_scope = None;
1387 if nested_scope.is_some() {
1390 let expr = match ast::Expr::cast(node) {
1395 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1396 let expr = return_expr.expr();
1397 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1398 rewriter.replace_ast(&return_expr.into(), &replacement);
1401 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1402 let expr = break_expr.expr();
1403 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1404 rewriter.replace_ast(&break_expr.into(), &replacement);
1407 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1408 if let Some(replacement) = make_rewritten_flow(handler, None) {
1409 rewriter.replace_ast(&continue_expr.into(), &replacement);
1418 rewriter.rewrite(syntax)
1421 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1422 let value = match handler {
1423 FlowHandler::None | FlowHandler::Try { .. } => return None,
1424 FlowHandler::If { .. } => {
1425 ast::Literal::cast(make::tokens::literal("true").parent()).unwrap().into()
1427 FlowHandler::IfOption { .. } => {
1428 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1429 let args = make::arg_list(iter::once(expr));
1430 make::expr_call(make::expr_path(make_path_from_text("Some")), args)
1432 FlowHandler::MatchOption { .. } => make::expr_path(make_path_from_text("None")),
1433 FlowHandler::MatchResult { .. } => {
1434 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1435 let args = make::arg_list(iter::once(expr));
1436 make::expr_call(make::expr_path(make_path_from_text("Err")), args)
1439 Some(make::expr_return(Some(value)))
1444 use crate::tests::{check_assist, check_assist_not_applicable};
1449 fn no_args_from_binary_expr() {
1461 fn $0fun_name() -> i32 {
1468 fn no_args_from_binary_expr_in_module() {
1483 fn $0fun_name() -> i32 {
1491 fn no_args_from_binary_expr_indented() {
1503 fn $0fun_name() -> i32 {
1510 fn no_args_from_stmt_with_last_expr() {
1525 fn $0fun_name() -> i32 {
1533 fn no_args_from_stmt_unit() {
1577 fn no_args_if_else() {
1582 $0if true { 1 } else { 2 }$0
1589 fn $0fun_name() -> i32 {
1590 if true { 1 } else { 2 }
1596 fn no_args_if_let_else() {
1601 $0if let true = false { 1 } else { 2 }$0
1608 fn $0fun_name() -> i32 {
1609 if let true = false { 1 } else { 2 }
1615 fn no_args_match() {
1630 fn $0fun_name() -> i32 {
1640 fn no_args_while() {
1664 $0for v in &[0, 1] { }$0
1672 for v in &[0, 1] { }
1678 fn no_args_from_loop_unit() {
1692 fn $0fun_name() -> ! {
1701 fn no_args_from_loop_with_return() {
1716 fn $0fun_name() -> i32 {
1726 fn no_args_from_match() {
1731 let v: i32 = $0match Some(1) {
1738 let v: i32 = fun_name();
1741 fn $0fun_name() -> i32 {
1751 fn argument_form_expr() {
1765 fn $0fun_name(n: u32) -> u32 {
1772 fn argument_used_twice_form_expr() {
1786 fn $0fun_name(n: u32) -> u32 {
1793 fn two_arguments_form_expr() {
1809 fn $0fun_name(n: u32, m: u32) -> u32 {
1816 fn argument_and_locals() {
1831 fn $0fun_name(n: u32) -> u32 {
1839 fn in_comment_is_not_applicable() {
1840 mark::check!(extract_function_in_comment_is_not_applicable);
1841 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
1845 fn part_of_expr_stmt() {
1857 fn $0fun_name() -> i32 {
1864 fn function_expr() {
1883 fn extract_from_nested() {
1889 let tuple = match x {
1890 true => ($02 + 2$0, true)
1897 let tuple = match x {
1898 true => (fun_name(), true)
1903 fn $0fun_name() -> i32 {
1910 fn param_from_closure() {
1915 let lambda = |x: u32| $0x * 2$0;
1919 let lambda = |x: u32| fun_name(x);
1922 fn $0fun_name(x: u32) -> u32 {
1929 fn extract_return_stmt() {
1941 fn $0fun_name() -> u32 {
1948 fn does_not_add_extra_whitespace() {
1964 fn $0fun_name() -> u32 {
1987 fn $0fun_name() -> i32 {
1999 let v = $00f32 as u32$0;
2006 fn $0fun_name() -> u32 {
2013 fn return_not_applicable() {
2014 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2018 fn method_to_freestanding() {
2025 fn foo(&self) -> i32 {
2033 fn foo(&self) -> i32 {
2038 fn $0fun_name() -> i32 {
2045 fn method_with_reference() {
2049 struct S { f: i32 };
2052 fn foo(&self) -> i32 {
2057 struct S { f: i32 };
2060 fn foo(&self) -> i32 {
2064 fn $0fun_name(&self) -> i32 {
2072 fn method_with_mut() {
2076 struct S { f: i32 };
2084 struct S { f: i32 };
2091 fn $0fun_name(&mut self) {
2099 fn variable_defined_inside_and_used_after_no_ret() {
2111 let k = fun_name(n);
2115 fn $0fun_name(n: i32) -> i32 {
2123 fn two_variables_defined_inside_and_used_after_no_ret() {
2136 let (k, m) = fun_name(n);
2140 fn $0fun_name(n: i32) -> (i32, i32) {
2149 fn nontrivial_patterns_define_variables() {
2153 struct Counter(i32);
2155 $0let Counter(n) = Counter(0);$0
2159 struct Counter(i32);
2165 fn $0fun_name() -> i32 {
2166 let Counter(n) = Counter(0);
2173 fn struct_with_two_fields_pattern_define_variables() {
2177 struct Counter { n: i32, m: i32 };
2179 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2183 struct Counter { n: i32, m: i32 };
2185 let (n, k) = fun_name();
2189 fn $0fun_name() -> (i32, i32) {
2190 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2197 fn mut_var_from_outer_scope() {
2213 fn $0fun_name(n: &mut i32) {
2220 fn mut_field_from_outer_scope() {
2226 let mut c = C { n: 0 };
2233 let mut c = C { n: 0 };
2238 fn $0fun_name(c: &mut C) {
2245 fn mut_nested_field_from_outer_scope() {
2252 let mut c = C { p: P { n: 0 } };
2253 let mut v = C { p: P { n: 0 } };
2254 let u = C { p: P { n: 0 } };
2256 let r = &mut v.p.n;$0
2257 let m = c.p.n + v.p.n + u.p.n;
2263 let mut c = C { p: P { n: 0 } };
2264 let mut v = C { p: P { n: 0 } };
2265 let u = C { p: P { n: 0 } };
2266 fun_name(&mut c, &u, &mut v);
2267 let m = c.p.n + v.p.n + u.p.n;
2270 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2278 fn mut_param_many_usages_stmt() {
2284 fn succ(&self) -> Self;
2285 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2288 fn succ(&self) -> Self { *self + 1 }
2306 fn succ(&self) -> Self;
2307 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2310 fn succ(&self) -> Self { *self + 1 }
2318 fn $0fun_name(n: &mut i32) {
2333 fn mut_param_many_usages_expr() {
2339 fn succ(&self) -> Self;
2340 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2343 fn succ(&self) -> Self { *self + 1 }
2363 fn succ(&self) -> Self;
2364 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2367 fn succ(&self) -> Self { *self + 1 }
2375 fn $0fun_name(n: &mut i32) {
2392 fn mut_param_by_value() {
2406 fn $0fun_name(mut n: i32) {
2413 fn mut_param_because_of_mut_ref() {
2430 fn $0fun_name(n: &mut i32) {
2438 fn mut_param_by_value_because_of_mut_ref() {
2453 fn $0fun_name(mut n: i32) {
2461 fn mut_method_call() {
2469 fn inc(&mut self) { *self += 1 }
2480 fn inc(&mut self) { *self += 1 }
2487 fn $0fun_name(mut n: i32) {
2494 fn shared_method_call() {
2502 fn succ(&self) { *self + 1 }
2513 fn succ(&self) { *self + 1 }
2520 fn $0fun_name(n: i32) {
2527 fn mut_method_call_with_other_receiver() {
2532 fn inc(&mut self, n: i32);
2535 fn inc(&mut self, n: i32) { *self += n }
2544 fn inc(&mut self, n: i32);
2547 fn inc(&mut self, n: i32) { *self += n }
2554 fn $0fun_name(n: i32) {
2562 fn non_copy_without_usages_after() {
2566 struct Counter(i32);
2572 struct Counter(i32);
2578 fn $0fun_name(c: Counter) {
2585 fn non_copy_used_after() {
2589 struct Counter(i32);
2596 struct Counter(i32);
2603 fn $0fun_name(c: &Counter) {
2610 fn copy_used_after() {
2616 impl Copy for i32 {}
2625 impl Copy for i32 {}
2632 fn $0fun_name(n: i32) {
2639 fn copy_custom_used_after() {
2645 struct Counter(i32);
2646 impl Copy for Counter {}
2655 struct Counter(i32);
2656 impl Copy for Counter {}
2663 fn $0fun_name(c: Counter) {
2670 fn indented_stmts() {
2699 fn indented_stmts_inside_mod() {
2737 #[lang = "None"] None,
2738 #[lang = "Some"] Some(T),
2752 #[lang = "None"] None,
2753 #[lang = "Some"] Some(T),
2759 let k = match fun_name(n) {
2760 Some(value) => value,
2767 fn $0fun_name(n: i32) -> Option<i32> {
2777 fn return_to_parent() {
2783 impl Copy for i32 {}
2785 #[lang = "Ok"] Ok(T),
2786 #[lang = "Err"] Err(E),
2799 impl Copy for i32 {}
2801 #[lang = "Ok"] Ok(T),
2802 #[lang = "Err"] Err(E),
2807 let k = match fun_name(n) {
2809 Err(value) => return value,
2814 fn $0fun_name(n: i32) -> Result<i32, i64> {
2824 fn break_and_continue() {
2825 mark::check!(external_control_flow_break_and_continue);
2826 check_assist_not_applicable(
2844 fn return_and_break() {
2845 mark::check!(external_control_flow_return_and_bc);
2846 check_assist_not_applicable(
2864 fn break_loop_with_if() {
2881 if fun_name(&mut n) {
2888 fn $0fun_name(n: &mut i32) -> bool {
2898 fn break_loop_nested() {
2923 fn $0fun_name(n: i32) -> bool {
2934 fn return_from_nested_loop() {
2954 let m = match fun_name() {
2955 Some(value) => value,
2962 fn $0fun_name() -> Option<i32> {
2974 fn break_from_nested_loop() {
2998 fn $0fun_name() -> i32 {
3010 fn break_from_nested_and_outer_loops() {
3032 let m = match fun_name() {
3033 Some(value) => value,
3040 fn $0fun_name() -> Option<i32> {
3055 fn return_from_nested_fn() {
3079 fn $0fun_name() -> i32 {
3091 fn break_with_value() {
3110 if let Some(value) = fun_name() {
3117 fn $0fun_name() -> Option<i32> {
3129 fn break_with_value_and_return() {
3149 let m = match fun_name() {
3151 Err(value) => break value,
3157 fn $0fun_name() -> Result<i32, i64> {
3173 enum Option<T> { None, Some(T), }
3175 fn bar() -> Option<i32> { None }
3176 fn foo() -> Option<()> {
3184 enum Option<T> { None, Some(T), }
3186 fn bar() -> Option<i32> { None }
3187 fn foo() -> Option<()> {
3189 let m = fun_name()?;
3194 fn $0fun_name() -> Option<i32> {
3203 fn try_option_unit() {
3207 enum Option<T> { None, Some(T), }
3209 fn foo() -> Option<()> {
3217 enum Option<T> { None, Some(T), }
3219 fn foo() -> Option<()> {
3226 fn $0fun_name() -> Option<()> {
3239 enum Result<T, E> { Ok(T), Err(E), }
3241 fn foo() -> Result<(), i64> {
3249 enum Result<T, E> { Ok(T), Err(E), }
3251 fn foo() -> Result<(), i64> {
3253 let m = fun_name()?;
3258 fn $0fun_name() -> Result<i32, i64> {
3267 fn try_option_with_return() {
3271 enum Option<T> { None, Some(T) }
3273 fn foo() -> Option<()> {
3284 enum Option<T> { None, Some(T) }
3286 fn foo() -> Option<()> {
3288 let m = fun_name()?;
3293 fn $0fun_name() -> Option<i32> {
3305 fn try_result_with_return() {
3309 enum Result<T, E> { Ok(T), Err(E), }
3311 fn foo() -> Result<(), i64> {
3322 enum Result<T, E> { Ok(T), Err(E), }
3324 fn foo() -> Result<(), i64> {
3326 let m = fun_name()?;
3331 fn $0fun_name() -> Result<i32, i64> {
3343 fn try_and_break() {
3344 mark::check!(external_control_flow_try_and_bc);
3345 check_assist_not_applicable(
3348 enum Option<T> { None, Some(T) }
3350 fn foo() -> Option<()> {
3365 fn try_and_return_ok() {
3366 mark::check!(external_control_flow_try_and_return_non_err);
3367 check_assist_not_applicable(
3370 enum Result<T, E> { Ok(T), Err(E), }
3372 fn foo() -> Result<(), i64> {