2 use hir::{HasSource, PathResolution};
3 use ide_db::{defs::Definition, search::FileReference};
6 ast::{self, edit::AstNodeEdit, ArgListOwner},
11 assist_context::{AssistContext, Assists},
15 // Assist: inline_call
17 // Inlines a function or method body creating a `let` statement per parameter unless the parameter
18 // can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
19 // or if the parameter is only accessed inside the function body once.
22 // # //- minicore: option
23 // fn foo(name: Option<&str>) {
24 // let name = name.unwrap$0();
29 // fn foo(name: Option<&str>) {
30 // let name = match name {
32 // None => panic!("called `Option::unwrap()` on a `None` value"),
36 pub(crate) fn inline_call(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
37 let (label, function, arguments, expr) =
38 if let Some(path_expr) = ctx.find_node_at_offset::<ast::PathExpr>() {
39 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
40 let path = path_expr.path()?;
42 let function = match ctx.sema.resolve_path(&path)? {
43 PathResolution::Def(hir::ModuleDef::Function(f))
44 | PathResolution::AssocItem(hir::AssocItem::Function(f)) => f,
48 format!("Inline `{}`", path),
50 call.arg_list()?.args().collect(),
51 ast::Expr::CallExpr(call),
54 let name_ref: ast::NameRef = ctx.find_node_at_offset()?;
55 let call = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
56 let receiver = call.receiver()?;
57 let function = ctx.sema.resolve_method_call(&call)?;
58 let mut arguments = vec![receiver];
59 arguments.extend(call.arg_list()?.args());
60 (format!("Inline `{}`", name_ref), function, arguments, ast::Expr::MethodCallExpr(call))
63 inline_(acc, ctx, label, function, arguments, expr)
66 pub(crate) fn inline_(
70 function: hir::Function,
71 arg_list: Vec<ast::Expr>,
74 let hir::InFile { value: function_source, file_id } = function.source(ctx.db())?;
75 let param_list = function_source.param_list()?;
76 let mut assoc_fn_params = function.assoc_fn_params(ctx.sema.db).into_iter();
78 let mut params = Vec::new();
79 if let Some(self_param) = param_list.self_param() {
80 // FIXME this should depend on the receiver as well as the self_param
83 self_param.amp_token().is_some(),
84 self_param.mut_token().is_some(),
88 assoc_fn_params.next()?,
91 for param in param_list.params() {
92 params.push((param.pat()?, assoc_fn_params.next()?));
95 if arg_list.len() != params.len() {
96 // Can't inline the function because they've passed the wrong number of
97 // arguments to this function
98 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
102 let body = function_source.body()?;
105 AssistId("inline_call", AssistKind::RefactorInline),
107 expr.syntax().text_range(),
109 let body = body.clone_for_update();
111 let file_id = file_id.original_file(ctx.sema.db);
112 let usages_for_locals = |local| {
113 Definition::Local(local)
121 // Contains the nodes of usages of parameters.
122 // If the inner Vec for a parameter is empty it either means there are no usages or that the parameter
123 // has a pattern that does not allow inlining
124 let param_use_nodes: Vec<Vec<_>> = params
126 .map(|(pat, param)| {
127 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
130 usages_for_locals(param.as_local(ctx.sema.db))
131 .map(|FileReference { name, range, .. }| match name {
132 ast::NameLike::NameRef(_) => body
134 .covering_element(range)
137 .and_then(ast::PathExpr::cast),
140 .collect::<Option<Vec<_>>>()
145 // Rewrite `self` to `this`
146 if param_list.self_param().is_some() {
147 let this = || make::name_ref("this").syntax().clone_for_update();
148 usages_for_locals(params[0].1.as_local(ctx.sema.db))
149 .flat_map(|FileReference { name, range, .. }| match name {
150 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
154 ted::replace(it, &this());
158 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
159 for ((pat, _), usages, expr) in izip!(params, param_use_nodes, arg_list).rev() {
160 let expr_is_name_ref = matches!(&expr,
161 ast::Expr::PathExpr(expr)
162 if expr.path().and_then(|path| path.as_single_name_ref()).is_some()
165 // inline single use closure arguments
167 if matches!(expr, ast::Expr::ClosureExpr(_))
168 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
170 cov_mark::hit!(inline_call_inline_closure);
171 let expr = make::expr_paren(expr);
172 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
174 // inline single use literals
175 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
176 cov_mark::hit!(inline_call_inline_literal);
177 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
179 // inline direct local arguments
180 [_, ..] if expr_is_name_ref => {
181 cov_mark::hit!(inline_call_inline_locals);
182 usages.into_iter().for_each(|usage| {
183 ted::replace(usage.syntax(), &expr.syntax().clone_for_update());
186 // cant inline, emit a let statement
187 // FIXME: emit type ascriptions when a coercion happens?
188 _ => body.push_front(make::let_stmt(pat, Some(expr)).clone_for_update().into()),
192 let original_indentation = expr.indent_level();
193 let replacement = body.reset_indent().indent(original_indentation);
195 let replacement = match replacement.tail_expr() {
196 Some(expr) if replacement.statements().next().is_none() => expr,
197 _ => ast::Expr::BlockExpr(replacement),
199 builder.replace_ast(expr, replacement);
206 use crate::tests::{check_assist, check_assist_not_applicable};
211 fn no_args_or_return_value_gets_inlined_without_block() {
215 fn foo() { println!("Hello, World!"); }
221 fn foo() { println!("Hello, World!"); }
223 { println!("Hello, World!"); };
230 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
231 cov_mark::check!(inline_call_incorrect_number_of_arguments);
232 check_assist_not_applicable(
235 fn add(a: u32, b: u32) -> u32 { a + b }
236 fn main() { let x = add$0(42); }
242 fn args_with_side_effects() {
246 fn foo(name: String) {
247 println!("Hello, {}!", name);
250 foo$0(String::from("Michael"));
254 fn foo(name: String) {
255 println!("Hello, {}!", name);
259 let name = String::from("Michael");
260 println!("Hello, {}!", name);
268 fn function_with_multiple_statements() {
272 fn foo(a: u32, b: u32) -> u32 {
283 fn foo(a: u32, b: u32) -> u32 {
302 fn function_with_self_param() {
309 fn add(self, a: u32) -> Self {
315 let x = Foo::add$0(Foo(3), 2);
322 fn add(self, a: u32) -> Self {
345 fn add(self, a: u32) -> Self {
351 let x = Foo(3).add$0(2);
358 fn add(self, a: u32) -> Self {
381 fn add(&self, a: u32) -> Self {
387 let x = Foo(3).add$0(2);
394 fn add(&self, a: u32) -> Self {
401 let ref this = Foo(3);
410 fn method_by_ref_mut() {
417 fn clear(&mut self) {
423 let mut foo = Foo(3);
431 fn clear(&mut self) {
437 let mut foo = Foo(3);
439 let ref mut this = foo;
448 fn function_multi_use_expr_in_param() {
452 fn square(x: u32) -> u32 {
457 let y = square$0(10 + x);
461 fn square(x: u32) -> u32 {
476 fn function_use_local_in_param() {
477 cov_mark::check!(inline_call_inline_locals);
481 fn square(x: u32) -> u32 {
486 let y = square$0(local);
490 fn square(x: u32) -> u32 {
495 let y = local * local;
502 fn method_in_impl() {
537 fn wraps_closure_in_paren() {
538 cov_mark::check!(inline_call_inline_closure);
588 fn inline_single_literal_expr() {
589 cov_mark::check!(inline_call_inline_literal);
593 fn foo(x: u32) -> u32{
602 fn foo(x: u32) -> u32{