2 use hir::{HasSource, PathResolution, TypeInfo};
3 use ide_db::{defs::Definition, path_transform::PathTransform, 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, generic_arg_list, 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 path.segment().and_then(|it| it.generic_arg_list()),
52 ast::Expr::CallExpr(call),
55 let name_ref: ast::NameRef = ctx.find_node_at_offset()?;
56 let call = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
57 let receiver = call.receiver()?;
58 let function = ctx.sema.resolve_method_call(&call)?;
59 let mut arguments = vec![receiver];
60 arguments.extend(call.arg_list()?.args());
62 format!("Inline `{}`", name_ref),
65 call.generic_arg_list(),
66 ast::Expr::MethodCallExpr(call),
70 inline_(acc, ctx, label, function, arguments, expr, generic_arg_list)
73 pub(crate) fn inline_(
77 function: hir::Function,
78 arg_list: Vec<ast::Expr>,
80 generic_arg_list: Option<ast::GenericArgList>,
82 let hir::InFile { value: function_source, file_id } = function.source(ctx.db())?;
83 let param_list = function_source.param_list()?;
84 let mut assoc_fn_params = function.assoc_fn_params(ctx.sema.db).into_iter();
86 let mut params = Vec::new();
87 if let Some(self_param) = param_list.self_param() {
88 // FIXME this should depend on the receiver as well as the self_param
91 self_param.amp_token().is_some(),
92 self_param.mut_token().is_some(),
97 assoc_fn_params.next()?,
100 for param in param_list.params() {
101 params.push((param.pat()?, param.ty(), assoc_fn_params.next()?));
104 if arg_list.len() != params.len() {
105 // Can't inline the function because they've passed the wrong number of
106 // arguments to this function
107 cov_mark::hit!(inline_call_incorrect_number_of_arguments);
111 let fn_body = function_source.body()?;
114 AssistId("inline_call", AssistKind::RefactorInline),
116 expr.syntax().text_range(),
118 let body = fn_body.clone_for_update();
120 let file_id = file_id.original_file(ctx.sema.db);
121 let usages_for_locals = |local| {
122 Definition::Local(local)
130 // Contains the nodes of usages of parameters.
131 // If the inner Vec for a parameter is empty it either means there are no usages or that the parameter
132 // has a pattern that does not allow inlining
133 let param_use_nodes: Vec<Vec<_>> = params
135 .map(|(pat, _, param)| {
136 if !matches!(pat, ast::Pat::IdentPat(pat) if pat.is_simple_ident()) {
139 usages_for_locals(param.as_local(ctx.sema.db))
140 .map(|FileReference { name, range, .. }| match name {
141 ast::NameLike::NameRef(_) => body
143 .covering_element(range)
146 .and_then(ast::PathExpr::cast),
149 .collect::<Option<Vec<_>>>()
154 // Rewrite `self` to `this`
155 if param_list.self_param().is_some() {
156 let this = || make::name_ref("this").syntax().clone_for_update();
157 usages_for_locals(params[0].2.as_local(ctx.sema.db))
158 .flat_map(|FileReference { name, range, .. }| match name {
159 ast::NameLike::NameRef(_) => Some(body.syntax().covering_element(range)),
163 ted::replace(it, &this());
167 // Inline parameter expressions or generate `let` statements depending on whether inlining works or not.
168 for ((pat, param_ty, _), usages, expr) in izip!(params, param_use_nodes, arg_list).rev()
170 let expr_is_name_ref = matches!(&expr,
171 ast::Expr::PathExpr(expr)
172 if expr.path().and_then(|path| path.as_single_name_ref()).is_some()
175 // inline single use closure arguments
177 if matches!(expr, ast::Expr::ClosureExpr(_))
178 && usage.syntax().parent().and_then(ast::Expr::cast).is_some() =>
180 cov_mark::hit!(inline_call_inline_closure);
181 let expr = make::expr_paren(expr);
182 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
184 // inline single use literals
185 [usage] if matches!(expr, ast::Expr::Literal(_)) => {
186 cov_mark::hit!(inline_call_inline_literal);
187 ted::replace(usage.syntax(), expr.syntax().clone_for_update());
189 // inline direct local arguments
190 [_, ..] if expr_is_name_ref => {
191 cov_mark::hit!(inline_call_inline_locals);
192 usages.into_iter().for_each(|usage| {
193 ted::replace(usage.syntax(), &expr.syntax().clone_for_update());
196 // cant inline, emit a let statement
201 .filter(TypeInfo::has_adjustment)
202 .and_then(|_| param_ty);
204 make::let_stmt(pat, ty, Some(expr)).clone_for_update().into(),
209 if let Some(generic_arg_list) = generic_arg_list {
210 PathTransform::function_call(
211 &ctx.sema.scope(expr.syntax()),
212 &ctx.sema.scope(fn_body.syntax()),
216 .apply(body.syntax());
219 let original_indentation = expr.indent_level();
220 let replacement = body.reset_indent().indent(original_indentation);
222 let replacement = match replacement.tail_expr() {
223 Some(expr) if replacement.statements().next().is_none() => expr,
224 _ => ast::Expr::BlockExpr(replacement),
226 builder.replace_ast(expr, replacement);
233 use crate::tests::{check_assist, check_assist_not_applicable};
238 fn no_args_or_return_value_gets_inlined_without_block() {
242 fn foo() { println!("Hello, World!"); }
248 fn foo() { println!("Hello, World!"); }
250 { println!("Hello, World!"); };
257 fn not_applicable_when_incorrect_number_of_parameters_are_provided() {
258 cov_mark::check!(inline_call_incorrect_number_of_arguments);
259 check_assist_not_applicable(
262 fn add(a: u32, b: u32) -> u32 { a + b }
263 fn main() { let x = add$0(42); }
269 fn args_with_side_effects() {
273 fn foo(name: String) {
274 println!("Hello, {}!", name);
277 foo$0(String::from("Michael"));
281 fn foo(name: String) {
282 println!("Hello, {}!", name);
286 let name = String::from("Michael");
287 println!("Hello, {}!", name);
295 fn function_with_multiple_statements() {
299 fn foo(a: u32, b: u32) -> u32 {
310 fn foo(a: u32, b: u32) -> u32 {
329 fn function_with_self_param() {
336 fn add(self, a: u32) -> Self {
342 let x = Foo::add$0(Foo(3), 2);
349 fn add(self, a: u32) -> Self {
372 fn add(self, a: u32) -> Self {
378 let x = Foo(3).add$0(2);
385 fn add(self, a: u32) -> Self {
408 fn add(&self, a: u32) -> Self {
414 let x = Foo(3).add$0(2);
421 fn add(&self, a: u32) -> Self {
428 let ref this = Foo(3);
437 fn method_by_ref_mut() {
444 fn clear(&mut self) {
450 let mut foo = Foo(3);
458 fn clear(&mut self) {
464 let mut foo = Foo(3);
466 let ref mut this = foo;
475 fn function_multi_use_expr_in_param() {
479 fn square(x: u32) -> u32 {
484 let y = square$0(10 + x);
488 fn square(x: u32) -> u32 {
503 fn function_use_local_in_param() {
504 cov_mark::check!(inline_call_inline_locals);
508 fn square(x: u32) -> u32 {
513 let y = square$0(local);
517 fn square(x: u32) -> u32 {
522 let y = local * local;
529 fn method_in_impl() {
564 fn wraps_closure_in_paren() {
565 cov_mark::check!(inline_call_inline_closure);
615 fn inline_single_literal_expr() {
616 cov_mark::check!(inline_call_inline_literal);
620 fn foo(x: u32) -> u32{
629 fn foo(x: u32) -> u32{
641 fn inline_emits_type_for_coercion() {
645 fn foo(x: *const u32) -> u32 {
654 fn foo(x: *const u32) -> u32 {
660 let x: *const u32 = &222;
668 // FIXME: const generics aren't being substituted, this is blocked on better support for them
670 fn inline_substitutes_generics() {
674 fn foo<T, const N: usize>() {
678 fn bar<U, const M: usize>() {}
681 foo::<usize, {0}>$0();
685 fn foo<T, const N: usize>() {
689 fn bar<U, const M: usize>() {}