1 //! Assorted functions shared by several assists.
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};
12 edit::{self, AstNodeEdit},
13 edit_in_place::{AttrsOwnerEdit, Removable},
14 make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
16 ted, AstNode, AstToken, Direction, SourceFile,
18 SyntaxNode, TextRange, TextSize, T,
21 use crate::assist_context::{AssistContext, SourceChangeBuilder};
23 pub(crate) mod suggest_name;
24 mod gen_trait_fn_body;
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())
32 pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
33 if block_expr.modifier().is_some() {
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),
43 non_trivial_children.next().is_some()
46 if let Some(expr) = stmt_list.tail_expr() {
47 if has_anything_else(expr.syntax()) {
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()) {
58 let expr = expr_stmt.expr()?;
59 if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
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.
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") {
84 #[derive(Copy, Clone, PartialEq)]
85 pub enum DefaultMethods {
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 {
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,
107 // Note: This throws away items with no source.
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),
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)
122 ast::AssocItem::Const(def) => matches!(
123 (default_methods, def.body()),
124 (DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None)
126 _ => default_methods == DefaultMethods::No,
131 pub fn add_trait_assoc_items_to_impl(
132 sema: &Semantics<'_, RootDatabase>,
133 items: Vec<ast::AssocItem>,
136 target_scope: hir::SemanticsScope<'_>,
137 ) -> (ast::Impl, ast::AssocItem) {
138 let source_scope = sema.scope_for_def(trait_);
140 let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
142 let items = items.into_iter().map(|assoc_item| {
143 transform.apply(assoc_item.syntax());
144 assoc_item.remove_attrs_and_docs();
148 let res = impl_.clone_for_update();
150 let assoc_item_list = res.get_or_create_assoc_item_list();
151 let mut first_item = None;
153 first_item.get_or_insert_with(|| item.clone());
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())
160 ast::AssocItem::TypeAlias(type_alias) => {
161 if let Some(type_bound_list) = type_alias.type_bound_list() {
162 type_bound_list.remove()
168 assoc_item_list.add_item(item)
171 (res, first_item.unwrap())
174 #[derive(Clone, Copy, Debug)]
175 pub(crate) enum Cursor<'a> {
176 Replace(&'a SyntaxNode),
177 Before(&'a SyntaxNode),
180 impl<'a> Cursor<'a> {
181 fn node(self) -> &'a SyntaxNode {
183 Cursor::Replace(node) | Cursor::Before(node) => node,
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();
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}"),
200 let mut buf = node.to_string();
201 buf.replace_range(range, &tab_stop);
204 fn escape(buf: &mut String) {
205 stdx::replace(buf, '{', r"\{");
206 stdx::replace(buf, '}', r"\}");
207 stdx::replace(buf, '$', r"\$");
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())
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))
222 fn invert_special_case(expr: &ast::Expr) -> Option<ast::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() {
234 // Parenthesize other expressions before prefixing `!`
235 _ => return Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
237 ted::replace(op_token, make::token(rev_token));
240 ast::Expr::MethodCallExpr(mce) => {
241 let receiver = mce.receiver()?;
242 let method = mce.name_ref()?;
243 let arg_list = mce.arg_list()?;
245 let method = match method.text().as_str() {
246 "is_some" => "is_none",
247 "is_none" => "is_some",
252 Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
254 ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
255 ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
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"))),
269 pub(crate) fn next_prev() -> impl Iterator<Item = Direction> {
270 [Direction::Next, Direction::Prev].into_iter()
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());
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(),
281 pat => first_node_text(pat),
284 let var_head = first_node_text(var);
289 pub(crate) fn does_nested_pattern(pat: &ast::Pat) -> bool {
290 let depth = calc_depth(pat, 0);
298 fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
300 ast::Pat::IdentPat(_)
301 | ast::Pat::BoxPat(_)
302 | ast::Pat::RestPat(_)
303 | ast::Pat::LiteralPat(_)
304 | ast::Pat::MacroPat(_)
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,
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);
330 // Uses a syntax-driven approach to find any impl blocks for the struct that
331 // exist within the module/file
333 // Returns `None` if we've found an existing fn
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_*`
339 /// `find_struct_impl` looks for impl of a struct, but this also has additional feature
340 /// where it takes a list of function names and check if they exist inside impl_, if
341 /// even one match is found, it returns None
342 pub(crate) fn find_struct_impl(
343 ctx: &AssistContext<'_>,
346 ) -> Option<Option<ast::Impl>> {
348 let module = adt.syntax().parent()?;
350 let struct_def = ctx.sema.to_def(adt)?;
352 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
353 let blk = ctx.sema.to_def(&impl_blk)?;
355 // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
356 // (we currently use the wrong type parameter)
357 // also we wouldn't want to use e.g. `impl S<u32>`
359 let same_ty = match blk.self_ty(db).as_adt() {
360 Some(def) => def == struct_def,
363 let not_trait_impl = blk.trait_(db).is_none();
365 if !(same_ty && not_trait_impl) {
372 if let Some(ref impl_blk) = block {
373 if has_any_fn(impl_blk, names) {
381 fn has_any_fn(imp: &ast::Impl, names: &[String]) -> bool {
382 if let Some(il) = imp.assoc_item_list() {
383 for item in il.assoc_items() {
384 if let ast::AssocItem::Fn(f) = item {
385 if let Some(name) = f.name() {
386 if names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) {
397 /// Find the start of the `impl` block for the given `ast::Impl`.
399 // FIXME: this partially overlaps with `find_struct_impl`
400 pub(crate) fn find_impl_block_start(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
402 let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end();
406 /// Find the end of the `impl` block for the given `ast::Impl`.
408 // FIXME: this partially overlaps with `find_struct_impl`
409 pub(crate) fn find_impl_block_end(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
413 .and_then(|it| it.r_curly_token())?
414 .prev_sibling_or_token()?
420 // Generates the surrounding `impl Type { <code> }` including type and lifetime
422 pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
423 generate_impl_text_inner(adt, None, code)
426 // Generates the surrounding `impl <trait> for Type { <code> }` including type
427 // and lifetime parameters
428 pub(crate) fn generate_trait_impl_text(adt: &ast::Adt, trait_text: &str, code: &str) -> String {
429 generate_impl_text_inner(adt, Some(trait_text), code)
432 fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str) -> String {
433 // Ensure lifetime params are before type & const params
434 let generic_params = adt.generic_param_list().map(|generic_params| {
435 let lifetime_params =
436 generic_params.lifetime_params().map(ast::GenericParam::LifetimeParam);
437 let ty_or_const_params = generic_params.type_or_const_params().filter_map(|param| {
438 // remove defaults since they can't be specified in impls
440 ast::TypeOrConstParam::Type(param) => {
441 let param = param.clone_for_update();
442 param.remove_default();
443 Some(ast::GenericParam::TypeParam(param))
445 ast::TypeOrConstParam::Const(param) => {
446 let param = param.clone_for_update();
447 param.remove_default();
448 Some(ast::GenericParam::ConstParam(param))
453 make::generic_param_list(itertools::chain(lifetime_params, ty_or_const_params))
456 // FIXME: use syntax::make & mutable AST apis instead
457 // `trait_text` and `code` can't be opaque blobs of text
458 let mut buf = String::with_capacity(code.len());
460 // Copy any cfg attrs from the original adt
461 buf.push_str("\n\n");
464 .filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false));
465 cfg_attrs.for_each(|attr| buf.push_str(&format!("{attr}\n")));
467 // `impl{generic_params} {trait_text} for {name}{generic_params.to_generic_args()}`
468 buf.push_str("impl");
469 if let Some(generic_params) = &generic_params {
470 format_to!(buf, "{generic_params}");
473 if let Some(trait_text) = trait_text {
474 buf.push_str(trait_text);
475 buf.push_str(" for ");
477 buf.push_str(&adt.name().unwrap().text());
478 if let Some(generic_params) = generic_params {
479 format_to!(buf, "{}", generic_params.to_generic_args());
482 match adt.where_clause() {
483 Some(where_clause) => {
484 format_to!(buf, "\n{where_clause}\n{{\n{code}\n}}");
487 format_to!(buf, " {{\n{code}\n}}");
494 pub(crate) fn add_method_to_adt(
495 builder: &mut SourceChangeBuilder,
497 impl_def: Option<ast::Impl>,
500 let mut buf = String::with_capacity(method.len() + 2);
501 if impl_def.is_some() {
504 buf.push_str(method);
506 let start_offset = impl_def
507 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
509 buf = generate_impl_text(adt, &buf);
510 adt.syntax().text_range().end()
513 builder.insert(start_offset, buf);
517 pub(crate) struct ReferenceConversion {
518 conversion: ReferenceConversionType,
523 enum ReferenceConversionType {
524 // reference can be stripped if the type is Copy
532 // &Option<T> -> Option<&T>
534 // &Result<T, E> -> Result<&T, &E>
538 impl ReferenceConversion {
539 pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String {
540 match self.conversion {
541 ReferenceConversionType::Copy => self.ty.display(db).to_string(),
542 ReferenceConversionType::AsRefStr => "&str".to_string(),
543 ReferenceConversionType::AsRefSlice => {
544 let type_argument_name =
545 self.ty.type_arguments().next().unwrap().display(db).to_string();
546 format!("&[{type_argument_name}]")
548 ReferenceConversionType::Dereferenced => {
549 let type_argument_name =
550 self.ty.type_arguments().next().unwrap().display(db).to_string();
551 format!("&{type_argument_name}")
553 ReferenceConversionType::Option => {
554 let type_argument_name =
555 self.ty.type_arguments().next().unwrap().display(db).to_string();
556 format!("Option<&{type_argument_name}>")
558 ReferenceConversionType::Result => {
559 let mut type_arguments = self.ty.type_arguments();
560 let first_type_argument_name =
561 type_arguments.next().unwrap().display(db).to_string();
562 let second_type_argument_name =
563 type_arguments.next().unwrap().display(db).to_string();
564 format!("Result<&{first_type_argument_name}, &{second_type_argument_name}>")
569 pub(crate) fn getter(&self, field_name: String) -> String {
570 match self.conversion {
571 ReferenceConversionType::Copy => format!("self.{field_name}"),
572 ReferenceConversionType::AsRefStr
573 | ReferenceConversionType::AsRefSlice
574 | ReferenceConversionType::Dereferenced
575 | ReferenceConversionType::Option
576 | ReferenceConversionType::Result => format!("self.{field_name}.as_ref()"),
581 // FIXME: It should return a new hir::Type, but currently constructing new types is too cumbersome
582 // and all users of this function operate on string type names, so they can do the conversion
583 // itself themselves.
584 pub(crate) fn convert_reference_type(
587 famous_defs: &FamousDefs<'_, '_>,
588 ) -> Option<ReferenceConversion> {
590 .or_else(|| handle_as_ref_str(&ty, db, famous_defs))
591 .or_else(|| handle_as_ref_slice(&ty, db, famous_defs))
592 .or_else(|| handle_dereferenced(&ty, db, famous_defs))
593 .or_else(|| handle_option_as_ref(&ty, db, famous_defs))
594 .or_else(|| handle_result_as_ref(&ty, db, famous_defs))
595 .map(|conversion| ReferenceConversion { ty, conversion })
598 fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
599 ty.is_copy(db).then(|| ReferenceConversionType::Copy)
602 fn handle_as_ref_str(
604 db: &dyn HirDatabase,
605 famous_defs: &FamousDefs<'_, '_>,
606 ) -> Option<ReferenceConversionType> {
607 let str_type = hir::BuiltinType::str().ty(db);
609 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[str_type])
610 .then(|| ReferenceConversionType::AsRefStr)
613 fn handle_as_ref_slice(
615 db: &dyn HirDatabase,
616 famous_defs: &FamousDefs<'_, '_>,
617 ) -> Option<ReferenceConversionType> {
618 let type_argument = ty.type_arguments().next()?;
619 let slice_type = hir::Type::new_slice(type_argument);
621 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[slice_type])
622 .then(|| ReferenceConversionType::AsRefSlice)
625 fn handle_dereferenced(
627 db: &dyn HirDatabase,
628 famous_defs: &FamousDefs<'_, '_>,
629 ) -> Option<ReferenceConversionType> {
630 let type_argument = ty.type_arguments().next()?;
632 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[type_argument])
633 .then(|| ReferenceConversionType::Dereferenced)
636 fn handle_option_as_ref(
638 db: &dyn HirDatabase,
639 famous_defs: &FamousDefs<'_, '_>,
640 ) -> Option<ReferenceConversionType> {
641 if ty.as_adt() == famous_defs.core_option_Option()?.ty(db).as_adt() {
642 Some(ReferenceConversionType::Option)
648 fn handle_result_as_ref(
650 db: &dyn HirDatabase,
651 famous_defs: &FamousDefs<'_, '_>,
652 ) -> Option<ReferenceConversionType> {
653 if ty.as_adt() == famous_defs.core_result_Result()?.ty(db).as_adt() {
654 Some(ReferenceConversionType::Result)
660 pub(crate) fn get_methods(items: &ast::AssocItemList) -> Vec<ast::Fn> {
663 .flat_map(|i| match i {
664 ast::AssocItem::Fn(f) => Some(f),
667 .filter(|f| f.name().is_some())
671 /// Trim(remove leading and trailing whitespace) `initial_range` in `source_file`, return the trimmed range.
672 pub(crate) fn trimmed_text_range(source_file: &SourceFile, initial_range: TextRange) -> TextRange {
673 let mut trimmed_range = initial_range;
676 .token_at_offset(trimmed_range.start())
677 .find_map(Whitespace::cast)
679 && trimmed_range.start() < trimmed_range.end()
681 let start = trimmed_range.start() + TextSize::from(1);
682 trimmed_range = TextRange::new(start, trimmed_range.end());
686 .token_at_offset(trimmed_range.end())
687 .find_map(Whitespace::cast)
689 && trimmed_range.start() < trimmed_range.end()
691 let end = trimmed_range.end() - TextSize::from(1);
692 trimmed_range = TextRange::new(trimmed_range.start(), end);
697 /// Convert a list of function params to a list of arguments that can be passed
698 /// into a function call.
699 pub(crate) fn convert_param_list_to_arg_list(list: ast::ParamList) -> ast::ArgList {
700 let mut args = vec![];
701 for param in list.params() {
702 if let Some(ast::Pat::IdentPat(pat)) = param.pat() {
703 if let Some(name) = pat.name() {
704 let name = name.to_string();
705 let expr = make::expr_path(make::ext::ident_path(&name));