3108: Magic Completion for `impl Trait for` Associated Items r=matklad a=kdelorey

# Summary
This PR adds a set of magic completions to auto complete associated trait items (functions/consts/types). 

![Associated Trait Impl](https://user-images.githubusercontent.com/2295721/74493144-d8f1af00-4e96-11ea-93a4-82725bf89646.gif)

## Notes
Since the assist and completion share the same logic when figuring out the associated items that are missing, a shared utility was created in the `ra_assists::utils` module.

Resolves #1046 

As this is my first PR to the rust-analyzer project, I'm new to the codebase, feedback welcomed!

Co-authored-by: Kevin DeLorey <2295721+kdelorey@users.noreply.github.com>
This commit is contained in:
bors[bot] 2020-02-17 09:34:08 +00:00 committed by GitHub
commit 8d8d542dfa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 536 additions and 36 deletions

View File

@ -1,4 +1,4 @@
use hir::{db::HirDatabase, HasSource, InFile};
use hir::{HasSource, InFile};
use ra_syntax::{
ast::{self, edit, make, AstNode, NameOwner},
SmolStr,
@ -6,6 +6,7 @@
use crate::{
ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams},
utils::{get_missing_impl_items, resolve_target_trait},
Assist, AssistCtx, AssistId,
};
@ -103,11 +104,9 @@ fn add_missing_impl_members_inner(
let impl_node = ctx.find_node_at_offset::<ast::ImplBlock>()?;
let impl_item_list = impl_node.item_list()?;
let (trait_, trait_def) = {
let analyzer = ctx.source_analyzer(impl_node.syntax(), None);
let analyzer = ctx.source_analyzer(impl_node.syntax(), None);
resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
};
let trait_ = resolve_target_trait(ctx.db, &analyzer, &impl_node)?;
let def_name = |item: &ast::ImplItem| -> Option<SmolStr> {
match item {
@ -118,11 +117,14 @@ fn add_missing_impl_members_inner(
.map(|it| it.text().clone())
};
let trait_items = trait_def.item_list()?.impl_items();
let impl_items = impl_item_list.impl_items().collect::<Vec<_>>();
let missing_items: Vec<_> = trait_items
.filter(|t| def_name(t).is_some())
let missing_items = get_missing_impl_items(ctx.db, &analyzer, &impl_node)
.iter()
.map(|i| match i {
hir::AssocItem::Function(i) => ast::ImplItem::FnDef(i.source(ctx.db).value),
hir::AssocItem::TypeAlias(i) => ast::ImplItem::TypeAliasDef(i.source(ctx.db).value),
hir::AssocItem::Const(i) => ast::ImplItem::ConstDef(i.source(ctx.db).value),
})
.filter(|t| def_name(&t).is_some())
.filter(|t| match t {
ast::ImplItem::FnDef(def) => match mode {
AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(),
@ -130,8 +132,8 @@ fn add_missing_impl_members_inner(
},
_ => mode == AddMissingImplMembersMode::NoDefaultMethods,
})
.filter(|t| impl_items.iter().all(|i| def_name(i) != def_name(t)))
.collect();
.collect::<Vec<_>>();
if missing_items.is_empty() {
return None;
}
@ -177,27 +179,6 @@ fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
}
}
/// Given an `ast::ImplBlock`, resolves the target trait (the one being
/// implemented) to a `ast::TraitDef`.
fn resolve_target_trait_def(
db: &impl HirDatabase,
analyzer: &hir::SourceAnalyzer,
impl_block: &ast::ImplBlock,
) -> Option<(hir::Trait, ast::TraitDef)> {
let ast_path = impl_block
.target_trait()
.map(|it| it.syntax().clone())
.and_then(ast::PathType::cast)?
.path()?;
match analyzer.resolve_path(db, &ast_path) {
Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => {
Some((def, def.source(db).value))
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -9,7 +9,7 @@
mod marks;
#[cfg(test)]
mod doc_tests;
mod utils;
pub mod utils;
pub mod ast_transform;
use ra_db::FileRange;

View File

@ -1,10 +1,81 @@
//! Assorted functions shared by several assists.
use ra_syntax::{
ast::{self, make},
T,
ast::{self, make, NameOwner},
AstNode, T,
};
use hir::db::HirDatabase;
use rustc_hash::FxHashSet;
pub fn get_missing_impl_items(
db: &impl HirDatabase,
analyzer: &hir::SourceAnalyzer,
impl_block: &ast::ImplBlock,
) -> Vec<hir::AssocItem> {
// Names must be unique between constants and functions. However, type aliases
// may share the same name as a function or constant.
let mut impl_fns_consts = FxHashSet::default();
let mut impl_type = FxHashSet::default();
if let Some(item_list) = impl_block.item_list() {
for item in item_list.impl_items() {
match item {
ast::ImplItem::FnDef(f) => {
if let Some(n) = f.name() {
impl_fns_consts.insert(n.syntax().to_string());
}
}
ast::ImplItem::TypeAliasDef(t) => {
if let Some(n) = t.name() {
impl_type.insert(n.syntax().to_string());
}
}
ast::ImplItem::ConstDef(c) => {
if let Some(n) = c.name() {
impl_fns_consts.insert(n.syntax().to_string());
}
}
}
}
}
resolve_target_trait(db, analyzer, impl_block).map_or(vec![], |target_trait| {
target_trait
.items(db)
.iter()
.filter(|i| match i {
hir::AssocItem::Function(f) => !impl_fns_consts.contains(&f.name(db).to_string()),
hir::AssocItem::TypeAlias(t) => !impl_type.contains(&t.name(db).to_string()),
hir::AssocItem::Const(c) => c
.name(db)
.map(|n| !impl_fns_consts.contains(&n.to_string()))
.unwrap_or_default(),
})
.cloned()
.collect()
})
}
pub(crate) fn resolve_target_trait(
db: &impl HirDatabase,
analyzer: &hir::SourceAnalyzer,
impl_block: &ast::ImplBlock,
) -> Option<hir::Trait> {
let ast_path = impl_block
.target_trait()
.map(|it| it.syntax().clone())
.and_then(ast::PathType::cast)?
.path()?;
match analyzer.resolve_path(db, &ast_path) {
Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def),
_ => None,
}
}
pub(crate) fn invert_boolean_expression(expr: ast::Expr) -> ast::Expr {
if let Some(expr) = invert_special_case(&expr) {
return expr;

View File

@ -15,6 +15,7 @@
mod complete_scope;
mod complete_postfix;
mod complete_macro_in_item_position;
mod complete_trait_impl;
use ra_db::SourceDatabase;
use ra_ide_db::RootDatabase;
@ -74,5 +75,7 @@ pub(crate) fn completions(db: &RootDatabase, position: FilePosition) -> Option<C
complete_pattern::complete_pattern(&mut acc, &ctx);
complete_postfix::complete_postfix(&mut acc, &ctx);
complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
complete_trait_impl::complete_trait_impl(&mut acc, &ctx);
Some(acc)
}

View File

@ -0,0 +1,436 @@
//! Completion for associated items in a trait implementation.
//!
//! This module adds the completion items related to implementing associated
//! items within a `impl Trait for Struct` block. The current context node
//! must be within either a `FN_DEF`, `TYPE_ALIAS_DEF`, or `CONST_DEF` node
//! and an direct child of an `IMPL_BLOCK`.
//!
//! # Examples
//!
//! Considering the following trait `impl`:
//!
//! ```ignore
//! trait SomeTrait {
//! fn foo();
//! }
//!
//! impl SomeTrait for () {
//! fn f<|>
//! }
//! ```
//!
//! may result in the completion of the following method:
//!
//! ```ignore
//! # trait SomeTrait {
//! # fn foo();
//! # }
//!
//! impl SomeTrait for () {
//! fn foo() {}<|>
//! }
//! ```
use hir::{self, Docs, HasSource};
use ra_assists::utils::get_missing_impl_items;
use ra_syntax::{
ast::{self, edit},
AstNode, SyntaxKind, SyntaxNode, TextRange,
};
use ra_text_edit::TextEdit;
use crate::{
completion::{
CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
},
display::FunctionSignature,
};
pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
let trigger = ctx.token.ancestors().find(|p| match p.kind() {
SyntaxKind::FN_DEF
| SyntaxKind::TYPE_ALIAS_DEF
| SyntaxKind::CONST_DEF
| SyntaxKind::BLOCK_EXPR => true,
_ => false,
});
let impl_block = trigger
.as_ref()
.and_then(|node| node.parent())
.and_then(|node| node.parent())
.and_then(|node| ast::ImplBlock::cast(node));
if let (Some(trigger), Some(impl_block)) = (trigger, impl_block) {
match trigger.kind() {
SyntaxKind::FN_DEF => {
for missing_fn in get_missing_impl_items(ctx.db, &ctx.analyzer, &impl_block)
.iter()
.filter_map(|item| match item {
hir::AssocItem::Function(fn_item) => Some(fn_item),
_ => None,
})
{
add_function_impl(&trigger, acc, ctx, &missing_fn);
}
}
SyntaxKind::TYPE_ALIAS_DEF => {
for missing_fn in get_missing_impl_items(ctx.db, &ctx.analyzer, &impl_block)
.iter()
.filter_map(|item| match item {
hir::AssocItem::TypeAlias(type_item) => Some(type_item),
_ => None,
})
{
add_type_alias_impl(&trigger, acc, ctx, &missing_fn);
}
}
SyntaxKind::CONST_DEF => {
for missing_fn in get_missing_impl_items(ctx.db, &ctx.analyzer, &impl_block)
.iter()
.filter_map(|item| match item {
hir::AssocItem::Const(const_item) => Some(const_item),
_ => None,
})
{
add_const_impl(&trigger, acc, ctx, &missing_fn);
}
}
_ => {}
}
}
}
fn add_function_impl(
fn_def_node: &SyntaxNode,
acc: &mut Completions,
ctx: &CompletionContext,
func: &hir::Function,
) {
let display = FunctionSignature::from_hir(ctx.db, func.clone());
let fn_name = func.name(ctx.db).to_string();
let label = if func.params(ctx.db).len() > 0 {
format!("fn {}(..)", fn_name)
} else {
format!("fn {}()", fn_name)
};
let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label.clone())
.lookup_by(fn_name)
.set_documentation(func.docs(ctx.db));
let completion_kind = if func.has_self_param(ctx.db) {
CompletionItemKind::Method
} else {
CompletionItemKind::Function
};
let snippet = format!("{} {{}}", display);
let range = TextRange::from_to(fn_def_node.text_range().start(), ctx.source_range().end());
builder.text_edit(TextEdit::replace(range, snippet)).kind(completion_kind).add_to(acc);
}
fn add_type_alias_impl(
type_def_node: &SyntaxNode,
acc: &mut Completions,
ctx: &CompletionContext,
type_alias: &hir::TypeAlias,
) {
let alias_name = type_alias.name(ctx.db).to_string();
let snippet = format!("type {} = ", alias_name);
let range = TextRange::from_to(type_def_node.text_range().start(), ctx.source_range().end());
CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
.text_edit(TextEdit::replace(range, snippet))
.lookup_by(alias_name)
.kind(CompletionItemKind::TypeAlias)
.set_documentation(type_alias.docs(ctx.db))
.add_to(acc);
}
fn add_const_impl(
const_def_node: &SyntaxNode,
acc: &mut Completions,
ctx: &CompletionContext,
const_: &hir::Const,
) {
let const_name = const_.name(ctx.db).map(|n| n.to_string());
if let Some(const_name) = const_name {
let snippet = make_const_compl_syntax(&const_.source(ctx.db).value);
let range =
TextRange::from_to(const_def_node.text_range().start(), ctx.source_range().end());
CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
.text_edit(TextEdit::replace(range, snippet))
.lookup_by(const_name)
.kind(CompletionItemKind::Const)
.set_documentation(const_.docs(ctx.db))
.add_to(acc);
}
}
fn make_const_compl_syntax(const_: &ast::ConstDef) -> String {
let const_ = edit::strip_attrs_and_docs(const_);
let const_start = const_.syntax().text_range().start();
let const_end = const_.syntax().text_range().end();
let start =
const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
let end = const_
.syntax()
.children_with_tokens()
.find(|s| s.kind() == SyntaxKind::SEMI || s.kind() == SyntaxKind::EQ)
.map_or(const_end, |f| f.text_range().start());
let len = end - start;
let range = TextRange::from_to(0.into(), len);
let syntax = const_.syntax().text().slice(range).to_string();
format!("{} = ", syntax.trim_end())
}
#[cfg(test)]
mod tests {
use crate::completion::{do_completion, CompletionItem, CompletionKind};
use insta::assert_debug_snapshot;
fn complete(code: &str) -> Vec<CompletionItem> {
do_completion(code, CompletionKind::Magic)
}
#[test]
fn single_function() {
let completions = complete(
r"
trait Test {
fn foo();
}
struct T1;
impl Test for T1 {
fn f<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "fn foo()",
source_range: [141; 142),
delete: [138; 142),
insert: "fn foo() {}",
kind: Function,
lookup: "foo",
},
]
"###);
}
#[test]
fn hide_implemented_fn() {
let completions = complete(
r"
trait Test {
fn foo();
fn foo_bar();
}
struct T1;
impl Test for T1 {
fn foo() {}
fn f<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "fn foo_bar()",
source_range: [200; 201),
delete: [197; 201),
insert: "fn foo_bar() {}",
kind: Function,
lookup: "foo_bar",
},
]
"###);
}
#[test]
fn completes_only_on_top_level() {
let completions = complete(
r"
trait Test {
fn foo();
fn foo_bar();
}
struct T1;
impl Test for T1 {
fn foo() {
<|>
}
}
",
);
assert_debug_snapshot!(completions, @r###"[]"###);
}
#[test]
fn generic_fn() {
let completions = complete(
r"
trait Test {
fn foo<T>();
}
struct T1;
impl Test for T1 {
fn f<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "fn foo()",
source_range: [144; 145),
delete: [141; 145),
insert: "fn foo<T>() {}",
kind: Function,
lookup: "foo",
},
]
"###);
}
#[test]
fn generic_constrait_fn() {
let completions = complete(
r"
trait Test {
fn foo<T>() where T: Into<String>;
}
struct T1;
impl Test for T1 {
fn f<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "fn foo()",
source_range: [166; 167),
delete: [163; 167),
insert: "fn foo<T>()\nwhere T: Into<String> {}",
kind: Function,
lookup: "foo",
},
]
"###);
}
#[test]
fn associated_type() {
let completions = complete(
r"
trait Test {
type SomeType;
}
impl Test for () {
type S<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "type SomeType = ",
source_range: [124; 125),
delete: [119; 125),
insert: "type SomeType = ",
kind: TypeAlias,
lookup: "SomeType",
},
]
"###);
}
#[test]
fn associated_const() {
let completions = complete(
r"
trait Test {
const SOME_CONST: u16;
}
impl Test for () {
const S<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "const SOME_CONST: u16 = ",
source_range: [133; 134),
delete: [127; 134),
insert: "const SOME_CONST: u16 = ",
kind: Const,
lookup: "SOME_CONST",
},
]
"###);
}
#[test]
fn associated_const_with_default() {
let completions = complete(
r"
trait Test {
const SOME_CONST: u16 = 42;
}
impl Test for () {
const S<|>
}
",
);
assert_debug_snapshot!(completions, @r###"
[
CompletionItem {
label: "const SOME_CONST: u16 = ",
source_range: [138; 139),
delete: [132; 139),
insert: "const SOME_CONST: u16 = ",
kind: Const,
lookup: "SOME_CONST",
},
]
"###);
}
}

View File

@ -25,6 +25,7 @@ pub(crate) struct CompletionContext<'a> {
pub(super) use_item_syntax: Option<ast::UseItem>,
pub(super) record_lit_syntax: Option<ast::RecordLit>,
pub(super) record_lit_pat: Option<ast::RecordPat>,
pub(super) impl_block: Option<ast::ImplBlock>,
pub(super) is_param: bool,
/// If a name-binding or reference to a const in a pattern.
/// Irrefutable patterns (like let) are excluded.
@ -72,6 +73,7 @@ pub(super) fn new(
use_item_syntax: None,
record_lit_syntax: None,
record_lit_pat: None,
impl_block: None,
is_param: false,
is_pat_binding: false,
is_trivial_path: false,
@ -148,6 +150,13 @@ fn classify_name_ref(&mut self, original_file: SourceFile, name_ref: ast::NameRe
self.record_lit_syntax = find_node_at_offset(original_file.syntax(), self.offset);
}
self.impl_block = self
.token
.parent()
.ancestors()
.take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
.find_map(ast::ImplBlock::cast);
let top_node = name_ref
.syntax()
.ancestors()