]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/utils.rs
90ec710c8e939f7c0ae4a15f194a719b8e275bf5
[rust.git] / crates / ide_assists / src / utils.rs
1 //! Assorted functions shared by several assists.
2
3 use std::ops;
4
5 use itertools::Itertools;
6
7 pub(crate) use gen_trait_fn_body::gen_trait_fn_body;
8 use hir::{db::HirDatabase, HirDisplay, Semantics};
9 use ide_db::{
10     helpers::FamousDefs, helpers::SnippetCap, path_transform::PathTransform, RootDatabase,
11 };
12 use stdx::format_to;
13 use syntax::{
14     ast::{
15         self,
16         edit::{self, AstNodeEdit},
17         edit_in_place::AttrsOwnerEdit,
18         make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
19     },
20     ted, AstNode, AstToken, Direction, SmolStr, SourceFile,
21     SyntaxKind::*,
22     SyntaxNode, TextRange, TextSize, T,
23 };
24
25 use crate::assist_context::{AssistBuilder, AssistContext};
26
27 pub(crate) mod suggest_name;
28 mod gen_trait_fn_body;
29
30 pub(crate) fn unwrap_trivial_block(block_expr: ast::BlockExpr) -> ast::Expr {
31     extract_trivial_expression(&block_expr)
32         .filter(|expr| !expr.syntax().text().contains_char('\n'))
33         .unwrap_or_else(|| block_expr.into())
34 }
35
36 pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
37     if block_expr.modifier().is_some() {
38         return None;
39     }
40     let stmt_list = block_expr.stmt_list()?;
41     let has_anything_else = |thing: &SyntaxNode| -> bool {
42         let mut non_trivial_children =
43             stmt_list.syntax().children_with_tokens().filter(|it| match it.kind() {
44                 WHITESPACE | T!['{'] | T!['}'] => false,
45                 _ => it.as_node() != Some(thing),
46             });
47         non_trivial_children.next().is_some()
48     };
49
50     if let Some(expr) = stmt_list.tail_expr() {
51         if has_anything_else(expr.syntax()) {
52             return None;
53         }
54         return Some(expr);
55     }
56     // Unwrap `{ continue; }`
57     let stmt = stmt_list.statements().next()?;
58     if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
59         if has_anything_else(expr_stmt.syntax()) {
60             return None;
61         }
62         let expr = expr_stmt.expr()?;
63         if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
64             return Some(expr);
65         }
66     }
67     None
68 }
69
70 /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as
71 /// `#[test_case(...)]`, `#[tokio::test]` and similar.
72 /// Also a regular `#[test]` annotation is supported.
73 ///
74 /// It may produce false positives, for example, `#[wasm_bindgen_test]` requires a different command to run the test,
75 /// but it's better than not to have the runnables for the tests at all.
76 pub fn test_related_attribute(fn_def: &ast::Fn) -> Option<ast::Attr> {
77     fn_def.attrs().find_map(|attr| {
78         let path = attr.path()?;
79         let text = path.syntax().text().to_string();
80         if text.starts_with("test") || text.ends_with("test") {
81             Some(attr)
82         } else {
83             None
84         }
85     })
86 }
87
88 #[derive(Copy, Clone, PartialEq)]
89 pub enum DefaultMethods {
90     Only,
91     No,
92 }
93
94 pub fn filter_assoc_items(
95     sema: &Semantics<RootDatabase>,
96     items: &[hir::AssocItem],
97     default_methods: DefaultMethods,
98 ) -> Vec<ast::AssocItem> {
99     fn has_def_name(item: &ast::AssocItem) -> bool {
100         match item {
101             ast::AssocItem::Fn(def) => def.name(),
102             ast::AssocItem::TypeAlias(def) => def.name(),
103             ast::AssocItem::Const(def) => def.name(),
104             ast::AssocItem::MacroCall(_) => None,
105         }
106         .is_some()
107     }
108
109     items
110         .iter()
111         // Note: This throws away items with no source.
112         .filter_map(|&i| {
113             let item = match i {
114                 hir::AssocItem::Function(i) => ast::AssocItem::Fn(sema.source(i)?.value),
115                 hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(sema.source(i)?.value),
116                 hir::AssocItem::Const(i) => ast::AssocItem::Const(sema.source(i)?.value),
117             };
118             Some(item)
119         })
120         .filter(has_def_name)
121         .filter(|it| match it {
122             ast::AssocItem::Fn(def) => matches!(
123                 (default_methods, def.body()),
124                 (DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None)
125             ),
126             _ => default_methods == DefaultMethods::No,
127         })
128         .collect::<Vec<_>>()
129 }
130
131 pub fn add_trait_assoc_items_to_impl(
132     sema: &Semantics<RootDatabase>,
133     items: Vec<ast::AssocItem>,
134     trait_: hir::Trait,
135     impl_: ast::Impl,
136     target_scope: hir::SemanticsScope,
137 ) -> (ast::Impl, ast::AssocItem) {
138     let source_scope = sema.scope_for_def(trait_);
139
140     let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
141
142     let items = items.into_iter().map(|assoc_item| {
143         transform.apply(assoc_item.syntax());
144         assoc_item.remove_attrs_and_docs();
145         assoc_item
146     });
147
148     let res = impl_.clone_for_update();
149
150     let assoc_item_list = res.get_or_create_assoc_item_list();
151     let mut first_item = None;
152     for item in items {
153         first_item.get_or_insert_with(|| item.clone());
154         match &item {
155             ast::AssocItem::Fn(fn_) if fn_.body().is_none() => {
156                 let body = make::block_expr(None, Some(make::ext::expr_todo()))
157                     .indent(edit::IndentLevel(1));
158                 ted::replace(fn_.get_or_create_body().syntax(), body.clone_for_update().syntax())
159             }
160             ast::AssocItem::TypeAlias(type_alias) => {
161                 if let Some(type_bound_list) = type_alias.type_bound_list() {
162                     type_bound_list.remove()
163                 }
164             }
165             _ => {}
166         }
167
168         assoc_item_list.add_item(item)
169     }
170
171     (res, first_item.unwrap())
172 }
173
174 #[derive(Clone, Copy, Debug)]
175 pub(crate) enum Cursor<'a> {
176     Replace(&'a SyntaxNode),
177     Before(&'a SyntaxNode),
178 }
179
180 impl<'a> Cursor<'a> {
181     fn node(self) -> &'a SyntaxNode {
182         match self {
183             Cursor::Replace(node) | Cursor::Before(node) => node,
184         }
185     }
186 }
187
188 pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor) -> String {
189     assert!(cursor.node().ancestors().any(|it| it == *node));
190     let range = cursor.node().text_range() - node.text_range().start();
191     let range: ops::Range<usize> = range.into();
192
193     let mut placeholder = cursor.node().to_string();
194     escape(&mut placeholder);
195     let tab_stop = match cursor {
196         Cursor::Replace(placeholder) => format!("${{0:{}}}", placeholder),
197         Cursor::Before(placeholder) => format!("$0{}", placeholder),
198     };
199
200     let mut buf = node.to_string();
201     buf.replace_range(range, &tab_stop);
202     return buf;
203
204     fn escape(buf: &mut String) {
205         stdx::replace(buf, '{', r"\{");
206         stdx::replace(buf, '}', r"\}");
207         stdx::replace(buf, '$', r"\$");
208     }
209 }
210
211 pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize {
212     node.children_with_tokens()
213         .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR))
214         .map(|it| it.text_range().start())
215         .unwrap_or_else(|| node.text_range().start())
216 }
217
218 pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr {
219     invert_special_case(&expr).unwrap_or_else(|| make::expr_prefix(T![!], expr))
220 }
221
222 fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
223     match expr {
224         ast::Expr::BinExpr(bin) => {
225             let bin = bin.clone_for_update();
226             let op_token = bin.op_token()?;
227             let rev_token = match op_token.kind() {
228                 T![==] => T![!=],
229                 T![!=] => T![==],
230                 T![<] => T![>=],
231                 T![<=] => T![>],
232                 T![>] => T![<=],
233                 T![>=] => T![<],
234                 // Parenthesize other expressions before prefixing `!`
235                 _ => return Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
236             };
237             ted::replace(op_token, make::token(rev_token));
238             Some(bin.into())
239         }
240         ast::Expr::MethodCallExpr(mce) => {
241             let receiver = mce.receiver()?;
242             let method = mce.name_ref()?;
243             let arg_list = mce.arg_list()?;
244
245             let method = match method.text().as_str() {
246                 "is_some" => "is_none",
247                 "is_none" => "is_some",
248                 "is_ok" => "is_err",
249                 "is_err" => "is_ok",
250                 _ => return None,
251             };
252             Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
253         }
254         ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
255             ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
256             _ => pe.expr(),
257         },
258         ast::Expr::Literal(lit) => match lit.kind() {
259             ast::LiteralKind::Bool(b) => match b {
260                 true => Some(ast::Expr::Literal(make::expr_literal("false"))),
261                 false => Some(ast::Expr::Literal(make::expr_literal("true"))),
262             },
263             _ => None,
264         },
265         _ => None,
266     }
267 }
268
269 pub(crate) fn next_prev() -> impl Iterator<Item = Direction> {
270     [Direction::Next, Direction::Prev].into_iter()
271 }
272
273 pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool {
274     let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text());
275
276     let pat_head = match pat {
277         ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
278             Some(p) => first_node_text(&p),
279             None => return pat.syntax().text() == var.syntax().text(),
280         },
281         pat => first_node_text(pat),
282     };
283
284     let var_head = first_node_text(var);
285
286     pat_head == var_head
287 }
288
289 pub(crate) fn does_nested_pattern(pat: &ast::Pat) -> bool {
290     let depth = calc_depth(pat, 0);
291
292     if 1 < depth {
293         return true;
294     }
295     false
296 }
297
298 fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
299     match pat {
300         ast::Pat::IdentPat(_)
301         | ast::Pat::BoxPat(_)
302         | ast::Pat::RestPat(_)
303         | ast::Pat::LiteralPat(_)
304         | ast::Pat::MacroPat(_)
305         | ast::Pat::OrPat(_)
306         | ast::Pat::ParenPat(_)
307         | ast::Pat::PathPat(_)
308         | ast::Pat::WildcardPat(_)
309         | ast::Pat::RangePat(_)
310         | ast::Pat::RecordPat(_)
311         | ast::Pat::RefPat(_)
312         | ast::Pat::SlicePat(_)
313         | ast::Pat::TuplePat(_)
314         | ast::Pat::ConstBlockPat(_) => depth,
315
316         // FIXME: Other patterns may also be nested. Currently it simply supports only `TupleStructPat`
317         ast::Pat::TupleStructPat(pat) => {
318             let mut max_depth = depth;
319             for p in pat.fields() {
320                 let d = calc_depth(&p, depth + 1);
321                 if d > max_depth {
322                     max_depth = d
323                 }
324             }
325             max_depth
326         }
327     }
328 }
329
330 // Uses a syntax-driven approach to find any impl blocks for the struct that
331 // exist within the module/file
332 //
333 // Returns `None` if we've found an existing fn
334 //
335 // FIXME: change the new fn checking to a more semantic approach when that's more
336 // viable (e.g. we process proc macros, etc)
337 // FIXME: this partially overlaps with `find_impl_block_*`
338 pub(crate) fn find_struct_impl(
339     ctx: &AssistContext,
340     adt: &ast::Adt,
341     name: &str,
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_fn(impl_blk, name) {
370             return None;
371         }
372     }
373
374     Some(block)
375 }
376
377 fn has_fn(imp: &ast::Impl, rhs_name: &str) -> 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 name.text().eq_ignore_ascii_case(rhs_name) {
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     let generic_params = adt.generic_param_list();
430     let mut buf = String::with_capacity(code.len());
431     buf.push_str("\n\n");
432     adt.attrs()
433         .filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false))
434         .for_each(|attr| buf.push_str(format!("{}\n", attr.to_string()).as_str()));
435     buf.push_str("impl");
436     if let Some(generic_params) = &generic_params {
437         let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax()));
438         let type_params = generic_params.type_params().map(|type_param| {
439             let mut buf = String::new();
440             if let Some(it) = type_param.name() {
441                 format_to!(buf, "{}", it.syntax());
442             }
443             if let Some(it) = type_param.colon_token() {
444                 format_to!(buf, "{} ", it);
445             }
446             if let Some(it) = type_param.type_bound_list() {
447                 format_to!(buf, "{}", it.syntax());
448             }
449             buf
450         });
451         let const_params = generic_params.const_params().map(|t| t.syntax().to_string());
452         let generics = lifetimes.chain(type_params).chain(const_params).format(", ");
453         format_to!(buf, "<{}>", generics);
454     }
455     buf.push(' ');
456     if let Some(trait_text) = trait_text {
457         buf.push_str(trait_text);
458         buf.push_str(" for ");
459     }
460     buf.push_str(&adt.name().unwrap().text());
461     if let Some(generic_params) = generic_params {
462         let lifetime_params = generic_params
463             .lifetime_params()
464             .filter_map(|it| it.lifetime())
465             .map(|it| SmolStr::from(it.text()));
466         let type_params = generic_params
467             .type_params()
468             .filter_map(|it| it.name())
469             .map(|it| SmolStr::from(it.text()));
470         let const_params = generic_params
471             .const_params()
472             .filter_map(|it| it.name())
473             .map(|it| SmolStr::from(it.text()));
474         format_to!(buf, "<{}>", lifetime_params.chain(type_params).chain(const_params).format(", "))
475     }
476
477     match adt.where_clause() {
478         Some(where_clause) => {
479             format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
480         }
481         None => {
482             format_to!(buf, " {{\n{}\n}}", code);
483         }
484     }
485
486     buf
487 }
488
489 pub(crate) fn add_method_to_adt(
490     builder: &mut AssistBuilder,
491     adt: &ast::Adt,
492     impl_def: Option<ast::Impl>,
493     method: &str,
494 ) {
495     let mut buf = String::with_capacity(method.len() + 2);
496     if impl_def.is_some() {
497         buf.push('\n');
498     }
499     buf.push_str(method);
500
501     let start_offset = impl_def
502         .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
503         .unwrap_or_else(|| {
504             buf = generate_impl_text(adt, &buf);
505             adt.syntax().text_range().end()
506         });
507
508     builder.insert(start_offset, buf);
509 }
510
511 #[derive(Debug)]
512 pub(crate) struct ReferenceConversion {
513     conversion: ReferenceConversionType,
514     ty: hir::Type,
515 }
516
517 #[derive(Debug)]
518 enum ReferenceConversionType {
519     // reference can be stripped if the type is Copy
520     Copy,
521     // &String -> &str
522     AsRefStr,
523     // &Vec<T> -> &[T]
524     AsRefSlice,
525     // &Box<T> -> &T
526     Dereferenced,
527     // &Option<T> -> Option<&T>
528     Option,
529     // &Result<T, E> -> Result<&T, &E>
530     Result,
531 }
532
533 impl ReferenceConversion {
534     pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String {
535         match self.conversion {
536             ReferenceConversionType::Copy => self.ty.display(db).to_string(),
537             ReferenceConversionType::AsRefStr => "&str".to_string(),
538             ReferenceConversionType::AsRefSlice => {
539                 let type_argument_name =
540                     self.ty.type_arguments().next().unwrap().display(db).to_string();
541                 format!("&[{}]", type_argument_name)
542             }
543             ReferenceConversionType::Dereferenced => {
544                 let type_argument_name =
545                     self.ty.type_arguments().next().unwrap().display(db).to_string();
546                 format!("&{}", type_argument_name)
547             }
548             ReferenceConversionType::Option => {
549                 let type_argument_name =
550                     self.ty.type_arguments().next().unwrap().display(db).to_string();
551                 format!("Option<&{}>", type_argument_name)
552             }
553             ReferenceConversionType::Result => {
554                 let mut type_arguments = self.ty.type_arguments();
555                 let first_type_argument_name =
556                     type_arguments.next().unwrap().display(db).to_string();
557                 let second_type_argument_name =
558                     type_arguments.next().unwrap().display(db).to_string();
559                 format!("Result<&{}, &{}>", first_type_argument_name, second_type_argument_name)
560             }
561         }
562     }
563
564     pub(crate) fn getter(&self, field_name: String) -> String {
565         match self.conversion {
566             ReferenceConversionType::Copy => format!("self.{}", field_name),
567             ReferenceConversionType::AsRefStr
568             | ReferenceConversionType::AsRefSlice
569             | ReferenceConversionType::Dereferenced
570             | ReferenceConversionType::Option
571             | ReferenceConversionType::Result => format!("self.{}.as_ref()", field_name),
572         }
573     }
574 }
575
576 // FIXME: It should return a new hir::Type, but currently constructing new types is too cumbersome
577 //        and all users of this function operate on string type names, so they can do the conversion
578 //        itself themselves.
579 pub(crate) fn convert_reference_type(
580     ty: hir::Type,
581     db: &RootDatabase,
582     famous_defs: &FamousDefs,
583 ) -> Option<ReferenceConversion> {
584     handle_copy(&ty, db)
585         .or_else(|| handle_as_ref_str(&ty, db, famous_defs))
586         .or_else(|| handle_as_ref_slice(&ty, db, famous_defs))
587         .or_else(|| handle_dereferenced(&ty, db, famous_defs))
588         .or_else(|| handle_option_as_ref(&ty, db, famous_defs))
589         .or_else(|| handle_result_as_ref(&ty, db, famous_defs))
590         .map(|conversion| ReferenceConversion { ty, conversion })
591 }
592
593 fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
594     ty.is_copy(db).then(|| ReferenceConversionType::Copy)
595 }
596
597 fn handle_as_ref_str(
598     ty: &hir::Type,
599     db: &dyn HirDatabase,
600     famous_defs: &FamousDefs,
601 ) -> Option<ReferenceConversionType> {
602     let module = famous_defs.1?.root_module(db);
603     let str_type = hir::BuiltinType::str().ty(db, module);
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 }