3 use hir::{db::HirDatabase, PathResolution, Semantics, TypeInfo};
5 base_db::{FileId, FileRange},
7 imports::insert_use::remove_path_if_in_use_stmt,
8 path_transform::PathTransform,
9 search::{FileReference, SearchScope},
10 syntax_helpers::{insert_whitespace_into_node::insert_ws_into, node_ext::expr_as_name_ref},
13 use itertools::{izip, Itertools};
15 ast::{self, edit_in_place::Indent, HasArgList, PathExpr},
16 ted, AstNode, NodeOrToken, SyntaxKind,
20 assist_context::{AssistContext, Assists},
24 // Assist: inline_into_callers
26 // Inline a function or method body into all of its callers where possible, creating a `let` statement per parameter
27 // unless the parameter can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
28 // or if the parameter is only accessed inside the function body once.
29 // If all calls can be inlined the function will be removed.
32 // fn print(_: &str) {}
33 // fn foo$0(word: &str) {
34 // if !word.is_empty() {
45 // fn print(_: &str) {}
49 // let word = "안녕하세요";
50 // if !word.is_empty() {
56 // if !word.is_empty() {
62 pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
63 let def_file = ctx.file_id();
64 let name = ctx.find_node_at_offset::<ast::Name>()?;
65 let ast_func = name.syntax().parent().and_then(ast::Fn::cast)?;
66 let func_body = ast_func.body()?;
67 let param_list = ast_func.param_list()?;
69 let function = ctx.sema.to_def(&ast_func)?;
71 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
73 let usages = Definition::Function(function).usages(&ctx.sema);
74 if !usages.at_least_one() {
78 let is_recursive_fn = usages
80 .in_scope(SearchScope::file_range(FileRange {
82 range: func_body.syntax().text_range(),
86 cov_mark::hit!(inline_into_callers_recursive);
91 AssistId("inline_into_callers", AssistKind::RefactorInline),
92 "Inline into all callers",
93 name.syntax().text_range(),
95 let mut usages = usages.all();
96 let current_file_usage = usages.references.remove(&def_file);
98 let mut remove_def = true;
99 let mut inline_refs_for_file = |file_id, refs: Vec<FileReference>| {
100 builder.edit_file(file_id);
101 let count = refs.len();
102 // The collects are required as we are otherwise iterating while mutating 🙅♀️🙅♂️
103 let (name_refs, name_refs_use): (Vec<_>, Vec<_>) = refs
105 .filter_map(|file_ref| match file_ref.name {
106 ast::NameLike::NameRef(name_ref) => Some(name_ref),
109 .partition_map(|name_ref| {
110 match name_ref.syntax().ancestors().find_map(ast::UseTree::cast) {
111 Some(use_tree) => Either::Right(builder.make_mut(use_tree)),
112 None => Either::Left(name_ref),
115 let call_infos: Vec<_> = name_refs
117 .filter_map(CallInfo::from_name_ref)
119 let mut_node = builder.make_syntax_mut(call_info.node.syntax().clone());
120 (call_info, mut_node)
123 let replaced = call_infos
125 .map(|(call_info, mut_node)| {
127 inline(&ctx.sema, def_file, function, &func_body, ¶ms, &call_info);
128 ted::replace(mut_node, replacement.syntax());
131 if replaced + name_refs_use.len() == count {
132 // we replaced all usages in this file, so we can remove the imports
133 name_refs_use.into_iter().for_each(|use_tree| {
134 if let Some(path) = use_tree.path() {
135 remove_path_if_in_use_stmt(&path);
142 for (file_id, refs) in usages.into_iter() {
143 inline_refs_for_file(file_id, refs);
145 match current_file_usage {
146 Some(refs) => inline_refs_for_file(def_file, refs),
147 None => 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 ast::CallableExpr::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,
190 (function, format!("Inline `{}`", path))
192 ast::CallableExpr::MethodCall(call) => {
193 (ctx.sema.resolve_method_call(call)?, format!("Inline `{}`", name_ref))
197 let fn_source = ctx.sema.source(function)?;
198 let fn_body = fn_source.value.body()?;
199 let param_list = fn_source.value.param_list()?;
201 let FileRange { file_id, range } = fn_source.syntax().original_file_range(ctx.sema.db);
202 if file_id == ctx.file_id() && range.contains(ctx.offset()) {
203 cov_mark::hit!(inline_call_recursive);
206 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
208 if call_info.arguments.len() != params.len() {
209 // Can't inline the function because they've passed the wrong number of
210 // arguments to this function
211 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
215 let syntax = call_info.node.syntax().clone();
217 AssistId("inline_call", AssistKind::RefactorInline),
221 let replacement = inline(&ctx.sema, file_id, function, &fn_body, ¶ms, &call_info);
224 match call_info.node {
225 ast::CallableExpr::Call(it) => ast::Expr::CallExpr(it),
226 ast::CallableExpr::MethodCall(it) => ast::Expr::MethodCallExpr(it),
235 node: ast::CallableExpr,
236 arguments: Vec<ast::Expr>,
237 generic_arg_list: Option<ast::GenericArgList>,
241 fn from_name_ref(name_ref: ast::NameRef) -> Option<CallInfo> {
242 let parent = name_ref.syntax().parent()?;
243 if let Some(call) = ast::MethodCallExpr::cast(parent.clone()) {
244 let receiver = call.receiver()?;
245 let mut arguments = vec![receiver];
246 arguments.extend(call.arg_list()?.args());
248 generic_arg_list: call.generic_arg_list(),
249 node: ast::CallableExpr::MethodCall(call),
252 } else if let Some(segment) = ast::PathSegment::cast(parent) {
253 let path = segment.syntax().parent().and_then(ast::Path::cast)?;
254 let path = path.syntax().parent().and_then(ast::PathExpr::cast)?;
255 let call = path.syntax().parent().and_then(ast::CallExpr::cast)?;
258 arguments: call.arg_list()?.args().collect(),
259 node: ast::CallableExpr::Call(call),
260 generic_arg_list: segment.generic_arg_list(),
269 db: &dyn HirDatabase,
270 function: hir::Function,
271 param_list: &ast::ParamList,
272 ) -> Option<Vec<(ast::Pat, Option<ast::Type>, hir::Param)>> {
273 let mut assoc_fn_params = function.assoc_fn_params(db).into_iter();
275 let mut params = Vec::new();
276 if let Some(self_param) = param_list.self_param() {
277 // FIXME this should depend on the receiver as well as the self_param
280 self_param.amp_token().is_some(),
281 self_param.mut_token().is_some(),
286 assoc_fn_params.next()?,
289 for param in param_list.params() {
290 params.push((param.pat()?, param.ty(), assoc_fn_params.next()?));
297 sema: &Semantics<'_, RootDatabase>,
298 function_def_file_id: FileId,
299 function: hir::Function,
300 fn_body: &ast::BlockExpr,
301 params: &[(ast::Pat, Option<ast::Type>, hir::Param)],
302 CallInfo { node, arguments, generic_arg_list }: &CallInfo,
304 let body = if sema.hir_file_for(fn_body.syntax()).is_macro() {
305 cov_mark::hit!(inline_call_defined_in_macro);
306 if let Some(body) = ast::BlockExpr::cast(insert_ws_into(fn_body.syntax().clone())) {
309 fn_body.clone_for_update()
312 fn_body.clone_for_update()
314 if let Some(imp) = body.syntax().ancestors().find_map(ast::Impl::cast) {
315 if !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) {
316 if let Some(t) = imp.self_ty() {
318 .descendants_with_tokens()
319 .filter_map(NodeOrToken::into_token)
320 .filter(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW)
321 .for_each(|tok| ted::replace(tok, t.syntax()));
325 let usages_for_locals = |local| {
326 Definition::Local(local)
330 .remove(&function_def_file_id)
334 let param_use_nodes: Vec<Vec<_>> = params
336 .map(|(pat, _, param)| {
337 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
340 // FIXME: we need to fetch all locals declared in the parameter here
341 // not only the local if it is a simple binding
342 match param.as_local(sema.db) {
343 Some(l) => usages_for_locals(l)
344 .map(|FileReference { name, range, .. }| match name {
345 ast::NameLike::NameRef(_) => body
347 .covering_element(range)
350 .and_then(ast::PathExpr::cast),
353 .collect::<Option<Vec<_>>>()
354 .unwrap_or_default(),
360 if function.self_param(sema.db).is_some() {
361 let this = || make::name_ref("this").syntax().clone_for_update();
362 if let Some(self_local) = params[0].2.as_local(sema.db) {
363 usages_for_locals(self_local)
364 .flat_map(|FileReference { name, range, .. }| match name {
365 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
369 ted::replace(it, &this());
373 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
374 for ((pat, param_ty, _), usages, expr) in izip!(params, param_use_nodes, arguments).rev() {
375 let inline_direct = |usage, replacement: &ast::Expr| {
376 if let Some(field) = path_expr_as_record_field(usage) {
377 cov_mark::hit!(inline_call_inline_direct_field);
378 field.replace_expr(replacement.clone_for_update());
380 ted::replace(usage.syntax(), &replacement.syntax().clone_for_update());
383 // izip confuses RA due to our lack of hygiene info currently losing us type info causing incorrect errors
384 let usages: &[ast::PathExpr] = &*usages;
385 let expr: &ast::Expr = expr;
387 // inline single use closure arguments
389 if matches!(expr, ast::Expr::ClosureExpr(_))
390 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
392 cov_mark::hit!(inline_call_inline_closure);
393 let expr = make::expr_paren(expr.clone());
394 inline_direct(usage, &expr);
396 // inline single use literals
397 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
398 cov_mark::hit!(inline_call_inline_literal);
399 inline_direct(usage, expr);
401 // inline direct local arguments
402 [_, ..] if expr_as_name_ref(expr).is_some() => {
403 cov_mark::hit!(inline_call_inline_locals);
404 usages.iter().for_each(|usage| inline_direct(usage, expr));
406 // can't inline, emit a let statement
409 sema.type_of_expr(expr).filter(TypeInfo::has_adjustment).and(param_ty.clone());
410 if let Some(stmt_list) = body.stmt_list() {
411 stmt_list.push_front(
412 make::let_stmt(pat.clone(), ty, Some(expr.clone()))
420 if let Some(generic_arg_list) = generic_arg_list.clone() {
421 if let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax()))
423 PathTransform::function_call(target, source, function, generic_arg_list)
424 .apply(body.syntax());
428 let original_indentation = match node {
429 ast::CallableExpr::Call(it) => it.indent_level(),
430 ast::CallableExpr::MethodCall(it) => it.indent_level(),
432 body.reindent_to(original_indentation);
434 match body.tail_expr() {
435 Some(expr) if body.statements().next().is_none() => expr,
439 .and_then(ast::BinExpr::cast)
440 .and_then(|bin_expr| bin_expr.lhs())
442 Some(lhs) if lhs.syntax() == node.syntax() => {
443 make::expr_paren(ast::Expr::BlockExpr(body)).clone_for_update()
445 _ => ast::Expr::BlockExpr(body),
450 fn path_expr_as_record_field(usage: &PathExpr) -> Option<ast::RecordExprField> {
451 let path = usage.path()?;
452 let name_ref = path.as_single_name_ref()?;
453 ast::RecordExprField::for_name_ref(&name_ref)
458 use crate::tests::{check_assist, check_assist_not_applicable};
463 fn no_args_or_return_value_gets_inlined_without_block() {
467 fn foo() { println!("Hello, World!"); }
473 fn foo() { println!("Hello, World!"); }
475 { println!("Hello, World!"); };
482 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
483 cov_mark::check!(inline_call_incorrect_number_of_arguments);
484 check_assist_not_applicable(
487 fn add(a: u32, b: u32) -> u32 { a + b }
488 fn main() { let x = add$0(42); }
494 fn args_with_side_effects() {
498 fn foo(name: String) {
499 println!("Hello, {}!", name);
502 foo$0(String::from("Michael"));
506 fn foo(name: String) {
507 println!("Hello, {}!", name);
511 let name = String::from("Michael");
512 println!("Hello, {}!", name);
520 fn function_with_multiple_statements() {
524 fn foo(a: u32, b: u32) -> u32 {
535 fn foo(a: u32, b: u32) -> u32 {
554 fn function_with_self_param() {
561 fn add(self, a: u32) -> Self {
567 let x = Foo::add$0(Foo(3), 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 {
633 fn add(&self, a: u32) -> Self {
639 let x = Foo(3).add$0(2);
646 fn add(&self, a: u32) -> Self {
653 let ref this = Foo(3);
662 fn method_by_ref_mut() {
669 fn clear(&mut self) {
675 let mut foo = Foo(3);
683 fn clear(&mut self) {
689 let mut foo = Foo(3);
691 let ref mut this = foo;
700 fn function_multi_use_expr_in_param() {
704 fn square(x: u32) -> u32 {
709 let y = square$0(10 + x);
713 fn square(x: u32) -> u32 {
728 fn function_use_local_in_param() {
729 cov_mark::check!(inline_call_inline_locals);
733 fn square(x: u32) -> u32 {
738 let y = square$0(local);
742 fn square(x: u32) -> u32 {
747 let y = local * local;
754 fn method_in_impl() {
789 fn wraps_closure_in_paren() {
790 cov_mark::check!(inline_call_inline_closure);
840 fn inline_single_literal_expr() {
841 cov_mark::check!(inline_call_inline_literal);
845 fn foo(x: u32) -> u32{
854 fn foo(x: u32) -> u32{
866 fn inline_emits_type_for_coercion() {
870 fn foo(x: *const u32) -> u32 {
879 fn foo(x: *const u32) -> u32 {
885 let x: *const u32 = &222;
893 // FIXME: const generics aren't being substituted, this is blocked on better support for them
895 fn inline_substitutes_generics() {
899 fn foo<T, const N: usize>() {
903 fn bar<U, const M: usize>() {}
906 foo$0::<usize, {0}>();
910 fn foo<T, const N: usize>() {
914 fn bar<U, const M: usize>() {}
924 fn inline_callers() {
928 fn do_the_math$0(b: u32) -> u32 {
956 fn inline_callers_across_files() {
962 fn do_the_math$0(b: u32) -> u32 {
967 use super::do_the_math;
995 fn inline_callers_across_files_with_def_file() {
1001 fn do_the_math$0(b: u32) -> u32 {
1005 fn bar(a: u32, b: u32) -> u32 {
1009 use super::do_the_math;
1018 fn bar(a: u32, b: u32) -> u32 {
1036 fn inline_callers_recursive() {
1037 cov_mark::check!(inline_into_callers_recursive);
1038 check_assist_not_applicable(
1039 inline_into_callers,
1049 fn inline_call_recursive() {
1050 cov_mark::check!(inline_call_recursive);
1051 check_assist_not_applicable(
1062 fn inline_call_field_shorthand() {
1063 cov_mark::check!(inline_call_inline_direct_field);
1073 fn foo(field: u32, field1: u32, val2: u32, val3: u32) -> Foo {
1084 foo$0(bar, 0, baz, 0);
1094 fn foo(field: u32, field1: u32, val2: u32, val3: u32) -> Foo {
1117 fn inline_callers_wrapped_in_parentheses() {
1119 inline_into_callers,
1145 fn inline_call_wrapped_in_parentheses() {
1173 fn inline_call_defined_in_macro() {
1174 cov_mark::check!(inline_call_defined_in_macro);
1178 macro_rules! define_foo {
1179 () => { fn foo() -> u32 {
1190 macro_rules! define_foo {
1191 () => { fn foo() -> u32 {
1208 fn inline_call_with_self_type() {
1214 fn f() -> Self { Self(114514) }
1223 fn f() -> Self { Self(114514) }
1233 fn inline_call_with_self_type_but_within_same_impl() {
1239 fn f() -> Self { Self(1919810) }
1248 fn f() -> Self { Self(1919810) }