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 source_change::SourceChangeBuilder,
11 syntax_helpers::{insert_whitespace_into_node::insert_ws_into, node_ext::expr_as_name_ref},
14 use itertools::{izip, Itertools};
16 ast::{self, edit_in_place::Indent, HasArgList, PathExpr},
17 ted, AstNode, NodeOrToken, SyntaxKind,
21 assist_context::{AssistContext, Assists},
25 // Assist: inline_into_callers
27 // Inline a function or method body into all of its callers where possible, creating a `let` statement per parameter
28 // unless the parameter can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
29 // or if the parameter is only accessed inside the function body once.
30 // If all calls can be inlined the function will be removed.
33 // fn print(_: &str) {}
34 // fn foo$0(word: &str) {
35 // if !word.is_empty() {
46 // fn print(_: &str) {}
50 // let word = "안녕하세요";
51 // if !word.is_empty() {
57 // if !word.is_empty() {
63 pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
64 let def_file = ctx.file_id();
65 let name = ctx.find_node_at_offset::<ast::Name>()?;
66 let ast_func = name.syntax().parent().and_then(ast::Fn::cast)?;
67 let func_body = ast_func.body()?;
68 let param_list = ast_func.param_list()?;
70 let function = ctx.sema.to_def(&ast_func)?;
72 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
74 let usages = Definition::Function(function).usages(&ctx.sema);
75 if !usages.at_least_one() {
79 let is_recursive_fn = usages
81 .in_scope(SearchScope::file_range(FileRange {
83 range: func_body.syntax().text_range(),
87 cov_mark::hit!(inline_into_callers_recursive);
92 AssistId("inline_into_callers", AssistKind::RefactorInline),
93 "Inline into all callers",
94 name.syntax().text_range(),
96 let mut usages = usages.all();
97 let current_file_usage = usages.references.remove(&def_file);
99 let mut remove_def = true;
100 let mut inline_refs_for_file = |file_id, refs: Vec<FileReference>| {
101 builder.edit_file(file_id);
102 let count = refs.len();
103 // The collects are required as we are otherwise iterating while mutating 🙅♀️🙅♂️
104 let (name_refs, name_refs_use) = split_refs_and_uses(builder, refs, Some);
105 let call_infos: Vec<_> = name_refs
107 .filter_map(CallInfo::from_name_ref)
109 let mut_node = builder.make_syntax_mut(call_info.node.syntax().clone());
110 (call_info, mut_node)
113 let replaced = call_infos
115 .map(|(call_info, mut_node)| {
117 inline(&ctx.sema, def_file, function, &func_body, ¶ms, &call_info);
118 ted::replace(mut_node, replacement.syntax());
121 if replaced + name_refs_use.len() == count {
122 // we replaced all usages in this file, so we can remove the imports
123 name_refs_use.iter().for_each(remove_path_if_in_use_stmt);
128 for (file_id, refs) in usages.into_iter() {
129 inline_refs_for_file(file_id, refs);
131 match current_file_usage {
132 Some(refs) => inline_refs_for_file(def_file, refs),
133 None => builder.edit_file(def_file),
136 builder.delete(ast_func.syntax().text_range());
142 pub(super) fn split_refs_and_uses<T: ast::AstNode>(
143 builder: &mut SourceChangeBuilder,
144 iter: impl IntoIterator<Item = FileReference>,
145 mut map_ref: impl FnMut(ast::NameRef) -> Option<T>,
146 ) -> (Vec<T>, Vec<ast::Path>) {
148 .filter_map(|file_ref| match file_ref.name {
149 ast::NameLike::NameRef(name_ref) => Some(name_ref),
152 .filter_map(|name_ref| match name_ref.syntax().ancestors().find_map(ast::UseTree::cast) {
153 Some(use_tree) => builder.make_mut(use_tree).path().map(Either::Right),
154 None => map_ref(name_ref).map(Either::Left),
156 .partition_map(|either| either)
159 // Assist: inline_call
161 // Inlines a function or method body creating a `let` statement per parameter unless the parameter
162 // can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
163 // or if the parameter is only accessed inside the function body once.
166 // # //- minicore: option
167 // fn foo(name: Option<&str>) {
168 // let name = name.unwrap$0();
173 // fn foo(name: Option<&str>) {
174 // let name = match name {
176 // None => panic!("called `Option::unwrap()` on a `None` value"),
180 pub(crate) fn inline_call(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
181 let name_ref: ast::NameRef = ctx.find_node_at_offset()?;
182 let call_info = CallInfo::from_name_ref(name_ref.clone())?;
183 let (function, label) = match &call_info.node {
184 ast::CallableExpr::Call(call) => {
185 let path = match call.expr()? {
186 ast::Expr::PathExpr(path) => path.path(),
189 let function = match ctx.sema.resolve_path(&path)? {
190 PathResolution::Def(hir::ModuleDef::Function(f)) => f,
193 (function, format!("Inline `{}`", path))
195 ast::CallableExpr::MethodCall(call) => {
196 (ctx.sema.resolve_method_call(call)?, format!("Inline `{}`", name_ref))
200 let fn_source = ctx.sema.source(function)?;
201 let fn_body = fn_source.value.body()?;
202 let param_list = fn_source.value.param_list()?;
204 let FileRange { file_id, range } = fn_source.syntax().original_file_range(ctx.sema.db);
205 if file_id == ctx.file_id() && range.contains(ctx.offset()) {
206 cov_mark::hit!(inline_call_recursive);
209 let params = get_fn_params(ctx.sema.db, function, ¶m_list)?;
211 if call_info.arguments.len() != params.len() {
212 // Can't inline the function because they've passed the wrong number of
213 // arguments to this function
214 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
218 let syntax = call_info.node.syntax().clone();
220 AssistId("inline_call", AssistKind::RefactorInline),
224 let replacement = inline(&ctx.sema, file_id, function, &fn_body, ¶ms, &call_info);
227 match call_info.node {
228 ast::CallableExpr::Call(it) => ast::Expr::CallExpr(it),
229 ast::CallableExpr::MethodCall(it) => ast::Expr::MethodCallExpr(it),
238 node: ast::CallableExpr,
239 arguments: Vec<ast::Expr>,
240 generic_arg_list: Option<ast::GenericArgList>,
244 fn from_name_ref(name_ref: ast::NameRef) -> Option<CallInfo> {
245 let parent = name_ref.syntax().parent()?;
246 if let Some(call) = ast::MethodCallExpr::cast(parent.clone()) {
247 let receiver = call.receiver()?;
248 let mut arguments = vec![receiver];
249 arguments.extend(call.arg_list()?.args());
251 generic_arg_list: call.generic_arg_list(),
252 node: ast::CallableExpr::MethodCall(call),
255 } else if let Some(segment) = ast::PathSegment::cast(parent) {
256 let path = segment.syntax().parent().and_then(ast::Path::cast)?;
257 let path = path.syntax().parent().and_then(ast::PathExpr::cast)?;
258 let call = path.syntax().parent().and_then(ast::CallExpr::cast)?;
261 arguments: call.arg_list()?.args().collect(),
262 node: ast::CallableExpr::Call(call),
263 generic_arg_list: segment.generic_arg_list(),
272 db: &dyn HirDatabase,
273 function: hir::Function,
274 param_list: &ast::ParamList,
275 ) -> Option<Vec<(ast::Pat, Option<ast::Type>, hir::Param)>> {
276 let mut assoc_fn_params = function.assoc_fn_params(db).into_iter();
278 let mut params = Vec::new();
279 if let Some(self_param) = param_list.self_param() {
280 // FIXME this should depend on the receiver as well as the self_param
283 self_param.amp_token().is_some(),
284 self_param.mut_token().is_some(),
289 assoc_fn_params.next()?,
292 for param in param_list.params() {
293 params.push((param.pat()?, param.ty(), assoc_fn_params.next()?));
300 sema: &Semantics<'_, RootDatabase>,
301 function_def_file_id: FileId,
302 function: hir::Function,
303 fn_body: &ast::BlockExpr,
304 params: &[(ast::Pat, Option<ast::Type>, hir::Param)],
305 CallInfo { node, arguments, generic_arg_list }: &CallInfo,
307 let body = if sema.hir_file_for(fn_body.syntax()).is_macro() {
308 cov_mark::hit!(inline_call_defined_in_macro);
309 if let Some(body) = ast::BlockExpr::cast(insert_ws_into(fn_body.syntax().clone())) {
312 fn_body.clone_for_update()
315 fn_body.clone_for_update()
317 if let Some(imp) = body.syntax().ancestors().find_map(ast::Impl::cast) {
318 if !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) {
319 if let Some(t) = imp.self_ty() {
321 .descendants_with_tokens()
322 .filter_map(NodeOrToken::into_token)
323 .filter(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW)
324 .for_each(|tok| ted::replace(tok, t.syntax()));
328 let usages_for_locals = |local| {
329 Definition::Local(local)
333 .remove(&function_def_file_id)
337 let param_use_nodes: Vec<Vec<_>> = params
339 .map(|(pat, _, param)| {
340 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
343 // FIXME: we need to fetch all locals declared in the parameter here
344 // not only the local if it is a simple binding
345 match param.as_local(sema.db) {
346 Some(l) => usages_for_locals(l)
347 .map(|FileReference { name, range, .. }| match name {
348 ast::NameLike::NameRef(_) => body
350 .covering_element(range)
353 .and_then(ast::PathExpr::cast),
356 .collect::<Option<Vec<_>>>()
357 .unwrap_or_default(),
363 if function.self_param(sema.db).is_some() {
364 let this = || make::name_ref("this").syntax().clone_for_update();
365 if let Some(self_local) = params[0].2.as_local(sema.db) {
366 usages_for_locals(self_local)
367 .flat_map(|FileReference { name, range, .. }| match name {
368 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
372 ted::replace(it, &this());
376 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
377 for ((pat, param_ty, _), usages, expr) in izip!(params, param_use_nodes, arguments).rev() {
378 let inline_direct = |usage, replacement: &ast::Expr| {
379 if let Some(field) = path_expr_as_record_field(usage) {
380 cov_mark::hit!(inline_call_inline_direct_field);
381 field.replace_expr(replacement.clone_for_update());
383 ted::replace(usage.syntax(), &replacement.syntax().clone_for_update());
386 // izip confuses RA due to our lack of hygiene info currently losing us type info causing incorrect errors
387 let usages: &[ast::PathExpr] = &*usages;
388 let expr: &ast::Expr = expr;
390 // inline single use closure arguments
392 if matches!(expr, ast::Expr::ClosureExpr(_))
393 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
395 cov_mark::hit!(inline_call_inline_closure);
396 let expr = make::expr_paren(expr.clone());
397 inline_direct(usage, &expr);
399 // inline single use literals
400 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
401 cov_mark::hit!(inline_call_inline_literal);
402 inline_direct(usage, expr);
404 // inline direct local arguments
405 [_, ..] if expr_as_name_ref(expr).is_some() => {
406 cov_mark::hit!(inline_call_inline_locals);
407 usages.iter().for_each(|usage| inline_direct(usage, expr));
409 // can't inline, emit a let statement
412 sema.type_of_expr(expr).filter(TypeInfo::has_adjustment).and(param_ty.clone());
413 if let Some(stmt_list) = body.stmt_list() {
414 stmt_list.push_front(
415 make::let_stmt(pat.clone(), ty, Some(expr.clone()))
423 if let Some(generic_arg_list) = generic_arg_list.clone() {
424 if let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax()))
426 PathTransform::function_call(target, source, function, generic_arg_list)
427 .apply(body.syntax());
431 let original_indentation = match node {
432 ast::CallableExpr::Call(it) => it.indent_level(),
433 ast::CallableExpr::MethodCall(it) => it.indent_level(),
435 body.reindent_to(original_indentation);
437 match body.tail_expr() {
438 Some(expr) if body.statements().next().is_none() => expr,
442 .and_then(ast::BinExpr::cast)
443 .and_then(|bin_expr| bin_expr.lhs())
445 Some(lhs) if lhs.syntax() == node.syntax() => {
446 make::expr_paren(ast::Expr::BlockExpr(body)).clone_for_update()
448 _ => ast::Expr::BlockExpr(body),
453 fn path_expr_as_record_field(usage: &PathExpr) -> Option<ast::RecordExprField> {
454 let path = usage.path()?;
455 let name_ref = path.as_single_name_ref()?;
456 ast::RecordExprField::for_name_ref(&name_ref)
461 use crate::tests::{check_assist, check_assist_not_applicable};
466 fn no_args_or_return_value_gets_inlined_without_block() {
470 fn foo() { println!("Hello, World!"); }
476 fn foo() { println!("Hello, World!"); }
478 { println!("Hello, World!"); };
485 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
486 cov_mark::check!(inline_call_incorrect_number_of_arguments);
487 check_assist_not_applicable(
490 fn add(a: u32, b: u32) -> u32 { a + b }
491 fn main() { let x = add$0(42); }
497 fn args_with_side_effects() {
501 fn foo(name: String) {
502 println!("Hello, {}!", name);
505 foo$0(String::from("Michael"));
509 fn foo(name: String) {
510 println!("Hello, {}!", name);
514 let name = String::from("Michael");
515 println!("Hello, {}!", name);
523 fn function_with_multiple_statements() {
527 fn foo(a: u32, b: u32) -> u32 {
538 fn foo(a: u32, b: u32) -> u32 {
557 fn function_with_self_param() {
564 fn add(self, a: u32) -> Self {
570 let x = Foo::add$0(Foo(3), 2);
577 fn add(self, a: u32) -> Self {
600 fn add(self, a: u32) -> Self {
606 let x = Foo(3).add$0(2);
613 fn add(self, a: u32) -> Self {
636 fn add(&self, a: u32) -> Self {
642 let x = Foo(3).add$0(2);
649 fn add(&self, a: u32) -> Self {
656 let ref this = Foo(3);
665 fn method_by_ref_mut() {
672 fn clear(&mut self) {
678 let mut foo = Foo(3);
686 fn clear(&mut self) {
692 let mut foo = Foo(3);
694 let ref mut this = foo;
703 fn function_multi_use_expr_in_param() {
707 fn square(x: u32) -> u32 {
712 let y = square$0(10 + x);
716 fn square(x: u32) -> u32 {
731 fn function_use_local_in_param() {
732 cov_mark::check!(inline_call_inline_locals);
736 fn square(x: u32) -> u32 {
741 let y = square$0(local);
745 fn square(x: u32) -> u32 {
750 let y = local * local;
757 fn method_in_impl() {
792 fn wraps_closure_in_paren() {
793 cov_mark::check!(inline_call_inline_closure);
843 fn inline_single_literal_expr() {
844 cov_mark::check!(inline_call_inline_literal);
848 fn foo(x: u32) -> u32{
857 fn foo(x: u32) -> u32{
869 fn inline_emits_type_for_coercion() {
873 fn foo(x: *const u32) -> u32 {
882 fn foo(x: *const u32) -> u32 {
888 let x: *const u32 = &222;
896 // FIXME: const generics aren't being substituted, this is blocked on better support for them
898 fn inline_substitutes_generics() {
902 fn foo<T, const N: usize>() {
906 fn bar<U, const M: usize>() {}
909 foo$0::<usize, {0}>();
913 fn foo<T, const N: usize>() {
917 fn bar<U, const M: usize>() {}
927 fn inline_callers() {
931 fn do_the_math$0(b: u32) -> u32 {
959 fn inline_callers_across_files() {
965 fn do_the_math$0(b: u32) -> u32 {
970 use super::do_the_math;
998 fn inline_callers_across_files_with_def_file() {
1000 inline_into_callers,
1004 fn do_the_math$0(b: u32) -> u32 {
1008 fn bar(a: u32, b: u32) -> u32 {
1012 use super::do_the_math;
1021 fn bar(a: u32, b: u32) -> u32 {
1039 fn inline_callers_recursive() {
1040 cov_mark::check!(inline_into_callers_recursive);
1041 check_assist_not_applicable(
1042 inline_into_callers,
1052 fn inline_call_recursive() {
1053 cov_mark::check!(inline_call_recursive);
1054 check_assist_not_applicable(
1065 fn inline_call_field_shorthand() {
1066 cov_mark::check!(inline_call_inline_direct_field);
1076 fn foo(field: u32, field1: u32, val2: u32, val3: u32) -> Foo {
1087 foo$0(bar, 0, baz, 0);
1097 fn foo(field: u32, field1: u32, val2: u32, val3: u32) -> Foo {
1120 fn inline_callers_wrapped_in_parentheses() {
1122 inline_into_callers,
1148 fn inline_call_wrapped_in_parentheses() {
1176 fn inline_call_defined_in_macro() {
1177 cov_mark::check!(inline_call_defined_in_macro);
1181 macro_rules! define_foo {
1182 () => { fn foo() -> u32 {
1193 macro_rules! define_foo {
1194 () => { fn foo() -> u32 {
1211 fn inline_call_with_self_type() {
1217 fn f() -> Self { Self(114514) }
1226 fn f() -> Self { Self(114514) }
1236 fn inline_call_with_self_type_but_within_same_impl() {
1242 fn f() -> Self { Self(1919810) }
1251 fn f() -> Self { Self(1919810) }