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(),
89 assoc_fn_params.next()?,
92 for param in param_list.params() {
93 params.push((param.pat()?, param.ty(), assoc_fn_params.next()?));
96 if arg_list.len() != params.len() {
97 // Can't inline the function because they've passed the wrong number of
98 // arguments to this function
99 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
103 let body = function_source.body()?;
106 AssistId("inline_call", AssistKind::RefactorInline),
108 expr.syntax().text_range(),
110 let body = body.clone_for_update();
112 let file_id = file_id.original_file(ctx.sema.db);
113 let usages_for_locals = |local| {
114 Definition::Local(local)
122 // Contains the nodes of usages of parameters.
123 // If the inner Vec for a parameter is empty it either means there are no usages or that the parameter
124 // has a pattern that does not allow inlining
125 let param_use_nodes: Vec<Vec<_>> = params
127 .map(|(pat, _, param)| {
128 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
131 usages_for_locals(param.as_local(ctx.sema.db))
132 .map(|FileReference { name, range, .. }| match name {
133 ast::NameLike::NameRef(_) => body
135 .covering_element(range)
138 .and_then(ast::PathExpr::cast),
141 .collect::<Option<Vec<_>>>()
146 // Rewrite `self` to `this`
147 if param_list.self_param().is_some() {
148 let this = || make::name_ref("this").syntax().clone_for_update();
149 usages_for_locals(params[0].2.as_local(ctx.sema.db))
150 .flat_map(|FileReference { name, range, .. }| match name {
151 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
155 ted::replace(it, &this());
159 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
160 for ((pat, param_ty, _), usages, expr) in izip!(params, param_use_nodes, arg_list).rev()
162 let expr_is_name_ref = matches!(&expr,
163 ast::Expr::PathExpr(expr)
164 if expr.path().and_then(|path| path.as_single_name_ref()).is_some()
167 // inline single use closure arguments
169 if matches!(expr, ast::Expr::ClosureExpr(_))
170 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
172 cov_mark::hit!(inline_call_inline_closure);
173 let expr = make::expr_paren(expr);
174 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
176 // inline single use literals
177 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
178 cov_mark::hit!(inline_call_inline_literal);
179 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
181 // inline direct local arguments
182 [_, ..] if expr_is_name_ref => {
183 cov_mark::hit!(inline_call_inline_locals);
184 usages.into_iter().for_each(|usage| {
185 ted::replace(usage.syntax(), &expr.syntax().clone_for_update());
188 // cant inline, emit a let statement
192 .type_of_expr_with_coercion(&expr)
193 .map_or(false, |(_, coerced)| coerced)
197 make::let_stmt(pat, ty, Some(expr)).clone_for_update().into(),
203 let original_indentation = expr.indent_level();
204 let replacement = body.reset_indent().indent(original_indentation);
206 let replacement = match replacement.tail_expr() {
207 Some(expr) if replacement.statements().next().is_none() => expr,
208 _ => ast::Expr::BlockExpr(replacement),
210 builder.replace_ast(expr, replacement);
217 use crate::tests::{check_assist, check_assist_not_applicable};
222 fn no_args_or_return_value_gets_inlined_without_block() {
226 fn foo() { println!("Hello, World!"); }
232 fn foo() { println!("Hello, World!"); }
234 { println!("Hello, World!"); };
241 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
242 cov_mark::check!(inline_call_incorrect_number_of_arguments);
243 check_assist_not_applicable(
246 fn add(a: u32, b: u32) -> u32 { a + b }
247 fn main() { let x = add$0(42); }
253 fn args_with_side_effects() {
257 fn foo(name: String) {
258 println!("Hello, {}!", name);
261 foo$0(String::from("Michael"));
265 fn foo(name: String) {
266 println!("Hello, {}!", name);
270 let name = String::from("Michael");
271 println!("Hello, {}!", name);
279 fn function_with_multiple_statements() {
283 fn foo(a: u32, b: u32) -> u32 {
294 fn foo(a: u32, b: u32) -> u32 {
313 fn function_with_self_param() {
320 fn add(self, a: u32) -> Self {
326 let x = Foo::add$0(Foo(3), 2);
333 fn add(self, a: u32) -> Self {
356 fn add(self, a: u32) -> Self {
362 let x = Foo(3).add$0(2);
369 fn add(self, a: u32) -> Self {
392 fn add(&self, a: u32) -> Self {
398 let x = Foo(3).add$0(2);
405 fn add(&self, a: u32) -> Self {
412 let ref this = Foo(3);
421 fn method_by_ref_mut() {
428 fn clear(&mut self) {
434 let mut foo = Foo(3);
442 fn clear(&mut self) {
448 let mut foo = Foo(3);
450 let ref mut this = foo;
459 fn function_multi_use_expr_in_param() {
463 fn square(x: u32) -> u32 {
468 let y = square$0(10 + x);
472 fn square(x: u32) -> u32 {
487 fn function_use_local_in_param() {
488 cov_mark::check!(inline_call_inline_locals);
492 fn square(x: u32) -> u32 {
497 let y = square$0(local);
501 fn square(x: u32) -> u32 {
506 let y = local * local;
513 fn method_in_impl() {
548 fn wraps_closure_in_paren() {
549 cov_mark::check!(inline_call_inline_closure);
599 fn inline_single_literal_expr() {
600 cov_mark::check!(inline_call_inline_literal);
604 fn foo(x: u32) -> u32{
613 fn foo(x: u32) -> u32{
625 fn inline_emits_type_for_coercion() {
629 fn foo(x: *const u32) -> u32 {
638 fn foo(x: *const u32) -> u32 {
644 let x: *const u32 = &222;