]> git.lizzy.rs Git - rust.git/blob - crates/ide-assists/src/utils.rs
Auto merge of #13379 - DropDemBits:ide-assists-format-args-capture, r=Veykril
[rust.git] / crates / ide-assists / src / utils.rs
1 //! Assorted functions shared by several assists.
2
3 use std::ops;
4
5 pub(crate) use gen_trait_fn_body::gen_trait_fn_body;
6 use hir::{db::HirDatabase, HirDisplay, Semantics};
7 use ide_db::{famous_defs::FamousDefs, path_transform::PathTransform, RootDatabase, SnippetCap};
8 use stdx::format_to;
9 use syntax::{
10     ast::{
11         self,
12         edit::{self, AstNodeEdit},
13         edit_in_place::{AttrsOwnerEdit, Removable},
14         make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
15     },
16     ted, AstNode, AstToken, Direction, SourceFile,
17     SyntaxKind::*,
18     SyntaxNode, TextRange, TextSize, T,
19 };
20
21 use crate::assist_context::{AssistContext, SourceChangeBuilder};
22
23 pub(crate) mod suggest_name;
24 mod gen_trait_fn_body;
25
26 pub(crate) fn unwrap_trivial_block(block_expr: ast::BlockExpr) -> ast::Expr {
27     extract_trivial_expression(&block_expr)
28         .filter(|expr| !expr.syntax().text().contains_char('\n'))
29         .unwrap_or_else(|| block_expr.into())
30 }
31
32 pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
33     if block_expr.modifier().is_some() {
34         return None;
35     }
36     let stmt_list = block_expr.stmt_list()?;
37     let has_anything_else = |thing: &SyntaxNode| -> bool {
38         let mut non_trivial_children =
39             stmt_list.syntax().children_with_tokens().filter(|it| match it.kind() {
40                 WHITESPACE | T!['{'] | T!['}'] => false,
41                 _ => it.as_node() != Some(thing),
42             });
43         non_trivial_children.next().is_some()
44     };
45
46     if let Some(expr) = stmt_list.tail_expr() {
47         if has_anything_else(expr.syntax()) {
48             return None;
49         }
50         return Some(expr);
51     }
52     // Unwrap `{ continue; }`
53     let stmt = stmt_list.statements().next()?;
54     if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
55         if has_anything_else(expr_stmt.syntax()) {
56             return None;
57         }
58         let expr = expr_stmt.expr()?;
59         if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
60             return Some(expr);
61         }
62     }
63     None
64 }
65
66 /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as
67 /// `#[test_case(...)]`, `#[tokio::test]` and similar.
68 /// Also a regular `#[test]` annotation is supported.
69 ///
70 /// It may produce false positives, for example, `#[wasm_bindgen_test]` requires a different command to run the test,
71 /// but it's better than not to have the runnables for the tests at all.
72 pub fn test_related_attribute(fn_def: &ast::Fn) -> Option<ast::Attr> {
73     fn_def.attrs().find_map(|attr| {
74         let path = attr.path()?;
75         let text = path.syntax().text().to_string();
76         if text.starts_with("test") || text.ends_with("test") {
77             Some(attr)
78         } else {
79             None
80         }
81     })
82 }
83
84 #[derive(Copy, Clone, PartialEq)]
85 pub enum DefaultMethods {
86     Only,
87     No,
88 }
89
90 pub fn filter_assoc_items(
91     sema: &Semantics<'_, RootDatabase>,
92     items: &[hir::AssocItem],
93     default_methods: DefaultMethods,
94 ) -> Vec<ast::AssocItem> {
95     fn has_def_name(item: &ast::AssocItem) -> bool {
96         match item {
97             ast::AssocItem::Fn(def) => def.name(),
98             ast::AssocItem::TypeAlias(def) => def.name(),
99             ast::AssocItem::Const(def) => def.name(),
100             ast::AssocItem::MacroCall(_) => None,
101         }
102         .is_some()
103     }
104
105     items
106         .iter()
107         // Note: This throws away items with no source.
108         .filter_map(|&i| {
109             let item = match i {
110                 hir::AssocItem::Function(i) => ast::AssocItem::Fn(sema.source(i)?.value),
111                 hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(sema.source(i)?.value),
112                 hir::AssocItem::Const(i) => ast::AssocItem::Const(sema.source(i)?.value),
113             };
114             Some(item)
115         })
116         .filter(has_def_name)
117         .filter(|it| match it {
118             ast::AssocItem::Fn(def) => matches!(
119                 (default_methods, def.body()),
120                 (DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None)
121             ),
122             _ => default_methods == DefaultMethods::No,
123         })
124         .collect::<Vec<_>>()
125 }
126
127 pub fn add_trait_assoc_items_to_impl(
128     sema: &Semantics<'_, RootDatabase>,
129     items: Vec<ast::AssocItem>,
130     trait_: hir::Trait,
131     impl_: ast::Impl,
132     target_scope: hir::SemanticsScope<'_>,
133 ) -> (ast::Impl, ast::AssocItem) {
134     let source_scope = sema.scope_for_def(trait_);
135
136     let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
137
138     let items = items.into_iter().map(|assoc_item| {
139         transform.apply(assoc_item.syntax());
140         assoc_item.remove_attrs_and_docs();
141         assoc_item
142     });
143
144     let res = impl_.clone_for_update();
145
146     let assoc_item_list = res.get_or_create_assoc_item_list();
147     let mut first_item = None;
148     for item in items {
149         first_item.get_or_insert_with(|| item.clone());
150         match &item {
151             ast::AssocItem::Fn(fn_) if fn_.body().is_none() => {
152                 let body = make::block_expr(None, Some(make::ext::expr_todo()))
153                     .indent(edit::IndentLevel(1));
154                 ted::replace(fn_.get_or_create_body().syntax(), body.clone_for_update().syntax())
155             }
156             ast::AssocItem::TypeAlias(type_alias) => {
157                 if let Some(type_bound_list) = type_alias.type_bound_list() {
158                     type_bound_list.remove()
159                 }
160             }
161             _ => {}
162         }
163
164         assoc_item_list.add_item(item)
165     }
166
167     (res, first_item.unwrap())
168 }
169
170 #[derive(Clone, Copy, Debug)]
171 pub(crate) enum Cursor<'a> {
172     Replace(&'a SyntaxNode),
173     Before(&'a SyntaxNode),
174 }
175
176 impl<'a> Cursor<'a> {
177     fn node(self) -> &'a SyntaxNode {
178         match self {
179             Cursor::Replace(node) | Cursor::Before(node) => node,
180         }
181     }
182 }
183
184 pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor<'_>) -> String {
185     assert!(cursor.node().ancestors().any(|it| it == *node));
186     let range = cursor.node().text_range() - node.text_range().start();
187     let range: ops::Range<usize> = range.into();
188
189     let mut placeholder = cursor.node().to_string();
190     escape(&mut placeholder);
191     let tab_stop = match cursor {
192         Cursor::Replace(placeholder) => format!("${{0:{placeholder}}}"),
193         Cursor::Before(placeholder) => format!("$0{placeholder}"),
194     };
195
196     let mut buf = node.to_string();
197     buf.replace_range(range, &tab_stop);
198     return buf;
199
200     fn escape(buf: &mut String) {
201         stdx::replace(buf, '{', r"\{");
202         stdx::replace(buf, '}', r"\}");
203         stdx::replace(buf, '$', r"\$");
204     }
205 }
206
207 pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize {
208     node.children_with_tokens()
209         .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR))
210         .map(|it| it.text_range().start())
211         .unwrap_or_else(|| node.text_range().start())
212 }
213
214 pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr {
215     invert_special_case(&expr).unwrap_or_else(|| make::expr_prefix(T![!], expr))
216 }
217
218 fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
219     match expr {
220         ast::Expr::BinExpr(bin) => {
221             let bin = bin.clone_for_update();
222             let op_token = bin.op_token()?;
223             let rev_token = match op_token.kind() {
224                 T![==] => T![!=],
225                 T![!=] => T![==],
226                 T![<] => T![>=],
227                 T![<=] => T![>],
228                 T![>] => T![<=],
229                 T![>=] => T![<],
230                 // Parenthesize other expressions before prefixing `!`
231                 _ => return Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
232             };
233             ted::replace(op_token, make::token(rev_token));
234             Some(bin.into())
235         }
236         ast::Expr::MethodCallExpr(mce) => {
237             let receiver = mce.receiver()?;
238             let method = mce.name_ref()?;
239             let arg_list = mce.arg_list()?;
240
241             let method = match method.text().as_str() {
242                 "is_some" => "is_none",
243                 "is_none" => "is_some",
244                 "is_ok" => "is_err",
245                 "is_err" => "is_ok",
246                 _ => return None,
247             };
248             Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
249         }
250         ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
251             ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
252             _ => pe.expr(),
253         },
254         ast::Expr::Literal(lit) => match lit.kind() {
255             ast::LiteralKind::Bool(b) => match b {
256                 true => Some(ast::Expr::Literal(make::expr_literal("false"))),
257                 false => Some(ast::Expr::Literal(make::expr_literal("true"))),
258             },
259             _ => None,
260         },
261         _ => None,
262     }
263 }
264
265 pub(crate) fn next_prev() -> impl Iterator<Item = Direction> {
266     [Direction::Next, Direction::Prev].into_iter()
267 }
268
269 pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool {
270     let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text());
271
272     let pat_head = match pat {
273         ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
274             Some(p) => first_node_text(&p),
275             None => return pat.syntax().text() == var.syntax().text(),
276         },
277         pat => first_node_text(pat),
278     };
279
280     let var_head = first_node_text(var);
281
282     pat_head == var_head
283 }
284
285 pub(crate) fn does_nested_pattern(pat: &ast::Pat) -> bool {
286     let depth = calc_depth(pat, 0);
287
288     if 1 < depth {
289         return true;
290     }
291     false
292 }
293
294 fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
295     match pat {
296         ast::Pat::IdentPat(_)
297         | ast::Pat::BoxPat(_)
298         | ast::Pat::RestPat(_)
299         | ast::Pat::LiteralPat(_)
300         | ast::Pat::MacroPat(_)
301         | ast::Pat::OrPat(_)
302         | ast::Pat::ParenPat(_)
303         | ast::Pat::PathPat(_)
304         | ast::Pat::WildcardPat(_)
305         | ast::Pat::RangePat(_)
306         | ast::Pat::RecordPat(_)
307         | ast::Pat::RefPat(_)
308         | ast::Pat::SlicePat(_)
309         | ast::Pat::TuplePat(_)
310         | ast::Pat::ConstBlockPat(_) => depth,
311
312         // FIXME: Other patterns may also be nested. Currently it simply supports only `TupleStructPat`
313         ast::Pat::TupleStructPat(pat) => {
314             let mut max_depth = depth;
315             for p in pat.fields() {
316                 let d = calc_depth(&p, depth + 1);
317                 if d > max_depth {
318                     max_depth = d
319                 }
320             }
321             max_depth
322         }
323     }
324 }
325
326 // Uses a syntax-driven approach to find any impl blocks for the struct that
327 // exist within the module/file
328 //
329 // Returns `None` if we've found an existing fn
330 //
331 // FIXME: change the new fn checking to a more semantic approach when that's more
332 // viable (e.g. we process proc macros, etc)
333 // FIXME: this partially overlaps with `find_impl_block_*`
334
335 /// `find_struct_impl` looks for impl of a struct, but this also has additional feature
336 /// where it takes a list of function names and check if they exist inside impl_, if
337 /// even one match is found, it returns None
338 pub(crate) fn find_struct_impl(
339     ctx: &AssistContext<'_>,
340     adt: &ast::Adt,
341     names: &[String],
342 ) -> Option<Option<ast::Impl>> {
343     let db = ctx.db();
344     let module = adt.syntax().parent()?;
345
346     let struct_def = ctx.sema.to_def(adt)?;
347
348     let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
349         let blk = ctx.sema.to_def(&impl_blk)?;
350
351         // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
352         // (we currently use the wrong type parameter)
353         // also we wouldn't want to use e.g. `impl S<u32>`
354
355         let same_ty = match blk.self_ty(db).as_adt() {
356             Some(def) => def == struct_def,
357             None => false,
358         };
359         let not_trait_impl = blk.trait_(db).is_none();
360
361         if !(same_ty && not_trait_impl) {
362             None
363         } else {
364             Some(impl_blk)
365         }
366     });
367
368     if let Some(ref impl_blk) = block {
369         if has_any_fn(impl_blk, names) {
370             return None;
371         }
372     }
373
374     Some(block)
375 }
376
377 fn has_any_fn(imp: &ast::Impl, names: &[String]) -> bool {
378     if let Some(il) = imp.assoc_item_list() {
379         for item in il.assoc_items() {
380             if let ast::AssocItem::Fn(f) = item {
381                 if let Some(name) = f.name() {
382                     if names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) {
383                         return true;
384                     }
385                 }
386             }
387         }
388     }
389
390     false
391 }
392
393 /// Find the start of the `impl` block for the given `ast::Impl`.
394 //
395 // FIXME: this partially overlaps with `find_struct_impl`
396 pub(crate) fn find_impl_block_start(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
397     buf.push('\n');
398     let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end();
399     Some(start)
400 }
401
402 /// Find the end of the `impl` block for the given `ast::Impl`.
403 //
404 // FIXME: this partially overlaps with `find_struct_impl`
405 pub(crate) fn find_impl_block_end(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
406     buf.push('\n');
407     let end = impl_def
408         .assoc_item_list()
409         .and_then(|it| it.r_curly_token())?
410         .prev_sibling_or_token()?
411         .text_range()
412         .end();
413     Some(end)
414 }
415
416 // Generates the surrounding `impl Type { <code> }` including type and lifetime
417 // parameters
418 pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
419     generate_impl_text_inner(adt, None, code)
420 }
421
422 // Generates the surrounding `impl <trait> for Type { <code> }` including type
423 // and lifetime parameters
424 pub(crate) fn generate_trait_impl_text(adt: &ast::Adt, trait_text: &str, code: &str) -> String {
425     generate_impl_text_inner(adt, Some(trait_text), code)
426 }
427
428 fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str) -> String {
429     // Ensure lifetime params are before type & const params
430     let generic_params = adt.generic_param_list().map(|generic_params| {
431         let lifetime_params =
432             generic_params.lifetime_params().map(ast::GenericParam::LifetimeParam);
433         let ty_or_const_params = generic_params.type_or_const_params().filter_map(|param| {
434             // remove defaults since they can't be specified in impls
435             match param {
436                 ast::TypeOrConstParam::Type(param) => {
437                     let param = param.clone_for_update();
438                     param.remove_default();
439                     Some(ast::GenericParam::TypeParam(param))
440                 }
441                 ast::TypeOrConstParam::Const(param) => {
442                     let param = param.clone_for_update();
443                     param.remove_default();
444                     Some(ast::GenericParam::ConstParam(param))
445                 }
446             }
447         });
448
449         make::generic_param_list(itertools::chain(lifetime_params, ty_or_const_params))
450     });
451
452     // FIXME: use syntax::make & mutable AST apis instead
453     // `trait_text` and `code` can't be opaque blobs of text
454     let mut buf = String::with_capacity(code.len());
455
456     // Copy any cfg attrs from the original adt
457     buf.push_str("\n\n");
458     let cfg_attrs = adt
459         .attrs()
460         .filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false));
461     cfg_attrs.for_each(|attr| buf.push_str(&format!("{attr}\n")));
462
463     // `impl{generic_params} {trait_text} for {name}{generic_params.to_generic_args()}`
464     buf.push_str("impl");
465     if let Some(generic_params) = &generic_params {
466         format_to!(buf, "{generic_params}");
467     }
468     buf.push(' ');
469     if let Some(trait_text) = trait_text {
470         buf.push_str(trait_text);
471         buf.push_str(" for ");
472     }
473     buf.push_str(&adt.name().unwrap().text());
474     if let Some(generic_params) = generic_params {
475         format_to!(buf, "{}", generic_params.to_generic_args());
476     }
477
478     match adt.where_clause() {
479         Some(where_clause) => {
480             format_to!(buf, "\n{where_clause}\n{{\n{code}\n}}");
481         }
482         None => {
483             format_to!(buf, " {{\n{code}\n}}");
484         }
485     }
486
487     buf
488 }
489
490 pub(crate) fn add_method_to_adt(
491     builder: &mut SourceChangeBuilder,
492     adt: &ast::Adt,
493     impl_def: Option<ast::Impl>,
494     method: &str,
495 ) {
496     let mut buf = String::with_capacity(method.len() + 2);
497     if impl_def.is_some() {
498         buf.push('\n');
499     }
500     buf.push_str(method);
501
502     let start_offset = impl_def
503         .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
504         .unwrap_or_else(|| {
505             buf = generate_impl_text(adt, &buf);
506             adt.syntax().text_range().end()
507         });
508
509     builder.insert(start_offset, buf);
510 }
511
512 #[derive(Debug)]
513 pub(crate) struct ReferenceConversion {
514     conversion: ReferenceConversionType,
515     ty: hir::Type,
516 }
517
518 #[derive(Debug)]
519 enum ReferenceConversionType {
520     // reference can be stripped if the type is Copy
521     Copy,
522     // &String -> &str
523     AsRefStr,
524     // &Vec<T> -> &[T]
525     AsRefSlice,
526     // &Box<T> -> &T
527     Dereferenced,
528     // &Option<T> -> Option<&T>
529     Option,
530     // &Result<T, E> -> Result<&T, &E>
531     Result,
532 }
533
534 impl ReferenceConversion {
535     pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String {
536         match self.conversion {
537             ReferenceConversionType::Copy => self.ty.display(db).to_string(),
538             ReferenceConversionType::AsRefStr => "&str".to_string(),
539             ReferenceConversionType::AsRefSlice => {
540                 let type_argument_name =
541                     self.ty.type_arguments().next().unwrap().display(db).to_string();
542                 format!("&[{type_argument_name}]")
543             }
544             ReferenceConversionType::Dereferenced => {
545                 let type_argument_name =
546                     self.ty.type_arguments().next().unwrap().display(db).to_string();
547                 format!("&{type_argument_name}")
548             }
549             ReferenceConversionType::Option => {
550                 let type_argument_name =
551                     self.ty.type_arguments().next().unwrap().display(db).to_string();
552                 format!("Option<&{type_argument_name}>")
553             }
554             ReferenceConversionType::Result => {
555                 let mut type_arguments = self.ty.type_arguments();
556                 let first_type_argument_name =
557                     type_arguments.next().unwrap().display(db).to_string();
558                 let second_type_argument_name =
559                     type_arguments.next().unwrap().display(db).to_string();
560                 format!("Result<&{first_type_argument_name}, &{second_type_argument_name}>")
561             }
562         }
563     }
564
565     pub(crate) fn getter(&self, field_name: String) -> String {
566         match self.conversion {
567             ReferenceConversionType::Copy => format!("self.{field_name}"),
568             ReferenceConversionType::AsRefStr
569             | ReferenceConversionType::AsRefSlice
570             | ReferenceConversionType::Dereferenced
571             | ReferenceConversionType::Option
572             | ReferenceConversionType::Result => format!("self.{field_name}.as_ref()"),
573         }
574     }
575 }
576
577 // FIXME: It should return a new hir::Type, but currently constructing new types is too cumbersome
578 //        and all users of this function operate on string type names, so they can do the conversion
579 //        itself themselves.
580 pub(crate) fn convert_reference_type(
581     ty: hir::Type,
582     db: &RootDatabase,
583     famous_defs: &FamousDefs<'_, '_>,
584 ) -> Option<ReferenceConversion> {
585     handle_copy(&ty, db)
586         .or_else(|| handle_as_ref_str(&ty, db, famous_defs))
587         .or_else(|| handle_as_ref_slice(&ty, db, famous_defs))
588         .or_else(|| handle_dereferenced(&ty, db, famous_defs))
589         .or_else(|| handle_option_as_ref(&ty, db, famous_defs))
590         .or_else(|| handle_result_as_ref(&ty, db, famous_defs))
591         .map(|conversion| ReferenceConversion { ty, conversion })
592 }
593
594 fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
595     ty.is_copy(db).then(|| ReferenceConversionType::Copy)
596 }
597
598 fn handle_as_ref_str(
599     ty: &hir::Type,
600     db: &dyn HirDatabase,
601     famous_defs: &FamousDefs<'_, '_>,
602 ) -> Option<ReferenceConversionType> {
603     let str_type = hir::BuiltinType::str().ty(db);
604
605     ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[str_type])
606         .then(|| ReferenceConversionType::AsRefStr)
607 }
608
609 fn handle_as_ref_slice(
610     ty: &hir::Type,
611     db: &dyn HirDatabase,
612     famous_defs: &FamousDefs<'_, '_>,
613 ) -> Option<ReferenceConversionType> {
614     let type_argument = ty.type_arguments().next()?;
615     let slice_type = hir::Type::new_slice(type_argument);
616
617     ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[slice_type])
618         .then(|| ReferenceConversionType::AsRefSlice)
619 }
620
621 fn handle_dereferenced(
622     ty: &hir::Type,
623     db: &dyn HirDatabase,
624     famous_defs: &FamousDefs<'_, '_>,
625 ) -> Option<ReferenceConversionType> {
626     let type_argument = ty.type_arguments().next()?;
627
628     ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[type_argument])
629         .then(|| ReferenceConversionType::Dereferenced)
630 }
631
632 fn handle_option_as_ref(
633     ty: &hir::Type,
634     db: &dyn HirDatabase,
635     famous_defs: &FamousDefs<'_, '_>,
636 ) -> Option<ReferenceConversionType> {
637     if ty.as_adt() == famous_defs.core_option_Option()?.ty(db).as_adt() {
638         Some(ReferenceConversionType::Option)
639     } else {
640         None
641     }
642 }
643
644 fn handle_result_as_ref(
645     ty: &hir::Type,
646     db: &dyn HirDatabase,
647     famous_defs: &FamousDefs<'_, '_>,
648 ) -> Option<ReferenceConversionType> {
649     if ty.as_adt() == famous_defs.core_result_Result()?.ty(db).as_adt() {
650         Some(ReferenceConversionType::Result)
651     } else {
652         None
653     }
654 }
655
656 pub(crate) fn get_methods(items: &ast::AssocItemList) -> Vec<ast::Fn> {
657     items
658         .assoc_items()
659         .flat_map(|i| match i {
660             ast::AssocItem::Fn(f) => Some(f),
661             _ => None,
662         })
663         .filter(|f| f.name().is_some())
664         .collect()
665 }
666
667 /// Trim(remove leading and trailing whitespace) `initial_range` in `source_file`, return the trimmed range.
668 pub(crate) fn trimmed_text_range(source_file: &SourceFile, initial_range: TextRange) -> TextRange {
669     let mut trimmed_range = initial_range;
670     while source_file
671         .syntax()
672         .token_at_offset(trimmed_range.start())
673         .find_map(Whitespace::cast)
674         .is_some()
675         && trimmed_range.start() < trimmed_range.end()
676     {
677         let start = trimmed_range.start() + TextSize::from(1);
678         trimmed_range = TextRange::new(start, trimmed_range.end());
679     }
680     while source_file
681         .syntax()
682         .token_at_offset(trimmed_range.end())
683         .find_map(Whitespace::cast)
684         .is_some()
685         && trimmed_range.start() < trimmed_range.end()
686     {
687         let end = trimmed_range.end() - TextSize::from(1);
688         trimmed_range = TextRange::new(trimmed_range.start(), end);
689     }
690     trimmed_range
691 }
692
693 /// Convert a list of function params to a list of arguments that can be passed
694 /// into a function call.
695 pub(crate) fn convert_param_list_to_arg_list(list: ast::ParamList) -> ast::ArgList {
696     let mut args = vec![];
697     for param in list.params() {
698         if let Some(ast::Pat::IdentPat(pat)) = param.pat() {
699             if let Some(name) = pat.name() {
700                 let name = name.to_string();
701                 let expr = make::expr_path(make::ext::ident_path(&name));
702                 args.push(expr);
703             }
704         }
705     }
706     make::arg_list(args)
707 }