1 //! Completion for attributes
3 //! This module uses a bit of static metadata to provide completions
4 //! for built-in attributes.
7 use ide_db::helpers::generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES};
8 use once_cell::sync::Lazy;
9 use rustc_hash::{FxHashMap, FxHashSet};
10 use syntax::{algo::non_trivia_sibling, ast, AstNode, Direction, NodeOrToken, SyntaxKind, T};
13 context::CompletionContext,
14 item::{CompletionItem, CompletionItemKind, CompletionKind},
21 pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
22 let attribute = ctx.attribute_under_caret.as_ref()?;
23 match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) {
24 (Some(path), Some(token_tree)) => match path.text().as_str() {
25 "derive" => derive::complete_derive(acc, ctx, token_tree),
26 "feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES),
27 "allow" | "warn" | "deny" | "forbid" => {
28 lint::complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINTS);
29 lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS);
33 (None, Some(_)) => (),
34 _ => complete_new_attribute(acc, ctx, attribute),
39 fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
40 let is_inner = attribute.kind() == ast::AttrKind::Inner;
41 let attribute_annotated_item_kind =
42 attribute.syntax().parent().map(|it| it.kind()).filter(|_| {
44 // If we got nothing coming after the attribute it could be anything so filter it the kind out
45 || non_trivia_sibling(attribute.syntax().clone().into(), Direction::Next).is_some()
47 let attributes = attribute_annotated_item_kind.and_then(|kind| {
48 if ast::Expr::can_cast(kind) {
51 KIND_TO_ATTRIBUTES.get(&kind).copied()
55 let add_completion = |attr_completion: &AttrCompletion| {
56 let mut item = CompletionItem::new(
57 CompletionKind::Attribute,
59 attr_completion.label,
61 item.kind(CompletionItemKind::Attribute);
63 if let Some(lookup) = attr_completion.lookup {
64 item.lookup_by(lookup);
67 if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
68 item.insert_snippet(cap, snippet);
71 if is_inner || !attr_completion.prefer_inner {
77 Some(applicable) => applicable
79 .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
80 .flat_map(|idx| ATTRIBUTES.get(idx))
81 .for_each(add_completion),
82 None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
83 None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
86 // FIXME: write a test for this when we can
87 ctx.scope.process_all_names(&mut |name, scope_def| {
88 if let hir::ScopeDef::MacroDef(mac) = scope_def {
89 if mac.kind() == hir::MacroKind::Attr {
90 let mut item = CompletionItem::new(
91 CompletionKind::Attribute,
95 item.kind(CompletionItemKind::Attribute);
96 if let Some(docs) = mac.docs(ctx.sema.db) {
97 item.documentation(docs);
105 struct AttrCompletion {
107 lookup: Option<&'static str>,
108 snippet: Option<&'static str>,
112 impl AttrCompletion {
113 fn key(&self) -> &'static str {
114 self.lookup.unwrap_or(self.label)
117 const fn prefer_inner(self) -> AttrCompletion {
118 AttrCompletion { prefer_inner: true, ..self }
124 lookup: Option<&'static str>,
125 snippet: Option<&'static str>,
126 ) -> AttrCompletion {
127 AttrCompletion { label, lookup, snippet, prefer_inner: false }
131 // attributes applicable to all items
132 [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
133 attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
135 // attributes applicable to all adts
136 [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
137 attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
139 // attributes applicable to all linkable things aka functions/statics
140 [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
141 attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
143 // error fallback for nicer error message
144 [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
145 compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
147 // general push down accumulation
148 [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
149 attrs!(@ { $($tt)* } { $($acc)*, $lit })
151 [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
152 compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
154 // final output construction
155 [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
158 attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
163 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
165 std::array::IntoIter::new([
170 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
171 "recursion_limit", "type_length_limit", "windows_subsystem"
174 (MODULE, attrs!(item, "no_implicit_prelude", "path")),
175 (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
176 (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
177 (MACRO_DEF, attrs!(item)),
178 (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
180 (TYPE_ALIAS, attrs!(item)),
181 (STRUCT, attrs!(item, adt, "non_exhaustive")),
182 (ENUM, attrs!(item, adt, "non_exhaustive")),
183 (UNION, attrs!(item, adt)),
184 (CONST, attrs!(item)),
189 "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
190 "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
191 "test", "track_caller"
194 (STATIC, attrs!(item, linkable, "global_allocator", "used")),
195 (TRAIT, attrs!(item, "must_use")),
196 (IMPL, attrs!(item, "automatically_derived")),
197 (ASSOC_ITEM_LIST, attrs!(item)),
198 (EXTERN_BLOCK, attrs!(item, "link")),
199 (EXTERN_ITEM_LIST, attrs!(item, "link")),
200 (MACRO_CALL, attrs!()),
201 (SELF_PARAM, attrs!()),
203 (RECORD_FIELD, attrs!()),
204 (VARIANT, attrs!("non_exhaustive")),
205 (TYPE_PARAM, attrs!()),
206 (CONST_PARAM, attrs!()),
207 (LIFETIME_PARAM, attrs!()),
208 (LET_STMT, attrs!()),
209 (EXPR_STMT, attrs!()),
211 (RECORD_EXPR_FIELD_LIST, attrs!()),
212 (RECORD_EXPR_FIELD, attrs!()),
213 (MATCH_ARM_LIST, attrs!()),
214 (MATCH_ARM, attrs!()),
215 (IDENT_PAT, attrs!()),
216 (RECORD_PAT_FIELD, attrs!()),
220 const EXPR_ATTRIBUTES: &[&str] = attrs!();
222 /// <https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index>
223 // Keep these sorted for the binary search!
224 const ATTRIBUTES: &[AttrCompletion] = &[
225 attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
226 attr("automatically_derived", None, None),
227 attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
228 attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
229 attr("cold", None, None),
230 attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
232 attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
233 attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
234 attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
235 attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
236 attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
237 attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
239 r#"export_name = "…""#,
241 Some(r#"export_name = "${0:exported_symbol_name}""#),
243 attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
244 attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
245 attr("global_allocator", None, None),
246 attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
247 attr("inline", Some("inline"), Some("inline")),
248 attr("link", None, None),
249 attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
251 r#"link_section = "…""#,
252 Some("link_section"),
253 Some(r#"link_section = "${0:section_name}""#),
255 attr("macro_export", None, None),
256 attr("macro_use", None, None),
257 attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
258 attr("no_implicit_prelude", None, None).prefer_inner(),
259 attr("no_link", None, None).prefer_inner(),
260 attr("no_main", None, None).prefer_inner(),
261 attr("no_mangle", None, None),
262 attr("no_std", None, None).prefer_inner(),
263 attr("non_exhaustive", None, None),
264 attr("panic_handler", None, None),
265 attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
266 attr("proc_macro", None, None),
267 attr("proc_macro_attribute", None, None),
268 attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
269 attr("recursion_limit = …", Some("recursion_limit"), Some("recursion_limit = ${0:128}"))
271 attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
272 attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
274 r#"target_feature = "…""#,
275 Some("target_feature"),
276 Some(r#"target_feature = "${0:feature}""#),
278 attr("test", None, None),
279 attr("track_caller", None, None),
280 attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
282 attr("used", None, None),
283 attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
285 r#"windows_subsystem = "…""#,
286 Some("windows_subsystem"),
287 Some(r#"windows_subsystem = "${0:subsystem}""#),
292 fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Option<FxHashSet<String>> {
293 let (l_paren, r_paren) = derive_input.l_paren_token().zip(derive_input.r_paren_token())?;
294 let mut input_derives = FxHashSet::default();
295 let mut tokens = derive_input
297 .children_with_tokens()
298 .filter_map(NodeOrToken::into_token)
299 .skip_while(|token| token != &l_paren)
301 .take_while(|token| token != &r_paren)
303 let mut input = String::new();
304 while tokens.peek().is_some() {
305 for token in tokens.by_ref().take_while(|t| t.kind() != T![,]) {
306 input.push_str(token.text());
309 if !input.is_empty() {
310 input_derives.insert(input.trim().to_owned());
323 use expect_test::{expect, Expect};
325 use crate::tests::completion_list;
328 fn attributes_are_sorted() {
329 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
330 let mut prev = attrs.next().unwrap();
332 attrs.for_each(|next| {
335 r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,
343 fn check(ra_fixture: &str, expect: Expect) {
344 let actual = completion_list(ra_fixture);
345 expect.assert_eq(&actual);
349 fn test_attribute_completion_inside_nested_attr() {
350 check(r#"#[cfg($0)]"#, expect![[]])
354 fn test_attribute_completion_with_existing_attr() {
356 r#"#[no_mangle] #[$0] mcall!();"#,
369 fn complete_attribute_on_source_file() {
387 at no_implicit_prelude
390 at recursion_limit = …
391 at type_length_limit = …
392 at windows_subsystem = "…"
398 fn complete_attribute_on_module() {
418 r#"mod foo {#![$0]}"#,
432 at no_implicit_prelude
438 fn complete_attribute_on_macro_rules() {
440 r#"#[$0] macro_rules! foo {}"#,
461 fn complete_attribute_on_macro_def() {
463 r#"#[$0] macro foo {}"#,
482 fn complete_attribute_on_extern_crate() {
484 r#"#[$0] extern crate foo;"#,
504 fn complete_attribute_on_use() {
525 fn complete_attribute_on_type_alias() {
527 r#"#[$0] type foo = ();"#,
546 fn complete_attribute_on_struct() {
548 r#"#[$0] struct Foo;"#,
570 fn complete_attribute_on_enum() {
572 r#"#[$0] enum Foo {}"#,
594 fn complete_attribute_on_const() {
596 r#"#[$0] const FOO: () = ();"#,
615 fn complete_attribute_on_static() {
617 r#"#[$0] static FOO: () = ()"#,
633 at link_section = "…"
641 fn complete_attribute_on_trait() {
643 r#"#[$0] trait Foo {}"#,
663 fn complete_attribute_on_impl() {
665 r#"#[$0] impl () {}"#,
679 at automatically_derived
683 r#"impl () {#![$0]}"#,
702 fn complete_attribute_on_extern_block() {
704 r#"#[$0] extern {}"#,
722 r#"extern {#![$0]}"#,
742 fn complete_attribute_on_variant() {
744 r#"enum Foo { #[$0] Bar }"#,
758 fn complete_attribute_on_fn() {
760 r#"#[$0] fn main() {}"#,
776 at link_section = "…"
783 at proc_macro_derive(…)
784 at proc_macro_attribute
786 at target_feature = "…"
795 fn complete_attribute_on_expr() {
797 r#"fn main() { #[$0] foo() }"#,
811 fn complete_attribute_in_source_file_end() {
816 at automatically_derived
833 at link_section = "…"
842 at proc_macro_attribute
843 at proc_macro_derive(…)
846 at target_feature = "…"