1 //! Assorted functions shared by several assists.
5 use itertools::Itertools;
7 pub(crate) use gen_trait_fn_body::gen_trait_fn_body;
8 use hir::{db::HirDatabase, HirDisplay, Semantics};
9 use ide_db::{famous_defs::FamousDefs, path_transform::PathTransform, RootDatabase, SnippetCap};
14 edit::{self, AstNodeEdit},
15 edit_in_place::AttrsOwnerEdit,
16 make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
18 ted, AstNode, AstToken, Direction, SmolStr, SourceFile,
20 SyntaxNode, TextRange, TextSize, T,
23 use crate::assist_context::{AssistBuilder, AssistContext};
25 pub(crate) mod suggest_name;
26 mod gen_trait_fn_body;
28 pub(crate) fn unwrap_trivial_block(block_expr: ast::BlockExpr) -> ast::Expr {
29 extract_trivial_expression(&block_expr)
30 .filter(|expr| !expr.syntax().text().contains_char('\n'))
31 .unwrap_or_else(|| block_expr.into())
34 pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
35 if block_expr.modifier().is_some() {
38 let stmt_list = block_expr.stmt_list()?;
39 let has_anything_else = |thing: &SyntaxNode| -> bool {
40 let mut non_trivial_children =
41 stmt_list.syntax().children_with_tokens().filter(|it| match it.kind() {
42 WHITESPACE | T!['{'] | T!['}'] => false,
43 _ => it.as_node() != Some(thing),
45 non_trivial_children.next().is_some()
48 if let Some(expr) = stmt_list.tail_expr() {
49 if has_anything_else(expr.syntax()) {
54 // Unwrap `{ continue; }`
55 let stmt = stmt_list.statements().next()?;
56 if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
57 if has_anything_else(expr_stmt.syntax()) {
60 let expr = expr_stmt.expr()?;
61 if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
68 /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as
69 /// `#[test_case(...)]`, `#[tokio::test]` and similar.
70 /// Also a regular `#[test]` annotation is supported.
72 /// It may produce false positives, for example, `#[wasm_bindgen_test]` requires a different command to run the test,
73 /// but it's better than not to have the runnables for the tests at all.
74 pub fn test_related_attribute(fn_def: &ast::Fn) -> Option<ast::Attr> {
75 fn_def.attrs().find_map(|attr| {
76 let path = attr.path()?;
77 let text = path.syntax().text().to_string();
78 if text.starts_with("test") || text.ends_with("test") {
86 #[derive(Copy, Clone, PartialEq)]
87 pub enum DefaultMethods {
92 pub fn filter_assoc_items(
93 sema: &Semantics<RootDatabase>,
94 items: &[hir::AssocItem],
95 default_methods: DefaultMethods,
96 ) -> Vec<ast::AssocItem> {
97 fn has_def_name(item: &ast::AssocItem) -> bool {
99 ast::AssocItem::Fn(def) => def.name(),
100 ast::AssocItem::TypeAlias(def) => def.name(),
101 ast::AssocItem::Const(def) => def.name(),
102 ast::AssocItem::MacroCall(_) => None,
109 // Note: This throws away items with no source.
112 hir::AssocItem::Function(i) => ast::AssocItem::Fn(sema.source(i)?.value),
113 hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(sema.source(i)?.value),
114 hir::AssocItem::Const(i) => ast::AssocItem::Const(sema.source(i)?.value),
118 .filter(has_def_name)
119 .filter(|it| match it {
120 ast::AssocItem::Fn(def) => matches!(
121 (default_methods, def.body()),
122 (DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None)
124 _ => default_methods == DefaultMethods::No,
129 pub fn add_trait_assoc_items_to_impl(
130 sema: &Semantics<RootDatabase>,
131 items: Vec<ast::AssocItem>,
134 target_scope: hir::SemanticsScope,
135 ) -> (ast::Impl, ast::AssocItem) {
136 let source_scope = sema.scope_for_def(trait_);
138 let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
140 let items = items.into_iter().map(|assoc_item| {
141 transform.apply(assoc_item.syntax());
142 assoc_item.remove_attrs_and_docs();
146 let res = impl_.clone_for_update();
148 let assoc_item_list = res.get_or_create_assoc_item_list();
149 let mut first_item = None;
151 first_item.get_or_insert_with(|| item.clone());
153 ast::AssocItem::Fn(fn_) if fn_.body().is_none() => {
154 let body = make::block_expr(None, Some(make::ext::expr_todo()))
155 .indent(edit::IndentLevel(1));
156 ted::replace(fn_.get_or_create_body().syntax(), body.clone_for_update().syntax())
158 ast::AssocItem::TypeAlias(type_alias) => {
159 if let Some(type_bound_list) = type_alias.type_bound_list() {
160 type_bound_list.remove()
166 assoc_item_list.add_item(item)
169 (res, first_item.unwrap())
172 #[derive(Clone, Copy, Debug)]
173 pub(crate) enum Cursor<'a> {
174 Replace(&'a SyntaxNode),
175 Before(&'a SyntaxNode),
178 impl<'a> Cursor<'a> {
179 fn node(self) -> &'a SyntaxNode {
181 Cursor::Replace(node) | Cursor::Before(node) => node,
186 pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor) -> String {
187 assert!(cursor.node().ancestors().any(|it| it == *node));
188 let range = cursor.node().text_range() - node.text_range().start();
189 let range: ops::Range<usize> = range.into();
191 let mut placeholder = cursor.node().to_string();
192 escape(&mut placeholder);
193 let tab_stop = match cursor {
194 Cursor::Replace(placeholder) => format!("${{0:{}}}", placeholder),
195 Cursor::Before(placeholder) => format!("$0{}", placeholder),
198 let mut buf = node.to_string();
199 buf.replace_range(range, &tab_stop);
202 fn escape(buf: &mut String) {
203 stdx::replace(buf, '{', r"\{");
204 stdx::replace(buf, '}', r"\}");
205 stdx::replace(buf, '$', r"\$");
209 pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize {
210 node.children_with_tokens()
211 .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR))
212 .map(|it| it.text_range().start())
213 .unwrap_or_else(|| node.text_range().start())
216 pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr {
217 invert_special_case(&expr).unwrap_or_else(|| make::expr_prefix(T![!], expr))
220 fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
222 ast::Expr::BinExpr(bin) => {
223 let bin = bin.clone_for_update();
224 let op_token = bin.op_token()?;
225 let rev_token = match op_token.kind() {
232 // Parenthesize other expressions before prefixing `!`
233 _ => return Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
235 ted::replace(op_token, make::token(rev_token));
238 ast::Expr::MethodCallExpr(mce) => {
239 let receiver = mce.receiver()?;
240 let method = mce.name_ref()?;
241 let arg_list = mce.arg_list()?;
243 let method = match method.text().as_str() {
244 "is_some" => "is_none",
245 "is_none" => "is_some",
250 Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
252 ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
253 ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
256 ast::Expr::Literal(lit) => match lit.kind() {
257 ast::LiteralKind::Bool(b) => match b {
258 true => Some(ast::Expr::Literal(make::expr_literal("false"))),
259 false => Some(ast::Expr::Literal(make::expr_literal("true"))),
267 pub(crate) fn next_prev() -> impl Iterator<Item = Direction> {
268 [Direction::Next, Direction::Prev].into_iter()
271 pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool {
272 let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text());
274 let pat_head = match pat {
275 ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
276 Some(p) => first_node_text(&p),
277 None => return pat.syntax().text() == var.syntax().text(),
279 pat => first_node_text(pat),
282 let var_head = first_node_text(var);
287 pub(crate) fn does_nested_pattern(pat: &ast::Pat) -> bool {
288 let depth = calc_depth(pat, 0);
296 fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
298 ast::Pat::IdentPat(_)
299 | ast::Pat::BoxPat(_)
300 | ast::Pat::RestPat(_)
301 | ast::Pat::LiteralPat(_)
302 | ast::Pat::MacroPat(_)
304 | ast::Pat::ParenPat(_)
305 | ast::Pat::PathPat(_)
306 | ast::Pat::WildcardPat(_)
307 | ast::Pat::RangePat(_)
308 | ast::Pat::RecordPat(_)
309 | ast::Pat::RefPat(_)
310 | ast::Pat::SlicePat(_)
311 | ast::Pat::TuplePat(_)
312 | ast::Pat::ConstBlockPat(_) => depth,
314 // FIXME: Other patterns may also be nested. Currently it simply supports only `TupleStructPat`
315 ast::Pat::TupleStructPat(pat) => {
316 let mut max_depth = depth;
317 for p in pat.fields() {
318 let d = calc_depth(&p, depth + 1);
328 // Uses a syntax-driven approach to find any impl blocks for the struct that
329 // exist within the module/file
331 // Returns `None` if we've found an existing fn
333 // FIXME: change the new fn checking to a more semantic approach when that's more
334 // viable (e.g. we process proc macros, etc)
335 // FIXME: this partially overlaps with `find_impl_block_*`
336 pub(crate) fn find_struct_impl(
340 ) -> Option<Option<ast::Impl>> {
342 let module = adt.syntax().parent()?;
344 let struct_def = ctx.sema.to_def(adt)?;
346 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
347 let blk = ctx.sema.to_def(&impl_blk)?;
349 // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
350 // (we currently use the wrong type parameter)
351 // also we wouldn't want to use e.g. `impl S<u32>`
353 let same_ty = match blk.self_ty(db).as_adt() {
354 Some(def) => def == struct_def,
357 let not_trait_impl = blk.trait_(db).is_none();
359 if !(same_ty && not_trait_impl) {
366 if let Some(ref impl_blk) = block {
367 if has_fn(impl_blk, name) {
375 fn has_fn(imp: &ast::Impl, rhs_name: &str) -> bool {
376 if let Some(il) = imp.assoc_item_list() {
377 for item in il.assoc_items() {
378 if let ast::AssocItem::Fn(f) = item {
379 if let Some(name) = f.name() {
380 if name.text().eq_ignore_ascii_case(rhs_name) {
391 /// Find the start of the `impl` block for the given `ast::Impl`.
393 // FIXME: this partially overlaps with `find_struct_impl`
394 pub(crate) fn find_impl_block_start(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
396 let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end();
400 /// Find the end of the `impl` block for the given `ast::Impl`.
402 // FIXME: this partially overlaps with `find_struct_impl`
403 pub(crate) fn find_impl_block_end(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
407 .and_then(|it| it.r_curly_token())?
408 .prev_sibling_or_token()?
414 // Generates the surrounding `impl Type { <code> }` including type and lifetime
416 pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
417 generate_impl_text_inner(adt, None, code)
420 // Generates the surrounding `impl <trait> for Type { <code> }` including type
421 // and lifetime parameters
422 pub(crate) fn generate_trait_impl_text(adt: &ast::Adt, trait_text: &str, code: &str) -> String {
423 generate_impl_text_inner(adt, Some(trait_text), code)
426 fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str) -> String {
427 let generic_params = adt.generic_param_list();
428 let mut buf = String::with_capacity(code.len());
429 buf.push_str("\n\n");
431 .filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false))
432 .for_each(|attr| buf.push_str(format!("{}\n", attr).as_str()));
433 buf.push_str("impl");
434 if let Some(generic_params) = &generic_params {
435 let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax()));
436 let toc_params = generic_params.type_or_const_params().map(|toc_param| {
437 let type_param = match toc_param {
438 ast::TypeOrConstParam::Type(x) => x,
439 ast::TypeOrConstParam::Const(x) => return x.syntax().to_string(),
441 let mut buf = String::new();
442 if let Some(it) = type_param.name() {
443 format_to!(buf, "{}", it.syntax());
445 if let Some(it) = type_param.colon_token() {
446 format_to!(buf, "{} ", it);
448 if let Some(it) = type_param.type_bound_list() {
449 format_to!(buf, "{}", it.syntax());
453 let generics = lifetimes.chain(toc_params).format(", ");
454 format_to!(buf, "<{}>", generics);
457 if let Some(trait_text) = trait_text {
458 buf.push_str(trait_text);
459 buf.push_str(" for ");
461 buf.push_str(&adt.name().unwrap().text());
462 if let Some(generic_params) = generic_params {
463 let lifetime_params = generic_params
465 .filter_map(|it| it.lifetime())
466 .map(|it| SmolStr::from(it.text()));
467 let toc_params = generic_params
468 .type_or_const_params()
469 .filter_map(|it| it.name())
470 .map(|it| SmolStr::from(it.text()));
471 format_to!(buf, "<{}>", lifetime_params.chain(toc_params).format(", "))
474 match adt.where_clause() {
475 Some(where_clause) => {
476 format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
479 format_to!(buf, " {{\n{}\n}}", code);
486 pub(crate) fn add_method_to_adt(
487 builder: &mut AssistBuilder,
489 impl_def: Option<ast::Impl>,
492 let mut buf = String::with_capacity(method.len() + 2);
493 if impl_def.is_some() {
496 buf.push_str(method);
498 let start_offset = impl_def
499 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
501 buf = generate_impl_text(adt, &buf);
502 adt.syntax().text_range().end()
505 builder.insert(start_offset, buf);
509 pub(crate) struct ReferenceConversion {
510 conversion: ReferenceConversionType,
515 enum ReferenceConversionType {
516 // reference can be stripped if the type is Copy
524 // &Option<T> -> Option<&T>
526 // &Result<T, E> -> Result<&T, &E>
530 impl ReferenceConversion {
531 pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String {
532 match self.conversion {
533 ReferenceConversionType::Copy => self.ty.display(db).to_string(),
534 ReferenceConversionType::AsRefStr => "&str".to_string(),
535 ReferenceConversionType::AsRefSlice => {
536 let type_argument_name =
537 self.ty.type_arguments().next().unwrap().display(db).to_string();
538 format!("&[{}]", type_argument_name)
540 ReferenceConversionType::Dereferenced => {
541 let type_argument_name =
542 self.ty.type_arguments().next().unwrap().display(db).to_string();
543 format!("&{}", type_argument_name)
545 ReferenceConversionType::Option => {
546 let type_argument_name =
547 self.ty.type_arguments().next().unwrap().display(db).to_string();
548 format!("Option<&{}>", type_argument_name)
550 ReferenceConversionType::Result => {
551 let mut type_arguments = self.ty.type_arguments();
552 let first_type_argument_name =
553 type_arguments.next().unwrap().display(db).to_string();
554 let second_type_argument_name =
555 type_arguments.next().unwrap().display(db).to_string();
556 format!("Result<&{}, &{}>", first_type_argument_name, second_type_argument_name)
561 pub(crate) fn getter(&self, field_name: String) -> String {
562 match self.conversion {
563 ReferenceConversionType::Copy => format!("self.{}", field_name),
564 ReferenceConversionType::AsRefStr
565 | ReferenceConversionType::AsRefSlice
566 | ReferenceConversionType::Dereferenced
567 | ReferenceConversionType::Option
568 | ReferenceConversionType::Result => format!("self.{}.as_ref()", field_name),
572 pub(crate) fn is_copy(&self) -> bool {
573 matches!(self.conversion, ReferenceConversionType::Copy)
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(
583 famous_defs: &FamousDefs,
584 ) -> Option<ReferenceConversion> {
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 })
594 fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
595 ty.is_copy(db).then(|| ReferenceConversionType::Copy)
598 fn handle_as_ref_str(
600 db: &dyn HirDatabase,
601 famous_defs: &FamousDefs,
602 ) -> Option<ReferenceConversionType> {
603 let str_type = hir::BuiltinType::str().ty(db);
605 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[str_type])
606 .then(|| ReferenceConversionType::AsRefStr)
609 fn handle_as_ref_slice(
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);
617 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[slice_type])
618 .then(|| ReferenceConversionType::AsRefSlice)
621 fn handle_dereferenced(
623 db: &dyn HirDatabase,
624 famous_defs: &FamousDefs,
625 ) -> Option<ReferenceConversionType> {
626 let type_argument = ty.type_arguments().next()?;
628 ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[type_argument])
629 .then(|| ReferenceConversionType::Dereferenced)
632 fn handle_option_as_ref(
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)
644 fn handle_result_as_ref(
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)
656 pub(crate) fn get_methods(items: &ast::AssocItemList) -> Vec<ast::Fn> {
659 .flat_map(|i| match i {
660 ast::AssocItem::Fn(f) => Some(f),
663 .filter(|f| f.name().is_some())
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;
672 .token_at_offset(trimmed_range.start())
673 .find_map(Whitespace::cast)
675 && trimmed_range.start() < trimmed_range.end()
677 let start = trimmed_range.start() + TextSize::from(1);
678 trimmed_range = TextRange::new(start, trimmed_range.end());
682 .token_at_offset(trimmed_range.end())
683 .find_map(Whitespace::cast)
685 && trimmed_range.start() < trimmed_range.end()
687 let end = trimmed_range.end() - TextSize::from(1);
688 trimmed_range = TextRange::new(trimmed_range.start(), end);
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));