755 lines
23 KiB
Rust
Raw Normal View History

2020-04-23 18:22:33 +02:00
//! Completion for attributes
//!
//! This module uses a bit of static metadata to provide completions
//! for built-in attributes.
2021-05-27 23:28:14 +02:00
use once_cell::sync::Lazy;
use rustc_hash::{FxHashMap, FxHashSet};
use syntax::{ast, AstNode, SyntaxKind, T};
2020-04-23 18:22:33 +02:00
use crate::{
2020-10-25 10:59:15 +03:00
context::CompletionContext,
generated_lint_completions::{CLIPPY_LINTS, FEATURES},
item::{CompletionItem, CompletionItemKind, CompletionKind},
Completions,
2020-05-04 15:07:51 +02:00
};
mod derive;
mod lint;
pub(crate) use self::lint::LintCompletion;
2020-10-25 10:59:15 +03:00
pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
2020-05-01 03:46:17 +03:00
let attribute = ctx.attribute_under_caret.as_ref()?;
2021-05-27 23:28:14 +02:00
match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) {
(Some(path), Some(token_tree)) => match path.text().as_str() {
"derive" => derive::complete_derive(acc, ctx, token_tree),
"feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES),
2021-05-27 23:28:14 +02:00
"allow" | "warn" | "deny" | "forbid" => {
lint::complete_lint(acc, ctx, token_tree.clone(), lint::DEFAULT_LINT_COMPLETIONS);
lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS);
2021-01-07 22:48:54 +01:00
}
2021-05-27 23:28:14 +02:00
_ => (),
},
(None, Some(_)) => (),
_ => complete_new_attribute(acc, ctx, attribute),
2020-05-01 03:46:17 +03:00
}
Some(())
}
2020-04-23 18:22:33 +02:00
2021-05-27 23:28:14 +02:00
fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
let attribute_annotated_item_kind = attribute.syntax().parent().map(|it| it.kind());
let attributes = attribute_annotated_item_kind.and_then(|kind| {
if ast::Expr::can_cast(kind) {
Some(EXPR_ATTRIBUTES)
} else {
KIND_TO_ATTRIBUTES.get(&kind).copied()
}
});
let is_inner = attribute.kind() == ast::AttrKind::Inner;
2021-05-27 23:28:14 +02:00
let add_completion = |attr_completion: &AttrCompletion| {
2020-04-23 18:22:33 +02:00
let mut item = CompletionItem::new(
CompletionKind::Attribute,
ctx.source_range(),
attr_completion.label,
);
item.kind(CompletionItemKind::Attribute);
2020-04-23 18:22:33 +02:00
if let Some(lookup) = attr_completion.lookup {
item.lookup_by(lookup);
}
2021-01-07 22:48:54 +01:00
if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
item.insert_snippet(cap, snippet);
2020-04-23 18:22:33 +02:00
}
2021-05-27 23:28:14 +02:00
if is_inner || !attr_completion.prefer_inner {
acc.add(item.build());
2020-04-23 18:22:33 +02:00
}
2021-05-27 23:28:14 +02:00
};
match attributes {
Some(applicable) => applicable
.iter()
.flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
.flat_map(|idx| ATTRIBUTES.get(idx))
.for_each(add_completion),
None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
2020-04-23 18:22:33 +02:00
}
}
struct AttrCompletion {
label: &'static str,
lookup: Option<&'static str>,
2020-04-23 18:22:33 +02:00
snippet: Option<&'static str>,
2020-07-03 15:38:20 +02:00
prefer_inner: bool,
}
impl AttrCompletion {
2021-05-27 23:28:14 +02:00
fn key(&self) -> &'static str {
self.lookup.unwrap_or(self.label)
}
2020-07-03 15:38:20 +02:00
const fn prefer_inner(self) -> AttrCompletion {
AttrCompletion { prefer_inner: true, ..self }
}
}
const fn attr(
label: &'static str,
lookup: Option<&'static str>,
snippet: Option<&'static str>,
) -> AttrCompletion {
AttrCompletion { label, lookup, snippet, prefer_inner: false }
2020-04-23 18:22:33 +02:00
}
2021-05-27 23:28:14 +02:00
macro_rules! attrs {
2021-05-28 00:35:21 +02:00
[@ { item $($tt:tt)* } {$($acc:tt)*}] => {
attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
};
[@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
};
[@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" }) };
[@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => { compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
};
[@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
attrs!(@ { $($tt)* } { $($acc)*, $lit })
};
[@ {$($tt:tt)+} {$($tt2:tt)*}] => {
compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
};
[@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
[$($tt:tt),*] => {
attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
2021-05-27 23:28:14 +02:00
};
}
2021-05-28 00:35:21 +02:00
#[rustfmt::skip]
2021-05-27 23:28:14 +02:00
static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
std::array::IntoIter::new([
2021-05-28 00:35:21 +02:00
(
SyntaxKind::SOURCE_FILE,
attrs!(
item,
"crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
"recursion_limit", "type_length_limit", "windows_subsystem"
),
),
(SyntaxKind::MODULE, attrs!(item, "no_implicit_prelude", "path")),
(SyntaxKind::ITEM_LIST, attrs!(item, "no_implicit_prelude")),
(SyntaxKind::MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
(SyntaxKind::MACRO_DEF, attrs!(item)),
(SyntaxKind::EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
(SyntaxKind::USE, attrs!(item)),
(SyntaxKind::TYPE_ALIAS, attrs!(item)),
(SyntaxKind::STRUCT, attrs!(item, adt, "non_exhaustive")),
(SyntaxKind::ENUM, attrs!(item, adt, "non_exhaustive")),
(SyntaxKind::UNION, attrs!(item, adt)),
(SyntaxKind::CONST, attrs!(item)),
(
SyntaxKind::FN,
attrs!(
item, linkable,
"cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
"proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
"test", "track_caller"
),
),
(SyntaxKind::STATIC, attrs!(item, linkable, "global_allocator", "used")),
(SyntaxKind::TRAIT, attrs!(item, "must_use")),
(SyntaxKind::IMPL, attrs!(item, "automatically_derived")),
(SyntaxKind::ASSOC_ITEM_LIST, attrs!(item)),
(SyntaxKind::EXTERN_BLOCK, attrs!(item, "link")),
(SyntaxKind::EXTERN_ITEM_LIST, attrs!(item, "link")),
2021-05-27 23:28:14 +02:00
(SyntaxKind::MACRO_CALL, attrs!()),
(SyntaxKind::SELF_PARAM, attrs!()),
(SyntaxKind::PARAM, attrs!()),
(SyntaxKind::RECORD_FIELD, attrs!()),
2021-05-28 00:35:21 +02:00
(SyntaxKind::VARIANT, attrs!("non_exhaustive")),
2021-05-27 23:28:14 +02:00
(SyntaxKind::TYPE_PARAM, attrs!()),
(SyntaxKind::CONST_PARAM, attrs!()),
(SyntaxKind::LIFETIME_PARAM, attrs!()),
(SyntaxKind::LET_STMT, attrs!()),
(SyntaxKind::EXPR_STMT, attrs!()),
(SyntaxKind::LITERAL, attrs!()),
(SyntaxKind::RECORD_EXPR_FIELD_LIST, attrs!()),
(SyntaxKind::RECORD_EXPR_FIELD, attrs!()),
(SyntaxKind::MATCH_ARM_LIST, attrs!()),
(SyntaxKind::MATCH_ARM, attrs!()),
(SyntaxKind::IDENT_PAT, attrs!()),
(SyntaxKind::RECORD_PAT_FIELD, attrs!()),
])
.collect()
});
const EXPR_ATTRIBUTES: &[&str] = attrs!();
2020-12-05 22:23:13 +01:00
/// https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index
2021-05-27 23:28:14 +02:00
// Keep these sorted for the binary search!
2020-04-23 18:22:33 +02:00
const ATTRIBUTES: &[AttrCompletion] = &[
2020-07-03 15:38:20 +02:00
attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
2020-12-05 22:23:13 +01:00
attr("automatically_derived", None, None),
2020-07-03 15:38:20 +02:00
attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
2021-05-27 23:28:14 +02:00
attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
2020-12-05 22:23:13 +01:00
attr("cold", None, None),
attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
.prefer_inner(),
2020-07-03 15:38:20 +02:00
attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
2021-01-06 11:07:57 +01:00
attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
2020-07-03 15:38:20 +02:00
attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
2021-05-27 23:28:14 +02:00
attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
2020-12-05 22:23:13 +01:00
attr(
r#"export_name = "…""#,
Some("export_name"),
Some(r#"export_name = "${0:exported_symbol_name}""#),
),
2020-07-03 15:38:20 +02:00
attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
2020-04-23 18:22:33 +02:00
// FIXME: resolve through macro resolution?
2020-07-03 15:38:20 +02:00
attr("global_allocator", None, None).prefer_inner(),
2020-07-12 11:17:15 +03:00
attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
attr("inline", Some("inline"), Some("inline")),
2020-07-03 15:38:20 +02:00
attr("link", None, None),
2020-12-05 22:23:13 +01:00
attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
attr(
r#"link_section = "…""#,
Some("link_section"),
Some(r#"link_section = "${0:section_name}""#),
),
2020-07-03 15:38:20 +02:00
attr("macro_export", None, None),
attr("macro_use", None, None),
attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
2020-12-05 22:23:13 +01:00
attr("no_implicit_prelude", None, None).prefer_inner(),
2021-05-27 23:28:14 +02:00
attr("no_link", None, None).prefer_inner(),
2020-12-05 22:23:13 +01:00
attr("no_main", None, None).prefer_inner(),
2020-07-03 15:38:20 +02:00
attr("no_mangle", None, None),
attr("no_std", None, None).prefer_inner(),
attr("non_exhaustive", None, None),
attr("panic_handler", None, None).prefer_inner(),
2020-12-05 22:23:13 +01:00
attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
2020-07-03 15:38:20 +02:00
attr("proc_macro", None, None),
attr("proc_macro_attribute", None, None),
attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
attr("recursion_limit = …", Some("recursion_limit"), Some("recursion_limit = ${0:128}"))
.prefer_inner(),
attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
2020-07-03 15:38:20 +02:00
attr(
r#"target_feature = "…""#,
Some("target_feature"),
2020-12-05 22:23:13 +01:00
Some(r#"target_feature = "${0:feature}""#),
2020-07-03 15:38:20 +02:00
),
attr("test", None, None),
2020-12-05 22:23:13 +01:00
attr("track_caller", None, None),
attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
.prefer_inner(),
2020-07-03 15:38:20 +02:00
attr("used", None, None),
attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
attr(
r#"windows_subsystem = "…""#,
Some("windows_subsystem"),
Some(r#"windows_subsystem = "${0:subsystem}""#),
)
.prefer_inner(),
2020-04-23 18:22:33 +02:00
];
2021-05-27 23:28:14 +02:00
#[test]
fn attributes_are_sorted() {
let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
let mut prev = attrs.next().unwrap();
attrs.for_each(|next| {
assert!(
prev < next,
r#"Attributes are not sorted, "{}" should come after "{}""#,
prev,
next
);
prev = next;
});
}
2020-07-27 01:49:17 +02:00
fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> {
2020-05-01 03:46:17 +03:00
match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) {
(Some(left_paren), Some(right_paren))
if left_paren.kind() == T!['('] && right_paren.kind() == T![')'] =>
2020-05-01 03:46:17 +03:00
{
2020-05-02 23:45:44 +03:00
let mut input_derives = FxHashSet::default();
let mut current_derive = String::new();
for token in derive_input
2020-05-01 03:46:17 +03:00
.syntax()
.children_with_tokens()
2020-05-02 23:45:44 +03:00
.filter_map(|token| token.into_token())
.skip_while(|token| token != &left_paren)
.skip(1)
.take_while(|token| token != &right_paren)
{
if T![,] == token.kind() {
2020-05-02 23:45:44 +03:00
if !current_derive.is_empty() {
input_derives.insert(current_derive);
current_derive = String::new();
}
} else {
current_derive.push_str(token.text().trim());
2020-05-02 23:45:44 +03:00
}
}
if !current_derive.is_empty() {
input_derives.insert(current_derive);
}
Ok(input_derives)
2020-05-01 03:46:17 +03:00
}
_ => Err(()),
}
}
2020-04-23 18:22:33 +02:00
#[cfg(test)]
mod tests {
2020-08-21 13:19:31 +02:00
use expect_test::{expect, Expect};
2020-04-23 18:22:33 +02:00
use crate::{test_utils::completion_list, CompletionKind};
2020-07-03 15:46:37 +02:00
fn check(ra_fixture: &str, expect: Expect) {
let actual = completion_list(ra_fixture, CompletionKind::Attribute);
expect.assert_eq(&actual);
2020-04-23 18:22:33 +02:00
}
2021-05-28 01:09:22 +02:00
#[test]
fn test_attribute_completion_inside_nested_attr() {
check(r#"#[cfg($0)]"#, expect![[]])
}
#[test]
fn test_attribute_completion_with_existing_attr() {
check(
r#"#[no_mangle] #[$0] mcall!();"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
"#]],
)
}
2021-05-28 00:54:52 +02:00
#[test]
fn complete_attribute_on_source_file() {
check(
r#"#![$0]"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at crate_name = ""
at feature()
at no_implicit_prelude
at no_main
at no_std
at recursion_limit =
at type_length_limit =
at windows_subsystem = ""
"#]],
);
}
#[test]
fn complete_attribute_on_module() {
check(
r#"#[$0] mod foo;"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at path = ""
"#]],
);
check(
r#"mod foo {#![$0]}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at no_implicit_prelude
"#]],
);
}
#[test]
fn complete_attribute_on_macro_rules() {
check(
r#"#[$0] macro_rules! foo {}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at macro_export
at macro_use
"#]],
);
}
#[test]
fn complete_attribute_on_macro_def() {
check(
r#"#[$0] macro foo {}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
"#]],
);
}
#[test]
fn complete_attribute_on_extern_crate() {
check(
r#"#[$0] extern crate foo;"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at macro_use
"#]],
);
}
#[test]
fn complete_attribute_on_use() {
check(
r#"#[$0] use foo;"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
"#]],
);
}
#[test]
fn complete_attribute_on_type_alias() {
check(
r#"#[$0] type foo = ();"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
"#]],
);
}
2021-05-27 23:28:14 +02:00
#[test]
fn complete_attribute_on_struct() {
check(
2021-05-28 00:54:52 +02:00
r#"#[$0] struct Foo;"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at derive()
at repr()
at non_exhaustive
"#]],
);
}
#[test]
fn complete_attribute_on_enum() {
check(
r#"#[$0] enum Foo {}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at derive()
at repr()
at non_exhaustive
"#]],
);
}
#[test]
fn complete_attribute_on_const() {
check(
r#"#[$0] const FOO: () = ();"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
"#]],
);
}
#[test]
fn complete_attribute_on_static() {
check(
r#"#[$0] static FOO: () = ()"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at export_name = ""
at link_name = ""
at link_section = ""
at used
"#]],
);
}
#[test]
fn complete_attribute_on_trait() {
check(
r#"#[$0] trait Foo {}"#,
2021-05-27 23:28:14 +02:00
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
2021-05-28 00:54:52 +02:00
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
2021-05-27 23:28:14 +02:00
at must_use
"#]],
);
}
2021-05-28 00:54:52 +02:00
#[test]
fn complete_attribute_on_impl() {
check(
r#"#[$0] impl () {}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at automatically_derived
"#]],
);
check(
r#"impl () {#![$0]}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
"#]],
);
}
#[test]
fn complete_attribute_on_extern_block() {
check(
r#"#[$0] extern {}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at link
"#]],
);
check(
r#"extern {#![$0]}"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at deprecated
at doc = ""
at doc(hidden)
at doc(alias = "")
at must_use
at no_mangle
at link
"#]],
);
}
#[test]
fn complete_attribute_on_variant() {
check(
r#"enum Foo { #[$0] Bar }"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
at non_exhaustive
"#]],
);
}
#[test]
fn complete_attribute_on_expr() {
check(
r#"fn main() { #[$0] foo() }"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
"#]],
);
check(
r#"fn main() { #[$0] foo(); }"#,
expect![[r#"
at allow()
at cfg()
at cfg_attr()
at deny()
at forbid()
at warn()
"#]],
);
}
2020-04-23 18:22:33 +02:00
}