3 use hir::{db::HirDatabase, HasSource, PathResolution, Semantics, TypeInfo};
5 base_db::{FileId, FileRange},
7 helpers::insert_use::remove_path_if_in_use_stmt,
8 path_transform::PathTransform,
9 search::{FileReference, SearchScope},
12 use itertools::{izip, Itertools};
14 ast::{self, edit_in_place::Indent, ArgListOwner},
15 ted, AstNode, SyntaxNode,
19 assist_context::{AssistContext, Assists},
23 // Assist: inline_into_callers
25 // Inline a function or method body into all of its callers where possible, creating a `let` statement per parameter
26 // unless the parameter can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
27 // or if the parameter is only accessed inside the function body once.
28 // If all calls can be inlined the function will be removed.
31 // fn print(_: &str) {}
32 // fn foo$0(word: &str) {
33 // if !word.is_empty() {
44 // fn print(_: &str) {}
48 // let word = "안녕하세요";
49 // if !word.is_empty() {
55 // if !word.is_empty() {
61 pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
62 let def_file = ctx.frange.file_id;
63 let name = ctx.find_node_at_offset::<ast::Name>()?;
64 let ast_func = name.syntax().parent().and_then(ast::Fn::cast)?;
65 let func_body = ast_func.body()?;
66 let param_list = ast_func.param_list()?;
68 let function = ctx.sema.to_def(&ast_func)?;
70 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
72 let usages = Definition::ModuleDef(hir::ModuleDef::Function(function)).usages(&ctx.sema);
73 if !usages.at_least_one() {
77 let is_recursive_fn = usages
79 .in_scope(SearchScope::file_range(FileRange {
81 range: func_body.syntax().text_range(),
85 cov_mark::hit!(inline_into_callers_recursive);
90 AssistId("inline_into_callers", AssistKind::RefactorInline),
91 "Inline into all callers",
92 name.syntax().text_range(),
94 let mut usages = usages.all();
95 let current_file_usage = usages.references.remove(&def_file);
97 let mut remove_def = true;
98 let mut inline_refs_for_file = |file_id, refs: Vec<FileReference>| {
99 builder.edit_file(file_id);
100 let count = refs.len();
101 // The collects are required as we are otherwise iterating while mutating 🙅♀️🙅♂️
102 let (name_refs, name_refs_use): (Vec<_>, Vec<_>) = refs
104 .filter_map(|file_ref| match file_ref.name {
105 ast::NameLike::NameRef(name_ref) => Some(name_ref),
108 .partition_map(|name_ref| {
109 match name_ref.syntax().ancestors().find_map(ast::UseTree::cast) {
110 Some(use_tree) => Either::Right(builder.make_mut(use_tree)),
111 None => Either::Left(name_ref),
114 let call_infos: Vec<_> = name_refs
116 .filter_map(CallInfo::from_name_ref)
118 let mut_node = builder.make_syntax_mut(call_info.node.syntax().clone());
119 (call_info, mut_node)
122 let replaced = call_infos
124 .map(|(call_info, mut_node)| {
126 inline(&ctx.sema, def_file, function, &func_body, ¶ms, &call_info);
127 ted::replace(mut_node, replacement.syntax());
130 if replaced + name_refs_use.len() == count {
131 // we replaced all usages in this file, so we can remove the imports
132 name_refs_use.into_iter().for_each(|use_tree| {
133 if let Some(path) = use_tree.path() {
134 remove_path_if_in_use_stmt(&path);
141 for (file_id, refs) in usages.into_iter() {
142 inline_refs_for_file(file_id, refs);
144 if let Some(refs) = current_file_usage {
145 inline_refs_for_file(def_file, refs);
147 builder.edit_file(def_file);
150 builder.delete(ast_func.syntax().text_range());
156 // Assist: inline_call
158 // Inlines a function or method body creating a `let` statement per parameter unless the parameter
159 // can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
160 // or if the parameter is only accessed inside the function body once.
163 // # //- minicore: option
164 // fn foo(name: Option<&str>) {
165 // let name = name.unwrap$0();
170 // fn foo(name: Option<&str>) {
171 // let name = match name {
173 // None => panic!("called `Option::unwrap()` on a `None` value"),
177 pub(crate) fn inline_call(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
178 let name_ref: ast::NameRef = ctx.find_node_at_offset()?;
179 let call_info = CallInfo::from_name_ref(name_ref.clone())?;
180 let (function, label) = match &call_info.node {
181 CallExprNode::Call(call) => {
182 let path = match call.expr()? {
183 ast::Expr::PathExpr(path) => path.path(),
186 let function = match ctx.sema.resolve_path(&path)? {
187 PathResolution::Def(hir::ModuleDef::Function(f)) => f,
188 PathResolution::AssocItem(hir::AssocItem::Function(f)) => f,
191 (function, format!("Inline `{}`", path))
193 CallExprNode::MethodCallExpr(call) => {
194 (ctx.sema.resolve_method_call(call)?, format!("Inline `{}`", name_ref))
198 let fn_source = function.source(ctx.db())?;
199 let fn_body = fn_source.value.body()?;
200 let param_list = fn_source.value.param_list()?;
202 let FileRange { file_id, range } = fn_source.syntax().original_file_range(ctx.sema.db);
203 if file_id == ctx.frange.file_id && range.contains(ctx.frange.range.start()) {
204 cov_mark::hit!(inline_call_recursive);
207 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
209 if call_info.arguments.len() != params.len() {
210 // Can't inline the function because they've passed the wrong number of
211 // arguments to this function
212 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
216 let syntax = call_info.node.syntax().clone();
218 AssistId("inline_call", AssistKind::RefactorInline),
222 let replacement = inline(&ctx.sema, file_id, function, &fn_body, ¶ms, &call_info);
225 match call_info.node {
226 CallExprNode::Call(it) => ast::Expr::CallExpr(it),
227 CallExprNode::MethodCallExpr(it) => ast::Expr::MethodCallExpr(it),
237 MethodCallExpr(ast::MethodCallExpr),
241 fn syntax(&self) -> &SyntaxNode {
243 CallExprNode::Call(it) => it.syntax(),
244 CallExprNode::MethodCallExpr(it) => it.syntax(),
251 arguments: Vec<ast::Expr>,
252 generic_arg_list: Option<ast::GenericArgList>,
256 fn from_name_ref(name_ref: ast::NameRef) -> Option<CallInfo> {
257 let parent = name_ref.syntax().parent()?;
258 if let Some(call) = ast::MethodCallExpr::cast(parent.clone()) {
259 let receiver = call.receiver()?;
260 let mut arguments = vec![receiver];
261 arguments.extend(call.arg_list()?.args());
263 generic_arg_list: call.generic_arg_list(),
264 node: CallExprNode::MethodCallExpr(call),
267 } else if let Some(segment) = ast::PathSegment::cast(parent) {
268 let path = segment.syntax().parent().and_then(ast::Path::cast)?;
269 let path = path.syntax().parent().and_then(ast::PathExpr::cast)?;
270 let call = path.syntax().parent().and_then(ast::CallExpr::cast)?;
273 arguments: call.arg_list()?.args().collect(),
274 node: CallExprNode::Call(call),
275 generic_arg_list: segment.generic_arg_list(),
284 db: &dyn HirDatabase,
285 function: hir::Function,
286 param_list: &ast::ParamList,
287 ) -> Option<Vec<(ast::Pat, Option<ast::Type>, hir::Param)>> {
288 let mut assoc_fn_params = function.assoc_fn_params(db).into_iter();
290 let mut params = Vec::new();
291 if let Some(self_param) = param_list.self_param() {
292 // FIXME this should depend on the receiver as well as the self_param
295 self_param.amp_token().is_some(),
296 self_param.mut_token().is_some(),
301 assoc_fn_params.next()?,
304 for param in param_list.params() {
305 params.push((param.pat()?, param.ty(), assoc_fn_params.next()?));
312 sema: &Semantics<RootDatabase>,
313 function_def_file_id: FileId,
314 function: hir::Function,
315 fn_body: &ast::BlockExpr,
316 params: &[(ast::Pat, Option<ast::Type>, hir::Param)],
317 CallInfo { node, arguments, generic_arg_list }: &CallInfo,
319 let body = fn_body.clone_for_update();
320 let usages_for_locals = |local| {
321 Definition::Local(local)
325 .remove(&function_def_file_id)
329 let param_use_nodes: Vec<Vec<_>> = params
331 .map(|(pat, _, param)| {
332 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
335 usages_for_locals(param.as_local(sema.db))
336 .map(|FileReference { name, range, .. }| match name {
337 ast::NameLike::NameRef(_) => body
339 .covering_element(range)
342 .and_then(ast::PathExpr::cast),
345 .collect::<Option<Vec<_>>>()
349 if function.self_param(sema.db).is_some() {
350 let this = || make::name_ref("this").syntax().clone_for_update();
351 usages_for_locals(params[0].2.as_local(sema.db))
352 .flat_map(|FileReference { name, range, .. }| match name {
353 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
357 ted::replace(it, &this());
360 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
361 for ((pat, param_ty, _), usages, expr) in izip!(params, param_use_nodes, arguments).rev() {
362 let expr_is_name_ref = matches!(&expr,
363 ast::Expr::PathExpr(expr)
364 if expr.path().and_then(|path| path.as_single_name_ref()).is_some()
367 // inline single use closure arguments
369 if matches!(expr, ast::Expr::ClosureExpr(_))
370 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
372 cov_mark::hit!(inline_call_inline_closure);
373 let expr = make::expr_paren(expr.clone());
374 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
376 // inline single use literals
377 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
378 cov_mark::hit!(inline_call_inline_literal);
379 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
381 // inline direct local arguments
382 [_, ..] if expr_is_name_ref => {
383 cov_mark::hit!(inline_call_inline_locals);
384 usages.into_iter().for_each(|usage| {
385 ted::replace(usage.syntax(), &expr.syntax().clone_for_update());
388 // cant inline, emit a let statement
391 sema.type_of_expr(expr).filter(TypeInfo::has_adjustment).and(param_ty.clone());
393 make::let_stmt(pat.clone(), ty, Some(expr.clone())).clone_for_update().into(),
398 if let Some(generic_arg_list) = generic_arg_list.clone() {
399 PathTransform::function_call(
400 &sema.scope(node.syntax()),
401 &sema.scope(fn_body.syntax()),
405 .apply(body.syntax());
408 let original_indentation = match node {
409 CallExprNode::Call(it) => it.indent_level(),
410 CallExprNode::MethodCallExpr(it) => it.indent_level(),
412 body.reindent_to(original_indentation);
414 match body.tail_expr() {
415 Some(expr) if body.statements().next().is_none() => expr,
416 _ => ast::Expr::BlockExpr(body),
422 use crate::tests::{check_assist, check_assist_not_applicable};
427 fn no_args_or_return_value_gets_inlined_without_block() {
431 fn foo() { println!("Hello, World!"); }
437 fn foo() { println!("Hello, World!"); }
439 { println!("Hello, World!"); };
446 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
447 cov_mark::check!(inline_call_incorrect_number_of_arguments);
448 check_assist_not_applicable(
451 fn add(a: u32, b: u32) -> u32 { a + b }
452 fn main() { let x = add$0(42); }
458 fn args_with_side_effects() {
462 fn foo(name: String) {
463 println!("Hello, {}!", name);
466 foo$0(String::from("Michael"));
470 fn foo(name: String) {
471 println!("Hello, {}!", name);
475 let name = String::from("Michael");
476 println!("Hello, {}!", name);
484 fn function_with_multiple_statements() {
488 fn foo(a: u32, b: u32) -> u32 {
499 fn foo(a: u32, b: u32) -> u32 {
518 fn function_with_self_param() {
525 fn add(self, a: u32) -> Self {
531 let x = Foo::add$0(Foo(3), 2);
538 fn add(self, a: u32) -> Self {
561 fn add(self, a: u32) -> Self {
567 let x = Foo(3).add$0(2);
574 fn add(self, a: u32) -> Self {
597 fn add(&self, a: u32) -> Self {
603 let x = Foo(3).add$0(2);
610 fn add(&self, a: u32) -> Self {
617 let ref this = Foo(3);
626 fn method_by_ref_mut() {
633 fn clear(&mut self) {
639 let mut foo = Foo(3);
647 fn clear(&mut self) {
653 let mut foo = Foo(3);
655 let ref mut this = foo;
664 fn function_multi_use_expr_in_param() {
668 fn square(x: u32) -> u32 {
673 let y = square$0(10 + x);
677 fn square(x: u32) -> u32 {
692 fn function_use_local_in_param() {
693 cov_mark::check!(inline_call_inline_locals);
697 fn square(x: u32) -> u32 {
702 let y = square$0(local);
706 fn square(x: u32) -> u32 {
711 let y = local * local;
718 fn method_in_impl() {
753 fn wraps_closure_in_paren() {
754 cov_mark::check!(inline_call_inline_closure);
804 fn inline_single_literal_expr() {
805 cov_mark::check!(inline_call_inline_literal);
809 fn foo(x: u32) -> u32{
818 fn foo(x: u32) -> u32{
830 fn inline_emits_type_for_coercion() {
834 fn foo(x: *const u32) -> u32 {
843 fn foo(x: *const u32) -> u32 {
849 let x: *const u32 = &222;
857 // FIXME: const generics aren't being substituted, this is blocked on better support for them
859 fn inline_substitutes_generics() {
863 fn foo<T, const N: usize>() {
867 fn bar<U, const M: usize>() {}
870 foo$0::<usize, {0}>();
874 fn foo<T, const N: usize>() {
878 fn bar<U, const M: usize>() {}
888 fn inline_callers() {
892 fn do_the_math$0(b: u32) -> u32 {
920 fn inline_callers_across_files() {
926 fn do_the_math$0(b: u32) -> u32 {
931 use super::do_the_math;
959 fn inline_callers_across_files_with_def_file() {
965 fn do_the_math$0(b: u32) -> u32 {
969 fn bar(a: u32, b: u32) -> u32 {
973 use super::do_the_math;
982 fn bar(a: u32, b: u32) -> u32 {
1000 fn inline_callers_recursive() {
1001 cov_mark::check!(inline_into_callers_recursive);
1002 check_assist_not_applicable(
1003 inline_into_callers,
1013 fn inline_call_recursive() {
1014 cov_mark::check!(inline_call_recursive);
1015 check_assist_not_applicable(