1 use std::{hash::BuildHasherDefault, iter};
5 use hir::{HirDisplay, InFile, Local, Semantics, TypeInfo};
7 defs::{Definition, NameRefClass},
8 helpers::node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
9 search::{FileReference, ReferenceCategory, SearchScope},
12 use itertools::Itertools;
13 use rustc_hash::FxHasher;
18 edit::{AstNodeEdit, IndentLevel},
21 match_ast, ted, SyntaxElement,
22 SyntaxKind::{self, COMMENT},
23 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
27 assist_context::{AssistContext, Assists, TreeMutator},
31 type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>;
33 // Assist: extract_function
35 // Extracts selected statements into new function.
53 // fn $0fun_name(n: i32) {
58 pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
59 let range = ctx.frange.range;
64 let node = ctx.covering_element();
65 if node.kind() == COMMENT {
66 cov_mark::hit!(extract_function_in_comment_is_not_applicable);
70 let node = match node {
71 syntax::NodeOrToken::Node(n) => n,
72 syntax::NodeOrToken::Token(t) => t.parent()?,
74 let body = extraction_target(&node, range)?;
75 let container_info = body.analyze_container(&ctx.sema)?;
77 let (locals_used, self_param) = body.analyze(&ctx.sema);
79 let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
80 let insert_after = node_to_insert_after(&body, anchor)?;
81 let module = ctx.sema.scope(&insert_after).module()?;
83 let ret_ty = body.return_ty(ctx)?;
84 let control_flow = body.external_control_flow(ctx, &container_info)?;
85 let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
87 let target_range = body.text_range();
90 AssistId("extract_function", crate::AssistKind::RefactorExtract),
91 "Extract into function",
94 let outliving_locals: Vec<_> = ret_values.collect();
95 if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
96 // We should not have variables that outlive body if we have expression block
101 body.extracted_function_params(ctx, &container_info, locals_used.iter().copied());
104 name: make::name_ref("fun_name"),
111 mods: container_info,
114 let new_indent = IndentLevel::from_node(&insert_after);
115 let old_indent = fun.body.indent_level();
117 builder.replace(target_range, make_call(ctx, &fun, old_indent));
119 let fn_def = format_function(ctx, module, &fun, old_indent, new_indent);
120 let insert_offset = insert_after.text_range().end();
121 match ctx.config.snippet_cap {
122 Some(cap) => builder.insert_snippet(cap, insert_offset, fn_def),
123 None => builder.insert(insert_offset, fn_def),
129 /// Try to guess what user wants to extract
131 /// We have basically have two cases:
132 /// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
133 /// Then we can use `ast::Expr`
134 /// * We want a few statements for a block. E.g.
136 /// fn foo() -> i32 {
146 fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
147 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
149 ast::Stmt::Item(_) => None,
150 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => Some(FunctionBody::from_range(
151 node.parent().and_then(ast::StmtList::cast)?,
157 // Covering element returned the parent block of one or multiple statements that have been selected
158 if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
159 if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
160 if block_expr.syntax().text_range() == selection_range {
161 return FunctionBody::from_expr(block_expr.into());
165 // Extract the full statements.
166 return Some(FunctionBody::from_range(stmt_list, selection_range));
169 let expr = ast::Expr::cast(node.clone())?;
170 // A node got selected fully
171 if node.text_range() == selection_range {
172 return FunctionBody::from_expr(expr);
175 node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
181 self_param: Option<ast::SelfParam>,
183 control_flow: ControlFlow,
186 outliving_locals: Vec<OutlivedLocal>,
199 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
207 #[derive(Debug, Eq, PartialEq)]
211 Tuple(Vec<hir::Type>),
214 /// Where to put extracted function definition
217 /// Extract free function and put right after current top-level function
219 /// Extract method and put right after current function in the impl-block
223 // FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
224 // probably be merged somehow.
227 kind: Option<FlowKind>,
232 /// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
233 #[derive(Clone, Debug)]
234 struct ContainerInfo {
237 parent_loop: Option<SyntaxNode>,
238 /// The function's return type, const's type etc.
239 ret_type: Option<hir::Type>,
242 /// Control flow that is exported from extracted function
254 #[derive(Debug, Clone)]
256 /// Return with value (`return $expr;`)
257 Return(Option<ast::Expr>),
261 /// Break with value (`break $expr;`)
262 Break(Option<ast::Expr>),
267 #[derive(Debug, Clone)]
270 Result { ty: hir::Type },
280 fn is_unit(&self) -> bool {
282 RetType::Expr(ty) => ty.is_unit(),
283 RetType::Stmt => true,
288 /// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
289 /// This is the future function body, the part that is being extracted.
293 Span { parent: ast::StmtList, text_range: TextRange },
297 struct OutlivedLocal {
299 mut_usage_outside_body: bool,
302 /// Container of local variable usages
304 /// Semanticall same as `UsageSearchResult`, but provides more convenient interface
305 struct LocalUsages(ide_db::search::UsageSearchResult);
308 fn find_local_usages(ctx: &AssistContext, var: Local) -> Self {
310 Definition::Local(var)
312 .in_scope(SearchScope::single_file(ctx.frange.file_id))
317 fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
318 self.0.iter().flat_map(|(_, rs)| rs)
323 fn return_type(&self, ctx: &AssistContext) -> FunType {
325 RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
326 RetType::Expr(ty) => FunType::Single(ty.clone()),
327 RetType::Stmt => match self.outliving_locals.as_slice() {
329 [var] => FunType::Single(var.local.ty(ctx.db())),
331 let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
332 FunType::Tuple(types)
340 fn is_ref(&self) -> bool {
341 matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
346 fn kind(&self) -> ParamKind {
347 match (self.move_local, self.requires_mut, self.is_copy) {
348 (false, true, _) => ParamKind::MutRef,
349 (false, false, false) => ParamKind::SharedRef,
350 (true, true, _) => ParamKind::MutValue,
351 (_, false, _) => ParamKind::Value,
355 fn to_arg(&self, ctx: &AssistContext) -> ast::Expr {
356 let var = path_expr_from_local(ctx, self.var);
358 ParamKind::Value | ParamKind::MutValue => var,
359 ParamKind::SharedRef => make::expr_ref(var, false),
360 ParamKind::MutRef => make::expr_ref(var, true),
364 fn to_param(&self, ctx: &AssistContext, module: hir::Module) -> ast::Param {
365 let var = self.var.name(ctx.db()).unwrap().to_string();
366 let var_name = make::name(&var);
367 let pat = match self.kind() {
368 ParamKind::MutValue => make::ident_pat(false, true, var_name),
369 ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
370 make::ext::simple_ident_pat(var_name)
374 let ty = make_ty(&self.ty, ctx, module);
375 let ty = match self.kind() {
376 ParamKind::Value | ParamKind::MutValue => ty,
377 ParamKind::SharedRef => make::ty_ref(ty, false),
378 ParamKind::MutRef => make::ty_ref(ty, true),
381 make::param(pat.into(), ty)
386 fn of_ty(ty: hir::Type, ctx: &AssistContext) -> Option<TryKind> {
388 // We favour Result for `expr?`
389 return Some(TryKind::Result { ty });
391 let adt = ty.as_adt()?;
392 let name = adt.name(ctx.db());
393 // FIXME: use lang items to determine if it is std type or user defined
394 // E.g. if user happens to define type named `Option`, we would have false positive
395 match name.to_string().as_str() {
396 "Option" => Some(TryKind::Option),
397 "Result" => Some(TryKind::Result { ty }),
404 fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
406 FlowKind::Return(_) => make::expr_return(expr),
407 FlowKind::Break(_) => make::expr_break(expr),
408 FlowKind::Try { .. } => {
409 stdx::never!("cannot have result handler with try");
410 expr.unwrap_or_else(|| make::expr_return(None))
412 FlowKind::Continue => {
413 stdx::always!(expr.is_none(), "continue with value is not possible");
414 make::expr_continue()
419 fn expr_ty(&self, ctx: &AssistContext) -> Option<hir::Type> {
421 FlowKind::Return(Some(expr)) | FlowKind::Break(Some(expr)) => {
422 ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
424 FlowKind::Try { .. } => {
425 stdx::never!("try does not have defined expr_ty");
434 fn parent(&self) -> Option<SyntaxNode> {
436 FunctionBody::Expr(expr) => expr.syntax().parent(),
437 FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
441 fn from_expr(expr: ast::Expr) -> Option<Self> {
443 ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
444 ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
445 ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
446 expr => Some(Self::Expr(expr)),
450 fn from_range(parent: ast::StmtList, selected: TextRange) -> FunctionBody {
451 let mut text_range = parent
453 .map(|stmt| stmt.syntax().text_range())
454 .filter(|&stmt| selected.intersect(stmt).filter(|it| !it.is_empty()).is_some())
455 .fold1(|acc, stmt| acc.cover(stmt));
456 if let Some(tail_range) = parent
458 .map(|it| it.syntax().text_range())
459 .filter(|&it| selected.intersect(it).is_some())
461 text_range = Some(match text_range {
462 Some(text_range) => text_range.cover(tail_range),
466 Self::Span { parent, text_range: text_range.unwrap_or(selected) }
469 fn indent_level(&self) -> IndentLevel {
471 FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
472 FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
476 fn tail_expr(&self) -> Option<ast::Expr> {
478 FunctionBody::Expr(expr) => Some(expr.clone()),
479 FunctionBody::Span { parent, text_range } => {
480 let tail_expr = parent.tail_expr()?;
481 text_range.contains_range(tail_expr.syntax().text_range()).then(|| tail_expr)
486 fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
488 FunctionBody::Expr(expr) => walk_expr(expr, cb),
489 FunctionBody::Span { parent, text_range } => {
492 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
493 .filter_map(|stmt| match stmt {
494 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
495 ast::Stmt::Item(_) => None,
496 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
498 .for_each(|expr| walk_expr(&expr, cb));
499 if let Some(expr) = parent
501 .filter(|it| text_range.contains_range(it.syntax().text_range()))
503 walk_expr(&expr, cb);
509 fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
511 FunctionBody::Expr(expr) => preorder_expr(expr, cb),
512 FunctionBody::Span { parent, text_range } => {
515 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
516 .filter_map(|stmt| match stmt {
517 ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
518 ast::Stmt::Item(_) => None,
519 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
521 .for_each(|expr| preorder_expr(&expr, cb));
522 if let Some(expr) = parent
524 .filter(|it| text_range.contains_range(it.syntax().text_range()))
526 preorder_expr(&expr, cb);
532 fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
534 FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
535 FunctionBody::Span { parent, text_range } => {
538 .filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
539 .for_each(|stmt| match stmt {
540 ast::Stmt::ExprStmt(expr_stmt) => {
541 if let Some(expr) = expr_stmt.expr() {
542 walk_patterns_in_expr(&expr, cb)
545 ast::Stmt::Item(_) => (),
546 ast::Stmt::LetStmt(stmt) => {
547 if let Some(pat) = stmt.pat() {
550 if let Some(expr) = stmt.initializer() {
551 walk_patterns_in_expr(&expr, cb);
555 if let Some(expr) = parent
557 .filter(|it| text_range.contains_range(it.syntax().text_range()))
559 walk_patterns_in_expr(&expr, cb);
565 fn text_range(&self) -> TextRange {
567 FunctionBody::Expr(expr) => expr.syntax().text_range(),
568 &FunctionBody::Span { text_range, .. } => text_range,
572 fn contains_range(&self, range: TextRange) -> bool {
573 self.text_range().contains_range(range)
576 fn precedes_range(&self, range: TextRange) -> bool {
577 self.text_range().end() <= range.start()
580 fn contains_node(&self, node: &SyntaxNode) -> bool {
581 self.contains_range(node.text_range())
586 /// Analyzes a function body, returning the used local variables that are referenced in it as well as
587 /// whether it contains an await expression.
590 sema: &Semantics<RootDatabase>,
591 ) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
592 let mut self_param = None;
593 let mut res = FxIndexSet::default();
594 let mut cb = |name_ref: Option<_>| {
596 match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
598 NameRefClass::Definition(Definition::Local(local_ref))
599 | NameRefClass::FieldShorthand { local_ref, field_ref: _ },
603 let InFile { file_id, value } = local_ref.source(sema.db);
604 // locals defined inside macros are not relevant to us
605 if !file_id.is_macro() {
607 Either::Right(it) => {
608 self_param.replace(it);
611 res.insert(local_ref);
616 self.walk_expr(&mut |expr| match expr {
617 ast::Expr::PathExpr(path_expr) => {
618 cb(path_expr.path().and_then(|it| it.as_single_name_ref()))
620 ast::Expr::MacroCall(call) => {
621 if let Some(tt) = call.token_tree() {
623 .children_with_tokens()
624 .flat_map(SyntaxElement::into_token)
625 .filter(|it| it.kind() == SyntaxKind::IDENT)
626 .flat_map(|t| sema.descend_into_macros_many(t))
627 .for_each(|t| cb(t.parent().and_then(ast::NameRef::cast)));
635 fn analyze_container(&self, sema: &Semantics<RootDatabase>) -> Option<ContainerInfo> {
636 let mut ancestors = self.parent()?.ancestors();
637 let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
638 let mut parent_loop = None;
639 let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
642 .map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
644 parent_loop.get_or_insert(loop_.syntax().clone());
647 let (is_const, expr, ty) = loop {
648 let anc = ancestors.next()?;
651 ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
652 ast::BlockExpr(block_expr) => {
653 let (constness, block) = match block_expr.modifier() {
654 Some(ast::BlockModifier::Const(_)) => (true, block_expr),
655 Some(ast::BlockModifier::Try(_)) => (false, block_expr),
656 Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
659 let expr = Some(ast::Expr::BlockExpr(block));
660 (constness, expr.clone(), infer_expr_opt(expr))
663 (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(sema.to_def(&fn_)?.ret_type(sema.db)))
665 ast::Static(statik) => {
666 (true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
668 ast::ConstArg(ca) => {
669 (true, ca.expr(), infer_expr_opt(ca.expr()))
671 ast::Const(konst) => {
672 (true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
674 ast::ConstParam(cp) => {
675 (true, cp.default_val(), Some(sema.to_def(&cp)?.ty(sema.db)))
677 ast::ConstBlockPat(cbp) => {
678 let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
679 (true, expr.clone(), infer_expr_opt(expr))
681 ast::Variant(__) => return None,
682 ast::Meta(__) => return None,
683 ast::LoopExpr(it) => {
684 set_parent_loop(&it);
687 ast::ForExpr(it) => {
688 set_parent_loop(&it);
691 ast::WhileExpr(it) => {
692 set_parent_loop(&it);
699 let container_tail = match expr? {
700 ast::Expr::BlockExpr(block) => block.tail_expr(),
704 container_tail.zip(self.tail_expr()).map_or(false, |(container_tail, body_tail)| {
705 container_tail.syntax().text_range().contains_range(body_tail.syntax().text_range())
707 Some(ContainerInfo { is_in_tail, is_const, parent_loop, ret_type: ty })
710 fn return_ty(&self, ctx: &AssistContext) -> Option<RetType> {
711 match self.tail_expr() {
712 Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
713 None => Some(RetType::Stmt),
717 /// Local variables defined inside `body` that are accessed outside of it
720 ctx: &'a AssistContext,
722 ) -> impl Iterator<Item = OutlivedLocal> + 'a {
723 let parent = parent.clone();
724 let range = self.text_range();
725 locals_defined_in_body(&ctx.sema, self)
727 .filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
730 /// Analyses the function body for external control flow.
731 fn external_control_flow(
734 container_info: &ContainerInfo,
735 ) -> Option<ControlFlow> {
736 let mut ret_expr = None;
737 let mut try_expr = None;
738 let mut break_expr = None;
739 let mut continue_expr = None;
740 let mut is_async = false;
741 let mut _is_unsafe = false;
743 let mut unsafe_depth = 0;
744 let mut loop_depth = 0;
746 self.preorder_expr(&mut |expr| {
747 let expr = match expr {
748 WalkEvent::Enter(e) => e,
749 WalkEvent::Leave(expr) => {
751 ast::Expr::LoopExpr(_)
752 | ast::Expr::ForExpr(_)
753 | ast::Expr::WhileExpr(_) => loop_depth -= 1,
754 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
763 ast::Expr::LoopExpr(_) | ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) => {
766 ast::Expr::BlockExpr(block_expr) if block_expr.unsafe_token().is_some() => {
769 ast::Expr::ReturnExpr(it) => {
772 ast::Expr::TryExpr(it) => {
775 ast::Expr::BreakExpr(it) if loop_depth == 0 => {
776 break_expr = Some(it);
778 ast::Expr::ContinueExpr(it) if loop_depth == 0 => {
779 continue_expr = Some(it);
781 ast::Expr::AwaitExpr(_) => is_async = true,
782 // FIXME: Do unsafe analysis on expression, sem highlighting knows this so we should be able
783 // to just lift that out of there
784 // expr if unsafe_depth ==0 && expr.is_unsafe => is_unsafe = true,
790 let kind = match (try_expr, ret_expr, break_expr, continue_expr) {
791 (Some(_), _, None, None) => {
792 let ret_ty = container_info.ret_type.clone()?;
793 let kind = TryKind::of_ty(ret_ty, ctx)?;
795 Some(FlowKind::Try { kind })
797 (Some(_), _, _, _) => {
798 cov_mark::hit!(external_control_flow_try_and_bc);
801 (None, Some(r), None, None) => Some(FlowKind::Return(r.expr())),
802 (None, Some(_), _, _) => {
803 cov_mark::hit!(external_control_flow_return_and_bc);
806 (None, None, Some(_), Some(_)) => {
807 cov_mark::hit!(external_control_flow_break_and_continue);
810 (None, None, Some(b), None) => Some(FlowKind::Break(b.expr())),
811 (None, None, None, Some(_)) => Some(FlowKind::Continue),
812 (None, None, None, None) => None,
815 Some(ControlFlow { kind, is_async, is_unsafe: _is_unsafe })
818 /// find variables that should be extracted as params
820 /// Computes additional info that affects param type and mutability
821 fn extracted_function_params(
824 container_info: &ContainerInfo,
825 locals: impl Iterator<Item = Local>,
828 .map(|local| (local, local.source(ctx.db())))
829 .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
830 .filter_map(|(local, src)| match src.value {
831 Either::Left(src) => Some((local, src)),
832 Either::Right(_) => {
833 stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
838 let usages = LocalUsages::find_local_usages(ctx, var);
839 let ty = var.ty(ctx.db());
841 let defined_outside_parent_loop = container_info
844 .map_or(true, |it| it.text_range().contains_range(src.syntax().text_range()));
846 let is_copy = ty.is_copy(ctx.db());
847 let has_usages = self.has_usages_after_body(&usages);
849 !ty.is_mutable_reference() && has_exclusive_usages(ctx, &usages, self);
850 // We can move the value into the function call if it's not used after the call,
851 // if the var is not used but defined outside a loop we are extracting from we can't move it either
852 // as the function will reuse it in the next iteration.
853 let move_local = !has_usages && defined_outside_parent_loop;
854 Param { var, ty, move_local, requires_mut, is_copy }
859 fn has_usages_after_body(&self, usages: &LocalUsages) -> bool {
860 usages.iter().any(|reference| self.precedes_range(reference.range))
864 /// checks if relevant var is used with `&mut` access inside body
865 fn has_exclusive_usages(ctx: &AssistContext, usages: &LocalUsages, body: &FunctionBody) -> bool {
868 .filter(|reference| body.contains_range(reference.range))
869 .any(|reference| reference_is_exclusive(reference, body, ctx))
872 /// checks if this reference requires `&mut` access inside node
873 fn reference_is_exclusive(
874 reference: &FileReference,
875 node: &dyn HasTokenAtOffset,
878 // we directly modify variable with set: `n = 0`, `n += 1`
879 if reference.category == Some(ReferenceCategory::Write) {
883 // we take `&mut` reference to variable: `&mut v`
884 let path = match path_element_of_reference(node, reference) {
886 None => return false,
889 expr_require_exclusive_access(ctx, &path).unwrap_or(false)
892 /// checks if this expr requires `&mut` access, recurses on field access
893 fn expr_require_exclusive_access(ctx: &AssistContext, expr: &ast::Expr) -> Option<bool> {
894 if let ast::Expr::MacroCall(_) = expr {
895 // FIXME: expand macro and check output for mutable usages of the variable?
899 let parent = expr.syntax().parent()?;
901 if let Some(bin_expr) = ast::BinExpr::cast(parent.clone()) {
902 if matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
903 return Some(bin_expr.lhs()?.syntax() == expr.syntax());
908 if let Some(ref_expr) = ast::RefExpr::cast(parent.clone()) {
909 return Some(ref_expr.mut_token().is_some());
912 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
913 let func = ctx.sema.resolve_method_call(&method_call)?;
914 let self_param = func.self_param(ctx.db())?;
915 let access = self_param.access(ctx.db());
917 return Some(matches!(access, hir::Access::Exclusive));
920 if let Some(field) = ast::FieldExpr::cast(parent) {
921 return expr_require_exclusive_access(ctx, &field.into());
927 trait HasTokenAtOffset {
928 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken>;
931 impl HasTokenAtOffset for SyntaxNode {
932 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
933 SyntaxNode::token_at_offset(self, offset)
937 impl HasTokenAtOffset for FunctionBody {
938 fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
940 FunctionBody::Expr(expr) => expr.syntax().token_at_offset(offset),
941 FunctionBody::Span { parent, text_range } => {
942 match parent.syntax().token_at_offset(offset) {
943 TokenAtOffset::None => TokenAtOffset::None,
944 TokenAtOffset::Single(t) => {
945 if text_range.contains_range(t.text_range()) {
946 TokenAtOffset::Single(t)
951 TokenAtOffset::Between(a, b) => {
953 text_range.contains_range(a.text_range()),
954 text_range.contains_range(b.text_range()),
956 (true, true) => TokenAtOffset::Between(a, b),
957 (true, false) => TokenAtOffset::Single(a),
958 (false, true) => TokenAtOffset::Single(b),
959 (false, false) => TokenAtOffset::None,
968 /// find relevant `ast::Expr` for reference
972 /// `node` must cover `reference`, that is `node.text_range().contains_range(reference.range)`
973 fn path_element_of_reference(
974 node: &dyn HasTokenAtOffset,
975 reference: &FileReference,
976 ) -> Option<ast::Expr> {
977 let token = node.token_at_offset(reference.range.start()).right_biased().or_else(|| {
978 stdx::never!(false, "cannot find token at variable usage: {:?}", reference);
981 let path = token.ancestors().find_map(ast::Expr::cast).or_else(|| {
982 stdx::never!(false, "cannot find path parent of variable usage: {:?}", token);
986 matches!(path, ast::Expr::PathExpr(_) | ast::Expr::MacroCall(_)),
987 "unexpected expression type for variable usage: {:?}",
993 /// list local variables defined inside `body`
994 fn locals_defined_in_body(
995 sema: &Semantics<RootDatabase>,
997 ) -> FxIndexSet<Local> {
998 // FIXME: this doesn't work well with macros
999 // see https://github.com/rust-analyzer/rust-analyzer/pull/7535#discussion_r570048550
1000 let mut res = FxIndexSet::default();
1001 body.walk_pat(&mut |pat| {
1002 if let ast::Pat::IdentPat(pat) = pat {
1003 if let Some(local) = sema.to_def(&pat) {
1011 /// Returns usage details if local variable is used after(outside of) body
1012 fn local_outlives_body(
1013 ctx: &AssistContext,
1014 body_range: TextRange,
1016 parent: &SyntaxNode,
1017 ) -> Option<OutlivedLocal> {
1018 let usages = LocalUsages::find_local_usages(ctx, local);
1019 let mut has_mut_usages = false;
1020 let mut any_outlives = false;
1021 for usage in usages.iter() {
1022 if body_range.end() <= usage.range.start() {
1023 has_mut_usages |= reference_is_exclusive(usage, parent, ctx);
1024 any_outlives |= true;
1026 break; // no need to check more elements we have all the info we wanted
1033 Some(OutlivedLocal { local, mut_usage_outside_body: has_mut_usages })
1036 /// checks if the relevant local was defined before(outside of) body
1037 fn is_defined_outside_of_body(
1038 ctx: &AssistContext,
1039 body: &FunctionBody,
1040 src: &hir::InFile<Either<ast::IdentPat, ast::SelfParam>>,
1042 src.file_id.original_file(ctx.db()) == ctx.frange.file_id
1043 && !body.contains_node(either_syntax(&src.value))
1046 fn either_syntax(value: &Either<ast::IdentPat, ast::SelfParam>) -> &SyntaxNode {
1048 Either::Left(pat) => pat.syntax(),
1049 Either::Right(it) => it.syntax(),
1053 /// find where to put extracted function definition
1055 /// Function should be put right after returned node
1056 fn node_to_insert_after(body: &FunctionBody, anchor: Anchor) -> Option<SyntaxNode> {
1057 let node = match body {
1058 FunctionBody::Expr(e) => e.syntax(),
1059 FunctionBody::Span { parent, .. } => parent.syntax(),
1061 let mut ancestors = node.ancestors().peekable();
1062 let mut last_ancestor = None;
1063 while let Some(next_ancestor) = ancestors.next() {
1064 match next_ancestor.kind() {
1065 SyntaxKind::SOURCE_FILE => break,
1066 SyntaxKind::ITEM_LIST if !matches!(anchor, Anchor::Freestanding) => continue,
1067 SyntaxKind::ITEM_LIST => {
1068 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::MODULE) {
1072 SyntaxKind::ASSOC_ITEM_LIST if !matches!(anchor, Anchor::Method) => {
1075 SyntaxKind::ASSOC_ITEM_LIST => {
1076 if ancestors.peek().map(SyntaxNode::kind) == Some(SyntaxKind::IMPL) {
1082 last_ancestor = Some(next_ancestor);
1087 fn make_call(ctx: &AssistContext, fun: &Function, indent: IndentLevel) -> String {
1088 let ret_ty = fun.return_type(ctx);
1090 let args = make::arg_list(fun.params.iter().map(|param| param.to_arg(ctx)));
1091 let name = fun.name.clone();
1092 let mut call_expr = if fun.self_param.is_some() {
1093 let self_arg = make::expr_path(make::ext::ident_path("self"));
1094 make::expr_method_call(self_arg, name, args)
1096 let func = make::expr_path(make::path_unqualified(make::path_segment(name)));
1097 make::expr_call(func, args)
1100 let handler = FlowHandler::from_ret_ty(fun, &ret_ty);
1102 if fun.control_flow.is_async {
1103 call_expr = make::expr_await(call_expr);
1105 let expr = handler.make_call_expr(call_expr).indent(indent);
1107 let mut_modifier = |var: &OutlivedLocal| if var.mut_usage_outside_body { "mut " } else { "" };
1109 let mut buf = String::new();
1110 match fun.outliving_locals.as_slice() {
1113 format_to!(buf, "let {}{} = ", mut_modifier(var), var.local.name(ctx.db()).unwrap())
1116 buf.push_str("let (");
1117 let bindings = vars.iter().format_with(", ", |local, f| {
1118 f(&format_args!("{}{}", mut_modifier(local), local.local.name(ctx.db()).unwrap()))
1120 format_to!(buf, "{}", bindings);
1121 buf.push_str(") = ");
1125 format_to!(buf, "{}", expr);
1126 let insert_comma = fun
1129 .and_then(ast::MatchArm::cast)
1130 .map_or(false, |it| it.comma_token().is_none());
1133 } else if fun.ret_ty.is_unit() && (!fun.outliving_locals.is_empty() || !expr.is_block_like()) {
1141 Try { kind: TryKind },
1142 If { action: FlowKind },
1143 IfOption { action: FlowKind },
1144 MatchOption { none: FlowKind },
1145 MatchResult { err: FlowKind },
1149 fn from_ret_ty(fun: &Function, ret_ty: &FunType) -> FlowHandler {
1150 match &fun.control_flow.kind {
1151 None => FlowHandler::None,
1152 Some(flow_kind) => {
1153 let action = flow_kind.clone();
1154 if *ret_ty == FunType::Unit {
1156 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1157 FlowHandler::If { action }
1159 FlowKind::Return(_) | FlowKind::Break(_) => {
1160 FlowHandler::IfOption { action }
1162 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1166 FlowKind::Return(None) | FlowKind::Break(None) | FlowKind::Continue => {
1167 FlowHandler::MatchOption { none: action }
1169 FlowKind::Return(_) | FlowKind::Break(_) => {
1170 FlowHandler::MatchResult { err: action }
1172 FlowKind::Try { kind } => FlowHandler::Try { kind: kind.clone() },
1179 fn make_call_expr(&self, call_expr: ast::Expr) -> ast::Expr {
1181 FlowHandler::None => call_expr,
1182 FlowHandler::Try { kind: _ } => make::expr_try(call_expr),
1183 FlowHandler::If { action } => {
1184 let action = action.make_result_handler(None);
1185 let stmt = make::expr_stmt(action);
1186 let block = make::block_expr(iter::once(stmt.into()), None);
1187 let condition = make::condition(call_expr, None);
1188 make::expr_if(condition, block, None)
1190 FlowHandler::IfOption { action } => {
1191 let path = make::ext::ident_path("Some");
1192 let value_pat = make::ext::simple_ident_pat(make::name("value"));
1193 let pattern = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1194 let cond = make::condition(call_expr, Some(pattern.into()));
1195 let value = make::expr_path(make::ext::ident_path("value"));
1196 let action_expr = action.make_result_handler(Some(value));
1197 let action_stmt = make::expr_stmt(action_expr);
1198 let then = make::block_expr(iter::once(action_stmt.into()), None);
1199 make::expr_if(cond, then, None)
1201 FlowHandler::MatchOption { none } => {
1202 let some_name = "value";
1205 let path = make::ext::ident_path("Some");
1206 let value_pat = make::ext::simple_ident_pat(make::name(some_name));
1207 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1208 let value = make::expr_path(make::ext::ident_path(some_name));
1209 make::match_arm(iter::once(pat.into()), None, value)
1212 let path = make::ext::ident_path("None");
1213 let pat = make::path_pat(path);
1214 make::match_arm(iter::once(pat), None, none.make_result_handler(None))
1216 let arms = make::match_arm_list(vec![some_arm, none_arm]);
1217 make::expr_match(call_expr, arms)
1219 FlowHandler::MatchResult { err } => {
1220 let ok_name = "value";
1221 let err_name = "value";
1224 let path = make::ext::ident_path("Ok");
1225 let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
1226 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1227 let value = make::expr_path(make::ext::ident_path(ok_name));
1228 make::match_arm(iter::once(pat.into()), None, value)
1231 let path = make::ext::ident_path("Err");
1232 let value_pat = make::ext::simple_ident_pat(make::name(err_name));
1233 let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
1234 let value = make::expr_path(make::ext::ident_path(err_name));
1236 iter::once(pat.into()),
1238 err.make_result_handler(Some(value)),
1241 let arms = make::match_arm_list(vec![ok_arm, err_arm]);
1242 make::expr_match(call_expr, arms)
1248 fn path_expr_from_local(ctx: &AssistContext, var: Local) -> ast::Expr {
1249 let name = var.name(ctx.db()).unwrap().to_string();
1250 make::expr_path(make::ext::ident_path(&name))
1254 ctx: &AssistContext,
1255 module: hir::Module,
1257 old_indent: IndentLevel,
1258 new_indent: IndentLevel,
1260 let mut fn_def = String::new();
1261 let params = fun.make_param_list(ctx, module);
1262 let ret_ty = fun.make_ret_ty(ctx, module);
1263 let body = make_body(ctx, old_indent, new_indent, fun);
1264 let const_kw = if fun.mods.is_const { "const " } else { "" };
1265 let async_kw = if fun.control_flow.is_async { "async " } else { "" };
1266 let unsafe_kw = if fun.control_flow.is_unsafe { "unsafe " } else { "" };
1267 match ctx.config.snippet_cap {
1268 Some(_) => format_to!(
1270 "\n\n{}{}{}{}fn $0{}{}",
1280 "\n\n{}{}{}{}fn {}{}",
1289 if let Some(ret_ty) = ret_ty {
1290 format_to!(fn_def, " {}", ret_ty);
1292 format_to!(fn_def, " {}", body);
1298 fn make_param_list(&self, ctx: &AssistContext, module: hir::Module) -> ast::ParamList {
1299 let self_param = self.self_param.clone();
1300 let params = self.params.iter().map(|param| param.to_param(ctx, module));
1301 make::param_list(self_param, params)
1304 fn make_ret_ty(&self, ctx: &AssistContext, module: hir::Module) -> Option<ast::RetType> {
1305 let fun_ty = self.return_type(ctx);
1306 let handler = if self.mods.is_in_tail {
1309 FlowHandler::from_ret_ty(self, &fun_ty)
1311 let ret_ty = match &handler {
1312 FlowHandler::None => {
1313 if matches!(fun_ty, FunType::Unit) {
1316 fun_ty.make_ty(ctx, module)
1318 FlowHandler::Try { kind: TryKind::Option } => {
1319 make::ext::ty_option(fun_ty.make_ty(ctx, module))
1321 FlowHandler::Try { kind: TryKind::Result { ty: parent_ret_ty } } => {
1322 let handler_ty = parent_ret_ty
1325 .map(|ty| make_ty(&ty, ctx, module))
1326 .unwrap_or_else(make::ty_placeholder);
1327 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1329 FlowHandler::If { .. } => make::ext::ty_bool(),
1330 FlowHandler::IfOption { action } => {
1331 let handler_ty = action
1333 .map(|ty| make_ty(&ty, ctx, module))
1334 .unwrap_or_else(make::ty_placeholder);
1335 make::ext::ty_option(handler_ty)
1337 FlowHandler::MatchOption { .. } => make::ext::ty_option(fun_ty.make_ty(ctx, module)),
1338 FlowHandler::MatchResult { err } => {
1339 let handler_ty = err
1341 .map(|ty| make_ty(&ty, ctx, module))
1342 .unwrap_or_else(make::ty_placeholder);
1343 make::ext::ty_result(fun_ty.make_ty(ctx, module), handler_ty)
1346 Some(make::ret_type(ret_ty))
1351 fn make_ty(&self, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1353 FunType::Unit => make::ty_unit(),
1354 FunType::Single(ty) => make_ty(ty, ctx, module),
1355 FunType::Tuple(types) => match types.as_slice() {
1357 stdx::never!("tuple type with 0 elements");
1361 stdx::never!("tuple type with 1 element");
1362 make_ty(ty, ctx, module)
1365 let types = types.iter().map(|ty| make_ty(ty, ctx, module));
1366 make::ty_tuple(types)
1374 ctx: &AssistContext,
1375 old_indent: IndentLevel,
1376 new_indent: IndentLevel,
1378 ) -> ast::BlockExpr {
1379 let ret_ty = fun.return_type(ctx);
1380 let handler = if fun.mods.is_in_tail {
1383 FlowHandler::from_ret_ty(fun, &ret_ty)
1385 let block = match &fun.body {
1386 FunctionBody::Expr(expr) => {
1387 let expr = rewrite_body_segment(ctx, &fun.params, &handler, expr.syntax());
1388 let expr = ast::Expr::cast(expr).unwrap();
1390 ast::Expr::BlockExpr(block) => {
1391 // If the extracted expression is itself a block, there is no need to wrap it inside another block.
1392 let block = block.dedent(old_indent);
1393 // Recreate the block for formatting consistency with other extracted functions.
1394 make::block_expr(block.statements(), block.tail_expr())
1397 let expr = expr.dedent(old_indent).indent(IndentLevel(1));
1399 make::block_expr(Vec::new(), Some(expr))
1403 FunctionBody::Span { parent, text_range } => {
1404 let mut elements: Vec<_> = parent
1407 .filter(|it| text_range.contains_range(it.text_range()))
1408 .map(|it| rewrite_body_segment(ctx, &fun.params, &handler, &it))
1411 let mut tail_expr = match elements.pop() {
1412 Some(node) => ast::Expr::cast(node.clone()).or_else(|| {
1413 elements.push(node);
1419 if tail_expr.is_none() {
1420 match fun.outliving_locals.as_slice() {
1423 tail_expr = Some(path_expr_from_local(ctx, var.local));
1426 let exprs = vars.iter().map(|var| path_expr_from_local(ctx, var.local));
1427 let expr = make::expr_tuple(exprs);
1428 tail_expr = Some(expr);
1433 let elements = elements.into_iter().filter_map(|node| match ast::Stmt::cast(node) {
1434 Some(stmt) => Some(stmt),
1436 stdx::never!("block contains non-statement");
1441 let body_indent = IndentLevel(1);
1442 let elements = elements.map(|stmt| stmt.dedent(old_indent).indent(body_indent));
1443 let tail_expr = tail_expr.map(|expr| expr.dedent(old_indent).indent(body_indent));
1445 make::block_expr(elements, tail_expr)
1449 let block = match &handler {
1450 FlowHandler::None => block,
1451 FlowHandler::Try { kind } => {
1452 let block = with_default_tail_expr(block, make::expr_unit());
1453 map_tail_expr(block, |tail_expr| {
1454 let constructor = match kind {
1455 TryKind::Option => "Some",
1456 TryKind::Result { .. } => "Ok",
1458 let func = make::expr_path(make::ext::ident_path(constructor));
1459 let args = make::arg_list(iter::once(tail_expr));
1460 make::expr_call(func, args)
1463 FlowHandler::If { .. } => {
1464 let lit_false = make::expr_literal("false");
1465 with_tail_expr(block, lit_false.into())
1467 FlowHandler::IfOption { .. } => {
1468 let none = make::expr_path(make::ext::ident_path("None"));
1469 with_tail_expr(block, none)
1471 FlowHandler::MatchOption { .. } => map_tail_expr(block, |tail_expr| {
1472 let some = make::expr_path(make::ext::ident_path("Some"));
1473 let args = make::arg_list(iter::once(tail_expr));
1474 make::expr_call(some, args)
1476 FlowHandler::MatchResult { .. } => map_tail_expr(block, |tail_expr| {
1477 let ok = make::expr_path(make::ext::ident_path("Ok"));
1478 let args = make::arg_list(iter::once(tail_expr));
1479 make::expr_call(ok, args)
1483 block.indent(new_indent)
1486 fn map_tail_expr(block: ast::BlockExpr, f: impl FnOnce(ast::Expr) -> ast::Expr) -> ast::BlockExpr {
1487 let tail_expr = match block.tail_expr() {
1488 Some(tail_expr) => tail_expr,
1489 None => return block,
1491 make::block_expr(block.statements(), Some(f(tail_expr)))
1494 fn with_default_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1495 match block.tail_expr() {
1497 None => make::block_expr(block.statements(), Some(tail_expr)),
1501 fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr {
1502 let stmt_tail = block.tail_expr().map(|expr| make::expr_stmt(expr).into());
1503 let stmts = block.statements().chain(stmt_tail);
1504 make::block_expr(stmts, Some(tail_expr))
1507 fn format_type(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> String {
1508 ty.display_source_code(ctx.db(), module.into()).ok().unwrap_or_else(|| "_".to_string())
1511 fn make_ty(ty: &hir::Type, ctx: &AssistContext, module: hir::Module) -> ast::Type {
1512 let ty_str = format_type(ty, ctx, module);
1516 fn rewrite_body_segment(
1517 ctx: &AssistContext,
1519 handler: &FlowHandler,
1520 syntax: &SyntaxNode,
1522 let syntax = fix_param_usages(ctx, params, syntax);
1523 update_external_control_flow(handler, &syntax);
1527 /// change all usages to account for added `&`/`&mut` for some params
1528 fn fix_param_usages(ctx: &AssistContext, params: &[Param], syntax: &SyntaxNode) -> SyntaxNode {
1529 let mut usages_for_param: Vec<(&Param, Vec<ast::Expr>)> = Vec::new();
1531 let tm = TreeMutator::new(syntax);
1533 for param in params {
1534 if !param.kind().is_ref() {
1538 let usages = LocalUsages::find_local_usages(ctx, param.var);
1541 .filter(|reference| syntax.text_range().contains_range(reference.range))
1542 .filter_map(|reference| path_element_of_reference(syntax, reference))
1543 .map(|expr| tm.make_mut(&expr));
1545 usages_for_param.push((param, usages.collect()));
1548 let res = tm.make_syntax_mut(syntax);
1550 for (param, usages) in usages_for_param {
1551 for usage in usages {
1552 match usage.syntax().ancestors().skip(1).find_map(ast::Expr::cast) {
1553 Some(ast::Expr::MethodCallExpr(_) | ast::Expr::FieldExpr(_)) => {
1556 Some(ast::Expr::RefExpr(node))
1557 if param.kind() == ParamKind::MutRef && node.mut_token().is_some() =>
1559 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1561 Some(ast::Expr::RefExpr(node))
1562 if param.kind() == ParamKind::SharedRef && node.mut_token().is_none() =>
1564 ted::replace(node.syntax(), node.expr().unwrap().syntax());
1567 let p = &make::expr_prefix(T![*], usage.clone()).clone_for_update();
1568 ted::replace(usage.syntax(), p.syntax())
1577 fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) {
1578 let mut nested_loop = None;
1579 let mut nested_scope = None;
1580 for event in syntax.preorder() {
1582 WalkEvent::Enter(e) => match e.kind() {
1583 SyntaxKind::LOOP_EXPR | SyntaxKind::WHILE_EXPR | SyntaxKind::FOR_EXPR => {
1584 if nested_loop.is_none() {
1585 nested_loop = Some(e.clone());
1590 | SyntaxKind::STATIC
1592 | SyntaxKind::MODULE => {
1593 if nested_scope.is_none() {
1594 nested_scope = Some(e.clone());
1599 WalkEvent::Leave(e) => {
1600 if nested_scope.is_none() {
1601 if let Some(expr) = ast::Expr::cast(e.clone()) {
1603 ast::Expr::ReturnExpr(return_expr) if nested_scope.is_none() => {
1604 let expr = return_expr.expr();
1605 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1606 ted::replace(return_expr.syntax(), replacement.syntax())
1609 ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => {
1610 let expr = break_expr.expr();
1611 if let Some(replacement) = make_rewritten_flow(handler, expr) {
1612 ted::replace(break_expr.syntax(), replacement.syntax())
1615 ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => {
1616 if let Some(replacement) = make_rewritten_flow(handler, None) {
1617 ted::replace(continue_expr.syntax(), replacement.syntax())
1627 if nested_loop.as_ref() == Some(&e) {
1630 if nested_scope.as_ref() == Some(&e) {
1631 nested_scope = None;
1638 fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1639 let value = match handler {
1640 FlowHandler::None | FlowHandler::Try { .. } => return None,
1641 FlowHandler::If { .. } => make::expr_literal("true").into(),
1642 FlowHandler::IfOption { .. } => {
1643 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1644 let args = make::arg_list(iter::once(expr));
1645 make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
1647 FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
1648 FlowHandler::MatchResult { .. } => {
1649 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1650 let args = make::arg_list(iter::once(expr));
1651 make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
1654 Some(make::expr_return(Some(value)).clone_for_update())
1659 use crate::tests::{check_assist, check_assist_not_applicable};
1664 fn no_args_from_binary_expr() {
1677 fn $0fun_name() -> i32 {
1685 fn no_args_from_binary_expr_in_module() {
1701 fn $0fun_name() -> i32 {
1710 fn no_args_from_binary_expr_indented() {
1723 fn $0fun_name() -> i32 {
1731 fn no_args_from_stmt_with_last_expr() {
1747 fn $0fun_name() -> i32 {
1756 fn no_args_from_stmt_unit() {
1804 fn no_args_if_else() {
1809 $0if true { 1 } else { 2 }$0
1817 fn $0fun_name() -> i32 {
1818 if true { 1 } else { 2 }
1825 fn no_args_if_let_else() {
1830 $0if let true = false { 1 } else { 2 }$0
1838 fn $0fun_name() -> i32 {
1839 if let true = false { 1 } else { 2 }
1846 fn no_args_match() {
1862 fn $0fun_name() -> i32 {
1873 fn no_args_while() {
1899 $0for v in &[0, 1] { }$0
1908 for v in &[0, 1] { }
1915 fn no_args_from_loop_unit() {
1930 fn $0fun_name() -> ! {
1940 fn no_args_from_loop_with_return() {
1956 fn $0fun_name() -> i32 {
1967 fn no_args_from_match() {
1972 let v: i32 = $0match Some(1) {
1980 let v: i32 = fun_name();
1983 fn $0fun_name() -> i32 {
1994 fn extract_partial_block_single_line() {
2000 let mut v = $0n * n;$0
2007 let mut v = fun_name(n);
2011 fn $0fun_name(n: i32) -> i32 {
2020 fn extract_partial_block() {
2027 let mut v = m $0* n;
2037 let (mut v, mut w) = fun_name(m, n);
2042 fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
2052 fn argument_form_expr() {
2067 fn $0fun_name(n: u32) -> u32 {
2075 fn argument_used_twice_form_expr() {
2090 fn $0fun_name(n: u32) -> u32 {
2098 fn two_arguments_form_expr() {
2115 fn $0fun_name(n: u32, m: u32) -> u32 {
2123 fn argument_and_locals() {
2139 fn $0fun_name(n: u32) -> u32 {
2148 fn in_comment_is_not_applicable() {
2149 cov_mark::check!(extract_function_in_comment_is_not_applicable);
2150 check_assist_not_applicable(extract_function, r"fn main() { 1 + /* $0comment$0 */ 1; }");
2154 fn part_of_expr_stmt() {
2167 fn $0fun_name() -> i32 {
2175 fn function_expr() {
2196 fn extract_from_nested() {
2202 let tuple = match x {
2203 true => ($02 + 2$0, true)
2211 let tuple = match x {
2212 true => (fun_name(), true)
2217 fn $0fun_name() -> i32 {
2225 fn param_from_closure() {
2230 let lambda = |x: u32| $0x * 2$0;
2235 let lambda = |x: u32| fun_name(x);
2238 fn $0fun_name(x: u32) -> u32 {
2246 fn extract_return_stmt() {
2259 fn $0fun_name() -> u32 {
2267 fn does_not_add_extra_whitespace() {
2284 fn $0fun_name() -> u32 {
2309 fn $0fun_name() -> i32 {
2322 let v = $00f32 as u32$0;
2330 fn $0fun_name() -> u32 {
2338 fn return_not_applicable() {
2339 check_assist_not_applicable(extract_function, r"fn foo() { $0return$0; } ");
2343 fn method_to_freestanding() {
2350 fn foo(&self) -> i32 {
2359 fn foo(&self) -> i32 {
2364 fn $0fun_name() -> i32 {
2372 fn method_with_reference() {
2376 struct S { f: i32 };
2379 fn foo(&self) -> i32 {
2385 struct S { f: i32 };
2388 fn foo(&self) -> i32 {
2392 fn $0fun_name(&self) -> i32 {
2401 fn method_with_mut() {
2405 struct S { f: i32 };
2414 struct S { f: i32 };
2421 fn $0fun_name(&mut self) {
2430 fn variable_defined_inside_and_used_after_no_ret() {
2443 let k = fun_name(n);
2447 fn $0fun_name(n: i32) -> i32 {
2456 fn variable_defined_inside_and_used_after_mutably_no_ret() {
2462 $0let mut k = n * n;$0
2469 let mut k = fun_name(n);
2473 fn $0fun_name(n: i32) -> i32 {
2482 fn two_variables_defined_inside_and_used_after_no_ret() {
2496 let (k, m) = fun_name(n);
2500 fn $0fun_name(n: i32) -> (i32, i32) {
2510 fn multi_variables_defined_inside_and_used_after_mutably_no_ret() {
2516 $0let mut k = n * n;
2527 let (mut k, mut m, o) = fun_name(n);
2532 fn $0fun_name(n: i32) -> (i32, i32, i32) {
2544 fn nontrivial_patterns_define_variables() {
2548 struct Counter(i32);
2550 $0let Counter(n) = Counter(0);$0
2555 struct Counter(i32);
2561 fn $0fun_name() -> i32 {
2562 let Counter(n) = Counter(0);
2570 fn struct_with_two_fields_pattern_define_variables() {
2574 struct Counter { n: i32, m: i32 };
2576 $0let Counter { n, m: k } = Counter { n: 1, m: 2 };$0
2581 struct Counter { n: i32, m: i32 };
2583 let (n, k) = fun_name();
2587 fn $0fun_name() -> (i32, i32) {
2588 let Counter { n, m: k } = Counter { n: 1, m: 2 };
2596 fn mut_var_from_outer_scope() {
2613 fn $0fun_name(n: &mut i32) {
2621 fn mut_field_from_outer_scope() {
2627 let mut c = C { n: 0 };
2635 let mut c = C { n: 0 };
2640 fn $0fun_name(c: &mut C) {
2648 fn mut_nested_field_from_outer_scope() {
2655 let mut c = C { p: P { n: 0 } };
2656 let mut v = C { p: P { n: 0 } };
2657 let u = C { p: P { n: 0 } };
2659 let r = &mut v.p.n;$0
2660 let m = c.p.n + v.p.n + u.p.n;
2667 let mut c = C { p: P { n: 0 } };
2668 let mut v = C { p: P { n: 0 } };
2669 let u = C { p: P { n: 0 } };
2670 fun_name(&mut c, &u, &mut v);
2671 let m = c.p.n + v.p.n + u.p.n;
2674 fn $0fun_name(c: &mut C, u: &C, v: &mut C) {
2683 fn mut_param_many_usages_stmt() {
2689 fn succ(&self) -> Self;
2690 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2693 fn succ(&self) -> Self { *self + 1 }
2712 fn succ(&self) -> Self;
2713 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2716 fn succ(&self) -> Self { *self + 1 }
2724 fn $0fun_name(n: &mut i32) {
2740 fn mut_param_many_usages_expr() {
2746 fn succ(&self) -> Self;
2747 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2750 fn succ(&self) -> Self { *self + 1 }
2771 fn succ(&self) -> Self;
2772 fn inc(&mut self) -> Self { let v = self.succ(); *self = v; v }
2775 fn succ(&self) -> Self { *self + 1 }
2783 fn $0fun_name(n: &mut i32) {
2799 fn mut_param_by_value() {
2814 fn $0fun_name(mut n: i32) {
2822 fn mut_param_because_of_mut_ref() {
2840 fn $0fun_name(n: &mut i32) {
2849 fn mut_param_by_value_because_of_mut_ref() {
2865 fn $0fun_name(mut n: i32) {
2874 fn mut_method_call() {
2882 fn inc(&mut self) { *self += 1 }
2894 fn inc(&mut self) { *self += 1 }
2901 fn $0fun_name(mut n: i32) {
2909 fn shared_method_call() {
2917 fn succ(&self) { *self + 1 }
2929 fn succ(&self) { *self + 1 }
2936 fn $0fun_name(n: i32) {
2944 fn mut_method_call_with_other_receiver() {
2949 fn inc(&mut self, n: i32);
2952 fn inc(&mut self, n: i32) { *self += n }
2962 fn inc(&mut self, n: i32);
2965 fn inc(&mut self, n: i32) { *self += n }
2972 fn $0fun_name(n: i32) {
2981 fn non_copy_without_usages_after() {
2985 struct Counter(i32);
2992 struct Counter(i32);
2998 fn $0fun_name(c: Counter) {
3006 fn non_copy_used_after() {
3010 struct Counter(i32);
3018 struct Counter(i32);
3025 fn $0fun_name(c: &Counter) {
3033 fn copy_used_after() {
3051 fn $0fun_name(n: i32) {
3059 fn copy_custom_used_after() {
3063 //- minicore: copy, derive
3064 #[derive(Clone, Copy)]
3065 struct Counter(i32);
3073 #[derive(Clone, Copy)]
3074 struct Counter(i32);
3081 fn $0fun_name(c: Counter) {
3089 fn indented_stmts() {
3120 fn indented_stmts_inside_mod() {
3159 //- minicore: option
3174 let k = match fun_name(n) {
3175 Some(value) => value,
3182 fn $0fun_name(n: i32) -> Option<i32> {
3193 fn return_to_parent() {
3197 //- minicore: copy, result
3209 let k = match fun_name(n) {
3211 Err(value) => return value,
3216 fn $0fun_name(n: i32) -> Result<i32, i64> {
3227 fn break_and_continue() {
3228 cov_mark::check!(external_control_flow_break_and_continue);
3229 check_assist_not_applicable(
3248 fn return_and_break() {
3249 cov_mark::check!(external_control_flow_return_and_bc);
3250 check_assist_not_applicable(
3269 fn break_loop_with_if() {
3287 if fun_name(&mut n) {
3294 fn $0fun_name(n: &mut i32) -> bool {
3305 fn break_loop_nested() {
3331 fn $0fun_name(n: i32) -> bool {
3343 fn return_from_nested_loop() {
3363 let m = match fun_name() {
3364 Some(value) => value,
3371 fn $0fun_name() -> Option<i32> {
3384 fn break_from_nested_loop() {
3409 fn $0fun_name() -> i32 {
3422 fn break_from_nested_and_outer_loops() {
3445 let m = match fun_name() {
3446 Some(value) => value,
3453 fn $0fun_name() -> Option<i32> {
3469 fn return_from_nested_fn() {
3494 fn $0fun_name() -> i32 {
3507 fn break_with_value() {
3527 if let Some(value) = fun_name() {
3534 fn $0fun_name() -> Option<i32> {
3547 fn break_with_value_and_return() {
3567 let m = match fun_name() {
3569 Err(value) => break value,
3575 fn $0fun_name() -> Result<i32, i64> {
3592 //- minicore: option
3593 fn bar() -> Option<i32> { None }
3594 fn foo() -> Option<()> {
3603 fn bar() -> Option<i32> { None }
3604 fn foo() -> Option<()> {
3606 let m = fun_name()?;
3611 fn $0fun_name() -> Option<i32> {
3621 fn try_option_unit() {
3625 //- minicore: option
3626 fn foo() -> Option<()> {
3635 fn foo() -> Option<()> {
3642 fn $0fun_name() -> Option<()> {
3656 //- minicore: result
3657 fn foo() -> Result<(), i64> {
3666 fn foo() -> Result<(), i64> {
3668 let m = fun_name()?;
3673 fn $0fun_name() -> Result<i32, i64> {
3683 fn try_option_with_return() {
3687 //- minicore: option
3688 fn foo() -> Option<()> {
3700 fn foo() -> Option<()> {
3702 let m = fun_name()?;
3707 fn $0fun_name() -> Option<i32> {
3720 fn try_result_with_return() {
3724 //- minicore: result
3725 fn foo() -> Result<(), i64> {
3737 fn foo() -> Result<(), i64> {
3739 let m = fun_name()?;
3744 fn $0fun_name() -> Result<i32, i64> {
3757 fn try_and_break() {
3758 cov_mark::check!(external_control_flow_try_and_bc);
3759 check_assist_not_applicable(
3762 //- minicore: option
3763 fn foo() -> Option<()> {
3779 fn try_and_return_ok() {
3783 //- minicore: result
3784 fn foo() -> Result<(), i64> {
3796 fn foo() -> Result<(), i64> {
3798 let m = fun_name()?;
3803 fn $0fun_name() -> Result<i32, i64> {
3816 fn param_usage_in_macro() {
3821 ($val:expr) => { $val };
3826 $0let k = n * m!(n);$0
3832 ($val:expr) => { $val };
3837 let k = fun_name(n);
3841 fn $0fun_name(n: i32) -> i32 {
3850 fn extract_with_await() {
3855 $0some_function().await;$0
3858 async fn some_function() {
3867 async fn $0fun_name() {
3868 some_function().await;
3871 async fn some_function() {
3879 fn extract_with_await_and_result_not_producing_match_expr() {
3883 async fn foo() -> Result<(), ()> {
3889 async fn foo() -> Result<(), ()> {
3893 async fn $0fun_name() -> _ {
3902 fn extract_with_await_and_result_producing_match_expr() {
3906 async fn foo() -> i32 {
3909 let k = async { 1 }.await;
3919 async fn foo() -> i32 {
3922 let m = match fun_name().await {
3924 Err(value) => break value,
3930 async fn $0fun_name() -> Result<i32, i32> {
3931 let k = async { 1 }.await;
3943 fn extract_with_await_in_args() {
3948 $0function_call("a", some_function().await);$0
3951 async fn some_function() {
3960 async fn $0fun_name() {
3961 function_call("a", some_function().await);
3964 async fn some_function() {
3972 fn extract_does_not_extract_standalone_blocks() {
3973 check_assist_not_applicable(
3982 fn extract_adds_comma_for_match_arm() {
4001 fn $0fun_name() -> i32 {
4024 fn $0fun_name() -> i32 {
4032 fn extract_does_not_tear_comments_apart() {
4059 fn extract_does_not_wrap_res_in_res() {
4063 //- minicore: result
4064 fn foo() -> Result<(), i64> {
4065 $0Result::<i32, i64>::Ok(0)?;
4070 fn foo() -> Result<(), i64> {
4074 fn $0fun_name() -> Result<(), i64> {
4075 Result::<i32, i64>::Ok(0)?;
4083 fn extract_knows_const() {
4096 const fn $0fun_name() {
4113 const fn $0fun_name() {
4121 fn extract_does_not_move_outer_loop_vars() {
4140 fn $0fun_name(x: &mut i32) {
4163 fn $0fun_name(mut x: i32) {
4190 fn $0fun_name(x: &mut i32) {
4197 // regression test for #9822
4199 fn extract_mut_ref_param_has_no_mut_binding_in_loop() {
4205 fn foo(&mut self) {}
4219 fn foo(&mut self) {}
4230 fn $0fun_name(y: &mut Foo) {
4238 fn extract_with_macro_arg() {
4243 ($val:expr) => { $val };
4252 ($val:expr) => { $val };
4259 fn $0fun_name(bar: &str) {
4267 fn unresolveable_types_default_to_placeholder() {
4272 let a = __unresolved;
4278 let a = __unresolved;
4279 let _ = fun_name(a);
4282 fn $0fun_name(a: _) -> _ {