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};
10 helpers::FamousDefs, helpers::SnippetCap, path_transform::PathTransform, RootDatabase,
16 edit::{self, AstNodeEdit},
17 edit_in_place::AttrsOwnerEdit,
18 make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
20 ted, AstNode, AstToken, Direction, SmolStr, SourceFile,
22 SyntaxNode, TextRange, TextSize, T,
25 use crate::assist_context::{AssistBuilder, AssistContext};
27 pub(crate) mod suggest_name;
28 mod gen_trait_fn_body;
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())
36 pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
37 if block_expr.modifier().is_some() {
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),
47 non_trivial_children.next().is_some()
50 if let Some(expr) = stmt_list.tail_expr() {
51 if has_anything_else(expr.syntax()) {
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()) {
62 let expr = expr_stmt.expr()?;
63 if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
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.
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") {
88 #[derive(Copy, Clone, PartialEq)]
89 pub enum DefaultMethods {
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 {
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,
111 // Note: This throws away items with no source.
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),
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)
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_*`
338 pub(crate) fn find_struct_impl(
342 ) -> Option<Option<ast::Impl>> {
344 let module = adt.syntax().parent()?;
346 let struct_def = ctx.sema.to_def(adt)?;
348 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
349 let blk = ctx.sema.to_def(&impl_blk)?;
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>`
355 let same_ty = match blk.self_ty(db).as_adt() {
356 Some(def) => def == struct_def,
359 let not_trait_impl = blk.trait_(db).is_none();
361 if !(same_ty && not_trait_impl) {
368 if let Some(ref impl_blk) = block {
369 if has_fn(impl_blk, name) {
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) {
393 /// Find the start of the `impl` block for the given `ast::Impl`.
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> {
398 let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end();
402 /// Find the end of the `impl` block for the given `ast::Impl`.
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> {
409 .and_then(|it| it.r_curly_token())?
410 .prev_sibling_or_token()?
416 // Generates the surrounding `impl Type { <code> }` including type and lifetime
418 pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
419 generate_impl_text_inner(adt, None, code)
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)
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");
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());
443 if let Some(it) = type_param.colon_token() {
444 format_to!(buf, "{} ", it);
446 if let Some(it) = type_param.type_bound_list() {
447 format_to!(buf, "{}", it.syntax());
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);
456 if let Some(trait_text) = trait_text {
457 buf.push_str(trait_text);
458 buf.push_str(" for ");
460 buf.push_str(&adt.name().unwrap().text());
461 if let Some(generic_params) = generic_params {
462 let lifetime_params = generic_params
464 .filter_map(|it| it.lifetime())
465 .map(|it| SmolStr::from(it.text()));
466 let type_params = generic_params
468 .filter_map(|it| it.name())
469 .map(|it| SmolStr::from(it.text()));
470 let const_params = generic_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(", "))
477 match adt.where_clause() {
478 Some(where_clause) => {
479 format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
482 format_to!(buf, " {{\n{}\n}}", code);
489 pub(crate) fn add_method_to_adt(
490 builder: &mut AssistBuilder,
492 impl_def: Option<ast::Impl>,
495 let mut buf = String::with_capacity(method.len() + 2);
496 if impl_def.is_some() {
499 buf.push_str(method);
501 let start_offset = impl_def
502 .and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
504 buf = generate_impl_text(adt, &buf);
505 adt.syntax().text_range().end()
508 builder.insert(start_offset, buf);
512 pub(crate) struct ReferenceConversion {
513 conversion: ReferenceConversionType,
518 enum ReferenceConversionType {
519 // reference can be stripped if the type is Copy
527 // &Option<T> -> Option<&T>
529 // &Result<T, E> -> Result<&T, &E>
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)
543 ReferenceConversionType::Dereferenced => {
544 let type_argument_name =
545 self.ty.type_arguments().next().unwrap().display(db).to_string();
546 format!("&{}", type_argument_name)
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)
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)
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),
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(
582 famous_defs: &FamousDefs,
583 ) -> Option<ReferenceConversion> {
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 })
593 fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
594 ty.is_copy(db).then(|| ReferenceConversionType::Copy)
597 fn handle_as_ref_str(
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);
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));