2020-02-07 08:57:38 -06:00
|
|
|
//! Assorted functions shared by several assists.
|
|
|
|
|
2020-10-24 02:47:23 -05:00
|
|
|
use std::ops;
|
2020-04-29 04:57:06 -05:00
|
|
|
|
2020-08-13 04:41:20 -05:00
|
|
|
use itertools::Itertools;
|
2021-09-29 07:04:32 -05:00
|
|
|
|
|
|
|
pub(crate) use gen_trait_fn_body::gen_trait_fn_body;
|
2021-10-20 14:35:35 -05:00
|
|
|
use hir::{db::HirDatabase, HasSource, HirDisplay};
|
|
|
|
use ide_db::{
|
|
|
|
helpers::FamousDefs, helpers::SnippetCap, path_transform::PathTransform, RootDatabase,
|
|
|
|
};
|
2021-02-09 05:30:13 -06:00
|
|
|
use stdx::format_to;
|
2020-08-12 11:26:51 -05:00
|
|
|
use syntax::{
|
2021-07-06 13:30:26 -05:00
|
|
|
ast::{
|
|
|
|
self,
|
|
|
|
edit::{self, AstNodeEdit},
|
2021-08-14 12:38:31 -05:00
|
|
|
edit_in_place::AttrsOwnerEdit,
|
2021-09-27 21:20:29 -05:00
|
|
|
make, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace,
|
2021-07-06 13:30:26 -05:00
|
|
|
},
|
2021-09-27 21:20:29 -05:00
|
|
|
ted, AstNode, AstToken, Direction, SmolStr, SourceFile,
|
2020-06-28 17:18:50 -05:00
|
|
|
SyntaxKind::*,
|
2021-09-27 21:20:29 -05:00
|
|
|
SyntaxNode, TextRange, TextSize, T,
|
2020-02-07 08:57:38 -06:00
|
|
|
};
|
2020-02-09 12:24:34 -06:00
|
|
|
|
2021-06-17 18:54:28 -05:00
|
|
|
use crate::assist_context::{AssistBuilder, AssistContext};
|
2020-05-19 16:12:01 -05:00
|
|
|
|
2021-09-29 07:04:32 -05:00
|
|
|
pub(crate) mod suggest_name;
|
|
|
|
mod gen_trait_fn_body;
|
2021-08-09 14:47:44 -05:00
|
|
|
|
2021-09-26 04:12:57 -05:00
|
|
|
pub(crate) fn unwrap_trivial_block(block_expr: ast::BlockExpr) -> ast::Expr {
|
|
|
|
extract_trivial_expression(&block_expr)
|
2020-08-13 04:41:20 -05:00
|
|
|
.filter(|expr| !expr.syntax().text().contains_char('\n'))
|
2021-09-26 04:12:57 -05:00
|
|
|
.unwrap_or_else(|| block_expr.into())
|
2020-08-13 04:41:20 -05:00
|
|
|
}
|
|
|
|
|
2021-09-26 04:12:57 -05:00
|
|
|
pub fn extract_trivial_expression(block_expr: &ast::BlockExpr) -> Option<ast::Expr> {
|
|
|
|
if block_expr.modifier().is_some() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let stmt_list = block_expr.stmt_list()?;
|
2020-08-13 04:41:20 -05:00
|
|
|
let has_anything_else = |thing: &SyntaxNode| -> bool {
|
|
|
|
let mut non_trivial_children =
|
2021-09-26 04:12:57 -05:00
|
|
|
stmt_list.syntax().children_with_tokens().filter(|it| match it.kind() {
|
2020-08-13 04:41:20 -05:00
|
|
|
WHITESPACE | T!['{'] | T!['}'] => false,
|
|
|
|
_ => it.as_node() != Some(thing),
|
|
|
|
});
|
|
|
|
non_trivial_children.next().is_some()
|
|
|
|
};
|
|
|
|
|
2021-09-26 04:12:57 -05:00
|
|
|
if let Some(expr) = stmt_list.tail_expr() {
|
2020-08-13 04:41:20 -05:00
|
|
|
if has_anything_else(expr.syntax()) {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
return Some(expr);
|
|
|
|
}
|
|
|
|
// Unwrap `{ continue; }`
|
2021-09-26 04:12:57 -05:00
|
|
|
let stmt = stmt_list.statements().next()?;
|
2020-08-13 04:41:20 -05:00
|
|
|
if let ast::Stmt::ExprStmt(expr_stmt) = stmt {
|
|
|
|
if has_anything_else(expr_stmt.syntax()) {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let expr = expr_stmt.expr()?;
|
2021-07-01 17:20:27 -05:00
|
|
|
if matches!(expr.syntax().kind(), CONTINUE_EXPR | BREAK_EXPR | RETURN_EXPR) {
|
|
|
|
return Some(expr);
|
2020-08-13 04:41:20 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2020-11-17 07:22:04 -06:00
|
|
|
/// This is a method with a heuristics to support test methods annotated with custom test annotations, such as
|
|
|
|
/// `#[test_case(...)]`, `#[tokio::test]` and similar.
|
|
|
|
/// Also a regular `#[test]` annotation is supported.
|
|
|
|
///
|
|
|
|
/// It may produce false positives, for example, `#[wasm_bindgen_test]` requires a different command to run the test,
|
|
|
|
/// but it's better than not to have the runnables for the tests at all.
|
|
|
|
pub fn test_related_attribute(fn_def: &ast::Fn) -> Option<ast::Attr> {
|
|
|
|
fn_def.attrs().find_map(|attr| {
|
|
|
|
let path = attr.path()?;
|
2021-09-30 11:01:47 -05:00
|
|
|
let text = path.syntax().text().to_string();
|
|
|
|
if text.starts_with("test") || text.ends_with("test") {
|
|
|
|
Some(attr)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2020-11-17 07:22:04 -06:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-11-05 16:34:50 -06:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
|
|
|
pub enum DefaultMethods {
|
|
|
|
Only,
|
|
|
|
No,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn filter_assoc_items(
|
|
|
|
db: &RootDatabase,
|
|
|
|
items: &[hir::AssocItem],
|
|
|
|
default_methods: DefaultMethods,
|
|
|
|
) -> Vec<ast::AssocItem> {
|
|
|
|
fn has_def_name(item: &ast::AssocItem) -> bool {
|
|
|
|
match item {
|
|
|
|
ast::AssocItem::Fn(def) => def.name(),
|
|
|
|
ast::AssocItem::TypeAlias(def) => def.name(),
|
|
|
|
ast::AssocItem::Const(def) => def.name(),
|
|
|
|
ast::AssocItem::MacroCall(_) => None,
|
|
|
|
}
|
|
|
|
.is_some()
|
2021-01-02 13:48:39 -06:00
|
|
|
}
|
2020-11-05 16:34:50 -06:00
|
|
|
|
|
|
|
items
|
|
|
|
.iter()
|
2020-12-31 23:49:44 -06:00
|
|
|
// Note: This throws away items with no source.
|
|
|
|
.filter_map(|i| {
|
|
|
|
let item = match i {
|
|
|
|
hir::AssocItem::Function(i) => ast::AssocItem::Fn(i.source(db)?.value),
|
|
|
|
hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(i.source(db)?.value),
|
|
|
|
hir::AssocItem::Const(i) => ast::AssocItem::Const(i.source(db)?.value),
|
|
|
|
};
|
|
|
|
Some(item)
|
2020-11-05 16:34:50 -06:00
|
|
|
})
|
|
|
|
.filter(has_def_name)
|
|
|
|
.filter(|it| match it {
|
|
|
|
ast::AssocItem::Fn(def) => matches!(
|
|
|
|
(default_methods, def.body()),
|
|
|
|
(DefaultMethods::Only, Some(_)) | (DefaultMethods::No, None)
|
|
|
|
),
|
|
|
|
_ => default_methods == DefaultMethods::No,
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn add_trait_assoc_items_to_impl(
|
|
|
|
sema: &hir::Semantics<ide_db::RootDatabase>,
|
|
|
|
items: Vec<ast::AssocItem>,
|
|
|
|
trait_: hir::Trait,
|
2021-05-14 10:47:08 -05:00
|
|
|
impl_: ast::Impl,
|
2020-11-05 16:34:50 -06:00
|
|
|
target_scope: hir::SemanticsScope,
|
|
|
|
) -> (ast::Impl, ast::AssocItem) {
|
|
|
|
let source_scope = sema.scope_for_def(trait_);
|
2021-05-18 06:42:41 -05:00
|
|
|
|
2021-08-10 07:39:56 -05:00
|
|
|
let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
|
2021-05-18 06:42:41 -05:00
|
|
|
|
|
|
|
let items = items.into_iter().map(|assoc_item| {
|
|
|
|
let assoc_item = assoc_item.clone_for_update();
|
2021-08-10 07:39:56 -05:00
|
|
|
transform.apply(assoc_item.syntax());
|
2021-08-14 12:38:31 -05:00
|
|
|
assoc_item.remove_attrs_and_docs();
|
2021-08-14 12:17:16 -05:00
|
|
|
assoc_item
|
2021-05-18 06:42:41 -05:00
|
|
|
});
|
2021-05-14 10:47:08 -05:00
|
|
|
|
|
|
|
let res = impl_.clone_for_update();
|
2021-05-14 12:00:35 -05:00
|
|
|
|
2021-05-14 10:47:08 -05:00
|
|
|
let assoc_item_list = res.get_or_create_assoc_item_list();
|
|
|
|
let mut first_item = None;
|
|
|
|
for item in items {
|
2021-05-14 12:00:35 -05:00
|
|
|
first_item.get_or_insert_with(|| item.clone());
|
|
|
|
match &item {
|
|
|
|
ast::AssocItem::Fn(fn_) if fn_.body().is_none() => {
|
2021-05-09 11:51:06 -05:00
|
|
|
let body = make::block_expr(None, Some(make::ext::expr_todo()))
|
|
|
|
.indent(edit::IndentLevel(1));
|
2021-05-14 12:00:35 -05:00
|
|
|
ted::replace(fn_.get_or_create_body().syntax(), body.clone_for_update().syntax())
|
|
|
|
}
|
|
|
|
ast::AssocItem::TypeAlias(type_alias) => {
|
|
|
|
if let Some(type_bound_list) = type_alias.type_bound_list() {
|
|
|
|
type_bound_list.remove()
|
|
|
|
}
|
2020-11-05 16:34:50 -06:00
|
|
|
}
|
2021-05-14 12:00:35 -05:00
|
|
|
_ => {}
|
2020-11-05 16:34:50 -06:00
|
|
|
}
|
2021-05-14 12:00:35 -05:00
|
|
|
|
|
|
|
assoc_item_list.add_item(item)
|
2020-11-05 16:34:50 -06:00
|
|
|
}
|
2021-05-14 12:00:35 -05:00
|
|
|
|
|
|
|
(res, first_item.unwrap())
|
2020-11-05 16:34:50 -06:00
|
|
|
}
|
|
|
|
|
2020-05-19 18:53:21 -05:00
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
pub(crate) enum Cursor<'a> {
|
|
|
|
Replace(&'a SyntaxNode),
|
|
|
|
Before(&'a SyntaxNode),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Cursor<'a> {
|
|
|
|
fn node(self) -> &'a SyntaxNode {
|
|
|
|
match self {
|
|
|
|
Cursor::Replace(node) | Cursor::Before(node) => node,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor) -> String {
|
|
|
|
assert!(cursor.node().ancestors().any(|it| it == *node));
|
|
|
|
let range = cursor.node().text_range() - node.text_range().start();
|
2020-05-19 15:25:07 -05:00
|
|
|
let range: ops::Range<usize> = range.into();
|
|
|
|
|
2020-05-19 18:53:21 -05:00
|
|
|
let mut placeholder = cursor.node().to_string();
|
2020-05-19 15:25:07 -05:00
|
|
|
escape(&mut placeholder);
|
2020-05-19 18:53:21 -05:00
|
|
|
let tab_stop = match cursor {
|
|
|
|
Cursor::Replace(placeholder) => format!("${{0:{}}}", placeholder),
|
|
|
|
Cursor::Before(placeholder) => format!("$0{}", placeholder),
|
|
|
|
};
|
2020-05-19 15:25:07 -05:00
|
|
|
|
|
|
|
let mut buf = node.to_string();
|
|
|
|
buf.replace_range(range, &tab_stop);
|
|
|
|
return buf;
|
|
|
|
|
|
|
|
fn escape(buf: &mut String) {
|
|
|
|
stdx::replace(buf, '{', r"\{");
|
|
|
|
stdx::replace(buf, '}', r"\}");
|
|
|
|
stdx::replace(buf, '$', r"\$");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-28 17:18:50 -05:00
|
|
|
pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize {
|
|
|
|
node.children_with_tokens()
|
|
|
|
.find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR))
|
|
|
|
.map(|it| it.text_range().start())
|
|
|
|
.unwrap_or_else(|| node.text_range().start())
|
|
|
|
}
|
|
|
|
|
2021-08-14 08:40:00 -05:00
|
|
|
pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr {
|
|
|
|
invert_special_case(&expr).unwrap_or_else(|| make::expr_prefix(T![!], expr))
|
2020-02-07 08:57:38 -06:00
|
|
|
}
|
|
|
|
|
2021-08-14 08:40:00 -05:00
|
|
|
fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
|
2020-02-07 08:57:38 -06:00
|
|
|
match expr {
|
2021-08-14 10:24:42 -05:00
|
|
|
ast::Expr::BinExpr(bin) => {
|
|
|
|
let bin = bin.clone_for_update();
|
|
|
|
let op_token = bin.op_token()?;
|
|
|
|
let rev_token = match op_token.kind() {
|
|
|
|
T![==] => T![!=],
|
|
|
|
T![!=] => T![==],
|
|
|
|
T![<] => T![>=],
|
|
|
|
T![<=] => T![>],
|
|
|
|
T![>] => T![<=],
|
|
|
|
T![>=] => T![<],
|
|
|
|
// Parenthesize other expressions before prefixing `!`
|
|
|
|
_ => return Some(make::expr_prefix(T![!], make::expr_paren(expr.clone()))),
|
|
|
|
};
|
|
|
|
ted::replace(op_token, make::token(rev_token));
|
|
|
|
Some(bin.into())
|
|
|
|
}
|
2020-08-23 15:30:07 -05:00
|
|
|
ast::Expr::MethodCallExpr(mce) => {
|
2020-08-25 03:57:51 -05:00
|
|
|
let receiver = mce.receiver()?;
|
|
|
|
let method = mce.name_ref()?;
|
|
|
|
let arg_list = mce.arg_list()?;
|
|
|
|
|
2021-03-26 12:30:59 -05:00
|
|
|
let method = match method.text().as_str() {
|
2020-08-25 03:57:51 -05:00
|
|
|
"is_some" => "is_none",
|
|
|
|
"is_none" => "is_some",
|
|
|
|
"is_ok" => "is_err",
|
|
|
|
"is_err" => "is_ok",
|
|
|
|
_ => return None,
|
|
|
|
};
|
2021-08-07 15:16:15 -05:00
|
|
|
Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
|
2020-08-23 15:30:07 -05:00
|
|
|
}
|
2021-10-03 07:53:01 -05:00
|
|
|
ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
|
|
|
|
ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
|
|
|
|
_ => pe.expr(),
|
|
|
|
},
|
2021-07-06 13:30:26 -05:00
|
|
|
ast::Expr::Literal(lit) => match lit.kind() {
|
|
|
|
ast::LiteralKind::Bool(b) => match b {
|
|
|
|
true => Some(ast::Expr::Literal(make::expr_literal("false"))),
|
|
|
|
false => Some(ast::Expr::Literal(make::expr_literal("true"))),
|
|
|
|
},
|
|
|
|
_ => None,
|
|
|
|
},
|
2020-02-07 08:57:38 -06:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
2020-04-29 03:38:18 -05:00
|
|
|
|
2020-08-19 11:44:33 -05:00
|
|
|
pub(crate) fn next_prev() -> impl Iterator<Item = Direction> {
|
|
|
|
[Direction::Next, Direction::Prev].iter().copied()
|
|
|
|
}
|
2021-01-22 16:31:19 -06:00
|
|
|
|
|
|
|
pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool {
|
|
|
|
let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text());
|
|
|
|
|
|
|
|
let pat_head = match pat {
|
2021-10-03 07:53:01 -05:00
|
|
|
ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
|
|
|
|
Some(p) => first_node_text(&p),
|
|
|
|
None => return pat.syntax().text() == var.syntax().text(),
|
|
|
|
},
|
2021-01-22 16:31:19 -06:00
|
|
|
pat => first_node_text(pat),
|
|
|
|
};
|
|
|
|
|
|
|
|
let var_head = first_node_text(var);
|
|
|
|
|
|
|
|
pat_head == var_head
|
|
|
|
}
|
2021-02-05 07:36:07 -06:00
|
|
|
|
2021-10-13 08:02:39 -05:00
|
|
|
pub(crate) fn does_nested_pattern(pat: &ast::Pat) -> bool {
|
|
|
|
let depth = calc_depth(pat, 0);
|
|
|
|
|
|
|
|
if 1 < depth {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2021-10-13 08:06:53 -05:00
|
|
|
fn calc_depth(pat: &ast::Pat, depth: usize) -> usize {
|
2021-10-13 08:02:39 -05:00
|
|
|
match pat {
|
|
|
|
ast::Pat::IdentPat(_)
|
|
|
|
| ast::Pat::BoxPat(_)
|
|
|
|
| ast::Pat::RestPat(_)
|
|
|
|
| ast::Pat::LiteralPat(_)
|
|
|
|
| ast::Pat::MacroPat(_)
|
|
|
|
| ast::Pat::OrPat(_)
|
|
|
|
| ast::Pat::ParenPat(_)
|
|
|
|
| ast::Pat::PathPat(_)
|
|
|
|
| ast::Pat::WildcardPat(_)
|
|
|
|
| ast::Pat::RangePat(_)
|
|
|
|
| ast::Pat::RecordPat(_)
|
|
|
|
| ast::Pat::RefPat(_)
|
|
|
|
| ast::Pat::SlicePat(_)
|
|
|
|
| ast::Pat::TuplePat(_)
|
2021-10-13 09:07:49 -05:00
|
|
|
| ast::Pat::ConstBlockPat(_) => depth,
|
2021-10-13 08:02:39 -05:00
|
|
|
|
2021-10-13 09:07:49 -05:00
|
|
|
// FIXME: Other patterns may also be nested. Currently it simply supports only `TupleStructPat`
|
2021-10-13 08:02:39 -05:00
|
|
|
ast::Pat::TupleStructPat(pat) => {
|
2021-10-13 08:06:53 -05:00
|
|
|
let mut max_depth = depth;
|
2021-10-13 08:02:39 -05:00
|
|
|
for p in pat.fields() {
|
2021-10-13 08:06:53 -05:00
|
|
|
let d = calc_depth(&p, depth + 1);
|
|
|
|
if d > max_depth {
|
|
|
|
max_depth = d
|
|
|
|
}
|
2021-10-13 08:02:39 -05:00
|
|
|
}
|
2021-10-13 08:06:53 -05:00
|
|
|
max_depth
|
2021-10-13 08:02:39 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-05 07:36:07 -06:00
|
|
|
// Uses a syntax-driven approach to find any impl blocks for the struct that
|
|
|
|
// exist within the module/file
|
|
|
|
//
|
2021-02-05 09:32:34 -06:00
|
|
|
// Returns `None` if we've found an existing fn
|
2021-02-05 07:36:07 -06:00
|
|
|
//
|
|
|
|
// FIXME: change the new fn checking to a more semantic approach when that's more
|
|
|
|
// viable (e.g. we process proc macros, etc)
|
2021-02-12 04:48:43 -06:00
|
|
|
// FIXME: this partially overlaps with `find_impl_block_*`
|
2021-02-05 07:36:07 -06:00
|
|
|
pub(crate) fn find_struct_impl(
|
|
|
|
ctx: &AssistContext,
|
2021-08-14 10:42:06 -05:00
|
|
|
adt: &ast::Adt,
|
2021-02-05 07:36:07 -06:00
|
|
|
name: &str,
|
|
|
|
) -> Option<Option<ast::Impl>> {
|
|
|
|
let db = ctx.db();
|
2021-08-14 10:42:06 -05:00
|
|
|
let module = adt.syntax().parent()?;
|
|
|
|
|
|
|
|
let struct_def = ctx.sema.to_def(adt)?;
|
2021-02-05 07:36:07 -06:00
|
|
|
|
|
|
|
let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
|
|
|
|
let blk = ctx.sema.to_def(&impl_blk)?;
|
|
|
|
|
|
|
|
// FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
|
|
|
|
// (we currently use the wrong type parameter)
|
|
|
|
// also we wouldn't want to use e.g. `impl S<u32>`
|
|
|
|
|
2021-03-29 10:46:33 -05:00
|
|
|
let same_ty = match blk.self_ty(db).as_adt() {
|
2021-02-05 07:36:07 -06:00
|
|
|
Some(def) => def == struct_def,
|
|
|
|
None => false,
|
|
|
|
};
|
2021-03-29 10:46:33 -05:00
|
|
|
let not_trait_impl = blk.trait_(db).is_none();
|
2021-02-05 07:36:07 -06:00
|
|
|
|
|
|
|
if !(same_ty && not_trait_impl) {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(impl_blk)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if let Some(ref impl_blk) = block {
|
|
|
|
if has_fn(impl_blk, name) {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(block)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn has_fn(imp: &ast::Impl, rhs_name: &str) -> bool {
|
|
|
|
if let Some(il) = imp.assoc_item_list() {
|
|
|
|
for item in il.assoc_items() {
|
|
|
|
if let ast::AssocItem::Fn(f) = item {
|
|
|
|
if let Some(name) = f.name() {
|
|
|
|
if name.text().eq_ignore_ascii_case(rhs_name) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
false
|
|
|
|
}
|
2021-02-05 09:32:34 -06:00
|
|
|
|
|
|
|
/// Find the start of the `impl` block for the given `ast::Impl`.
|
|
|
|
//
|
|
|
|
// FIXME: this partially overlaps with `find_struct_impl`
|
2021-02-12 04:48:43 -06:00
|
|
|
pub(crate) fn find_impl_block_start(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
|
2021-02-05 09:32:34 -06:00
|
|
|
buf.push('\n');
|
2021-02-12 04:48:43 -06:00
|
|
|
let start = impl_def.assoc_item_list().and_then(|it| it.l_curly_token())?.text_range().end();
|
|
|
|
Some(start)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Find the end of the `impl` block for the given `ast::Impl`.
|
|
|
|
//
|
|
|
|
// FIXME: this partially overlaps with `find_struct_impl`
|
|
|
|
pub(crate) fn find_impl_block_end(impl_def: ast::Impl, buf: &mut String) -> Option<TextSize> {
|
|
|
|
buf.push('\n');
|
|
|
|
let end = impl_def
|
|
|
|
.assoc_item_list()
|
|
|
|
.and_then(|it| it.r_curly_token())?
|
|
|
|
.prev_sibling_or_token()?
|
2021-02-05 09:32:34 -06:00
|
|
|
.text_range()
|
|
|
|
.end();
|
2021-02-12 04:48:43 -06:00
|
|
|
Some(end)
|
2021-02-05 09:32:34 -06:00
|
|
|
}
|
2021-02-09 05:30:13 -06:00
|
|
|
|
|
|
|
// Generates the surrounding `impl Type { <code> }` including type and lifetime
|
|
|
|
// parameters
|
|
|
|
pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
|
2021-02-13 14:26:58 -06:00
|
|
|
generate_impl_text_inner(adt, None, code)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generates the surrounding `impl <trait> for Type { <code> }` including type
|
|
|
|
// and lifetime parameters
|
|
|
|
pub(crate) fn generate_trait_impl_text(adt: &ast::Adt, trait_text: &str, code: &str) -> String {
|
|
|
|
generate_impl_text_inner(adt, Some(trait_text), code)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str) -> String {
|
2021-02-13 15:59:51 -06:00
|
|
|
let generic_params = adt.generic_param_list();
|
2021-02-09 05:30:13 -06:00
|
|
|
let mut buf = String::with_capacity(code.len());
|
2021-02-13 14:38:52 -06:00
|
|
|
buf.push_str("\n\n");
|
2021-02-13 14:51:48 -06:00
|
|
|
adt.attrs()
|
|
|
|
.filter(|attr| attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false))
|
2021-02-13 14:38:52 -06:00
|
|
|
.for_each(|attr| buf.push_str(format!("{}\n", attr.to_string()).as_str()));
|
|
|
|
buf.push_str("impl");
|
2021-02-13 15:59:51 -06:00
|
|
|
if let Some(generic_params) = &generic_params {
|
|
|
|
let lifetimes = generic_params.lifetime_params().map(|lt| format!("{}", lt.syntax()));
|
|
|
|
let type_params = generic_params.type_params().map(|type_param| {
|
|
|
|
let mut buf = String::new();
|
|
|
|
if let Some(it) = type_param.name() {
|
|
|
|
format_to!(buf, "{}", it.syntax());
|
|
|
|
}
|
|
|
|
if let Some(it) = type_param.colon_token() {
|
|
|
|
format_to!(buf, "{} ", it);
|
|
|
|
}
|
|
|
|
if let Some(it) = type_param.type_bound_list() {
|
|
|
|
format_to!(buf, "{}", it.syntax());
|
|
|
|
}
|
|
|
|
buf
|
|
|
|
});
|
2021-03-27 04:37:39 -05:00
|
|
|
let const_params = generic_params.const_params().map(|t| t.syntax().to_string());
|
|
|
|
let generics = lifetimes.chain(type_params).chain(const_params).format(", ");
|
2021-02-13 15:59:51 -06:00
|
|
|
format_to!(buf, "<{}>", generics);
|
2021-02-09 05:30:13 -06:00
|
|
|
}
|
|
|
|
buf.push(' ');
|
2021-02-13 14:26:58 -06:00
|
|
|
if let Some(trait_text) = trait_text {
|
|
|
|
buf.push_str(trait_text);
|
|
|
|
buf.push_str(" for ");
|
|
|
|
}
|
2021-03-26 12:30:59 -05:00
|
|
|
buf.push_str(&adt.name().unwrap().text());
|
2021-02-13 15:59:51 -06:00
|
|
|
if let Some(generic_params) = generic_params {
|
|
|
|
let lifetime_params = generic_params
|
2021-02-09 05:30:13 -06:00
|
|
|
.lifetime_params()
|
|
|
|
.filter_map(|it| it.lifetime())
|
|
|
|
.map(|it| SmolStr::from(it.text()));
|
2021-02-13 15:59:51 -06:00
|
|
|
let type_params = generic_params
|
|
|
|
.type_params()
|
|
|
|
.filter_map(|it| it.name())
|
|
|
|
.map(|it| SmolStr::from(it.text()));
|
2021-03-27 04:37:39 -05:00
|
|
|
let const_params = generic_params
|
|
|
|
.const_params()
|
|
|
|
.filter_map(|it| it.name())
|
|
|
|
.map(|it| SmolStr::from(it.text()));
|
|
|
|
format_to!(buf, "<{}>", lifetime_params.chain(type_params).chain(const_params).format(", "))
|
2021-02-09 05:30:13 -06:00
|
|
|
}
|
|
|
|
|
2021-02-20 08:05:01 -06:00
|
|
|
match adt.where_clause() {
|
|
|
|
Some(where_clause) => {
|
|
|
|
format_to!(buf, "\n{}\n{{\n{}\n}}", where_clause, code);
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
format_to!(buf, " {{\n{}\n}}", code);
|
|
|
|
}
|
|
|
|
}
|
2021-02-09 05:30:13 -06:00
|
|
|
|
|
|
|
buf
|
|
|
|
}
|
2021-02-15 15:25:33 -06:00
|
|
|
|
|
|
|
pub(crate) fn add_method_to_adt(
|
|
|
|
builder: &mut AssistBuilder,
|
|
|
|
adt: &ast::Adt,
|
|
|
|
impl_def: Option<ast::Impl>,
|
|
|
|
method: &str,
|
|
|
|
) {
|
|
|
|
let mut buf = String::with_capacity(method.len() + 2);
|
|
|
|
if impl_def.is_some() {
|
|
|
|
buf.push('\n');
|
|
|
|
}
|
|
|
|
buf.push_str(method);
|
|
|
|
|
|
|
|
let start_offset = impl_def
|
|
|
|
.and_then(|impl_def| find_impl_block_end(impl_def, &mut buf))
|
|
|
|
.unwrap_or_else(|| {
|
2021-06-12 22:54:16 -05:00
|
|
|
buf = generate_impl_text(adt, &buf);
|
2021-02-15 15:25:33 -06:00
|
|
|
adt.syntax().text_range().end()
|
|
|
|
});
|
|
|
|
|
|
|
|
builder.insert(start_offset, buf);
|
|
|
|
}
|
2021-07-31 06:13:22 -05:00
|
|
|
|
2021-09-29 07:04:32 -05:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub(crate) struct ReferenceConversion {
|
|
|
|
conversion: ReferenceConversionType,
|
|
|
|
ty: hir::Type,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
enum ReferenceConversionType {
|
|
|
|
// reference can be stripped if the type is Copy
|
|
|
|
Copy,
|
|
|
|
// &String -> &str
|
|
|
|
AsRefStr,
|
|
|
|
// &Vec<T> -> &[T]
|
|
|
|
AsRefSlice,
|
|
|
|
// &Box<T> -> &T
|
|
|
|
Dereferenced,
|
|
|
|
// &Option<T> -> Option<&T>
|
|
|
|
Option,
|
|
|
|
// &Result<T, E> -> Result<&T, &E>
|
|
|
|
Result,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ReferenceConversion {
|
|
|
|
pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> String {
|
|
|
|
match self.conversion {
|
|
|
|
ReferenceConversionType::Copy => self.ty.display(db).to_string(),
|
|
|
|
ReferenceConversionType::AsRefStr => "&str".to_string(),
|
|
|
|
ReferenceConversionType::AsRefSlice => {
|
|
|
|
let type_argument_name =
|
|
|
|
self.ty.type_arguments().next().unwrap().display(db).to_string();
|
|
|
|
format!("&[{}]", type_argument_name)
|
|
|
|
}
|
|
|
|
ReferenceConversionType::Dereferenced => {
|
|
|
|
let type_argument_name =
|
|
|
|
self.ty.type_arguments().next().unwrap().display(db).to_string();
|
|
|
|
format!("&{}", type_argument_name)
|
|
|
|
}
|
|
|
|
ReferenceConversionType::Option => {
|
|
|
|
let type_argument_name =
|
|
|
|
self.ty.type_arguments().next().unwrap().display(db).to_string();
|
|
|
|
format!("Option<&{}>", type_argument_name)
|
|
|
|
}
|
|
|
|
ReferenceConversionType::Result => {
|
|
|
|
let mut type_arguments = self.ty.type_arguments();
|
|
|
|
let first_type_argument_name =
|
|
|
|
type_arguments.next().unwrap().display(db).to_string();
|
|
|
|
let second_type_argument_name =
|
|
|
|
type_arguments.next().unwrap().display(db).to_string();
|
|
|
|
format!("Result<&{}, &{}>", first_type_argument_name, second_type_argument_name)
|
|
|
|
}
|
|
|
|
}
|
2021-07-31 06:13:22 -05:00
|
|
|
}
|
2021-09-29 07:04:32 -05:00
|
|
|
|
|
|
|
pub(crate) fn getter(&self, field_name: String) -> String {
|
|
|
|
match self.conversion {
|
|
|
|
ReferenceConversionType::Copy => format!("self.{}", field_name),
|
|
|
|
ReferenceConversionType::AsRefStr
|
|
|
|
| ReferenceConversionType::AsRefSlice
|
|
|
|
| ReferenceConversionType::Dereferenced
|
|
|
|
| ReferenceConversionType::Option
|
|
|
|
| ReferenceConversionType::Result => format!("self.{}.as_ref()", field_name),
|
|
|
|
}
|
2021-07-31 06:13:22 -05:00
|
|
|
}
|
2021-09-29 07:04:32 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME: It should return a new hir::Type, but currently constructing new types is too cumbersome
|
|
|
|
// and all users of this function operate on string type names, so they can do the conversion
|
|
|
|
// itself themselves.
|
|
|
|
pub(crate) fn convert_reference_type(
|
|
|
|
ty: hir::Type,
|
2021-10-20 14:35:35 -05:00
|
|
|
db: &RootDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
2021-09-29 07:04:32 -05:00
|
|
|
) -> Option<ReferenceConversion> {
|
|
|
|
handle_copy(&ty, db)
|
2021-10-20 14:35:35 -05:00
|
|
|
.or_else(|| handle_as_ref_str(&ty, db, famous_defs))
|
2021-09-29 07:04:32 -05:00
|
|
|
.or_else(|| handle_as_ref_slice(&ty, db, famous_defs))
|
|
|
|
.or_else(|| handle_dereferenced(&ty, db, famous_defs))
|
|
|
|
.or_else(|| handle_option_as_ref(&ty, db, famous_defs))
|
|
|
|
.or_else(|| handle_result_as_ref(&ty, db, famous_defs))
|
|
|
|
.map(|conversion| ReferenceConversion { ty, conversion })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_copy(ty: &hir::Type, db: &dyn HirDatabase) -> Option<ReferenceConversionType> {
|
|
|
|
ty.is_copy(db).then(|| ReferenceConversionType::Copy)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_as_ref_str(
|
|
|
|
ty: &hir::Type,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
|
|
|
) -> Option<ReferenceConversionType> {
|
2021-10-20 14:35:35 -05:00
|
|
|
let module = famous_defs.1?.root_module(db);
|
2021-09-29 07:04:32 -05:00
|
|
|
let str_type = hir::BuiltinType::str().ty(db, module);
|
|
|
|
|
|
|
|
ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[str_type])
|
|
|
|
.then(|| ReferenceConversionType::AsRefStr)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_as_ref_slice(
|
|
|
|
ty: &hir::Type,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
|
|
|
) -> Option<ReferenceConversionType> {
|
|
|
|
let type_argument = ty.type_arguments().next()?;
|
2021-10-20 15:35:31 -05:00
|
|
|
let slice_type = hir::Type::new_slice(type_argument);
|
2021-09-29 07:04:32 -05:00
|
|
|
|
|
|
|
ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[slice_type])
|
|
|
|
.then(|| ReferenceConversionType::AsRefSlice)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_dereferenced(
|
|
|
|
ty: &hir::Type,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
|
|
|
) -> Option<ReferenceConversionType> {
|
|
|
|
let type_argument = ty.type_arguments().next()?;
|
|
|
|
|
|
|
|
ty.impls_trait(db, famous_defs.core_convert_AsRef()?, &[type_argument])
|
|
|
|
.then(|| ReferenceConversionType::Dereferenced)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_option_as_ref(
|
|
|
|
ty: &hir::Type,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
|
|
|
) -> Option<ReferenceConversionType> {
|
|
|
|
if ty.as_adt() == famous_defs.core_option_Option()?.ty(db).as_adt() {
|
|
|
|
Some(ReferenceConversionType::Option)
|
|
|
|
} else {
|
|
|
|
None
|
2021-07-31 06:13:22 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-29 07:04:32 -05:00
|
|
|
fn handle_result_as_ref(
|
|
|
|
ty: &hir::Type,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
famous_defs: &FamousDefs,
|
|
|
|
) -> Option<ReferenceConversionType> {
|
|
|
|
if ty.as_adt() == famous_defs.core_result_Result()?.ty(db).as_adt() {
|
|
|
|
Some(ReferenceConversionType::Result)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2021-07-31 06:13:22 -05:00
|
|
|
}
|
2021-07-30 21:15:28 -05:00
|
|
|
|
|
|
|
pub(crate) fn get_methods(items: &ast::AssocItemList) -> Vec<ast::Fn> {
|
|
|
|
items
|
|
|
|
.assoc_items()
|
|
|
|
.flat_map(|i| match i {
|
|
|
|
ast::AssocItem::Fn(f) => Some(f),
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
.filter(|f| f.name().is_some())
|
|
|
|
.collect()
|
|
|
|
}
|
2021-09-27 21:20:29 -05:00
|
|
|
|
|
|
|
/// Trim(remove leading and trailing whitespace) `initial_range` in `source_file`, return the trimmed range.
|
|
|
|
pub(crate) fn trimmed_text_range(source_file: &SourceFile, initial_range: TextRange) -> TextRange {
|
|
|
|
let mut trimmed_range = initial_range;
|
|
|
|
while source_file
|
|
|
|
.syntax()
|
|
|
|
.token_at_offset(trimmed_range.start())
|
|
|
|
.find_map(Whitespace::cast)
|
|
|
|
.is_some()
|
|
|
|
&& trimmed_range.start() < trimmed_range.end()
|
|
|
|
{
|
|
|
|
let start = trimmed_range.start() + TextSize::from(1);
|
|
|
|
trimmed_range = TextRange::new(start, trimmed_range.end());
|
|
|
|
}
|
|
|
|
while source_file
|
|
|
|
.syntax()
|
|
|
|
.token_at_offset(trimmed_range.end())
|
|
|
|
.find_map(Whitespace::cast)
|
|
|
|
.is_some()
|
|
|
|
&& trimmed_range.start() < trimmed_range.end()
|
|
|
|
{
|
|
|
|
let end = trimmed_range.end() - TextSize::from(1);
|
|
|
|
trimmed_range = TextRange::new(trimmed_range.start(), end);
|
|
|
|
}
|
|
|
|
trimmed_range
|
|
|
|
}
|
2021-10-14 11:19:20 -05:00
|
|
|
|
|
|
|
/// Convert a list of function params to a list of arguments that can be passed
|
|
|
|
/// into a function call.
|
|
|
|
pub(crate) fn convert_param_list_to_arg_list(list: ast::ParamList) -> ast::ArgList {
|
|
|
|
let mut args = vec![];
|
|
|
|
for param in list.params() {
|
|
|
|
if let Some(ast::Pat::IdentPat(pat)) = param.pat() {
|
|
|
|
if let Some(name) = pat.name() {
|
|
|
|
let name = name.to_string();
|
|
|
|
let expr = make::expr_path(make::ext::ident_path(&name));
|
|
|
|
args.push(expr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
make::arg_list(args)
|
|
|
|
}
|