]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/attribute.rs
Merge #10929
[rust.git] / crates / ide_completion / src / completions / attribute.rs
1 //! Completion for attributes
2 //!
3 //! This module uses a bit of static metadata to provide completions
4 //! for built-in attributes.
5
6 use hir::HasAttrs;
7 use ide_db::{
8     helpers::{
9         generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES, RUSTDOC_LINTS},
10         parse_tt_as_comma_sep_paths,
11     },
12     SymbolKind,
13 };
14 use itertools::Itertools;
15 use once_cell::sync::Lazy;
16 use rustc_hash::FxHashMap;
17 use syntax::{algo::non_trivia_sibling, ast, AstNode, Direction, SyntaxKind, T};
18
19 use crate::{context::CompletionContext, item::CompletionItem, Completions};
20
21 mod cfg;
22 mod derive;
23 mod lint;
24 mod repr;
25
26 pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
27     let attribute = ctx.attribute_under_caret.as_ref()?;
28     let name_ref = match attribute.path() {
29         Some(p) => Some(p.as_single_name_ref()?),
30         None => None,
31     };
32     match (name_ref, attribute.token_tree()) {
33         (Some(path), Some(token_tree)) => match path.text().as_str() {
34             "repr" => repr::complete_repr(acc, ctx, token_tree),
35             "derive" => {
36                 derive::complete_derive(acc, ctx, &parse_tt_as_comma_sep_paths(token_tree)?)
37             }
38             "feature" => {
39                 lint::complete_lint(acc, ctx, &parse_tt_as_comma_sep_paths(token_tree)?, FEATURES)
40             }
41             "allow" | "warn" | "deny" | "forbid" => {
42                 let existing_lints = parse_tt_as_comma_sep_paths(token_tree)?;
43                 lint::complete_lint(acc, ctx, &existing_lints, DEFAULT_LINTS);
44                 lint::complete_lint(acc, ctx, &existing_lints, CLIPPY_LINTS);
45                 lint::complete_lint(acc, ctx, &existing_lints, RUSTDOC_LINTS);
46             }
47             "cfg" => {
48                 cfg::complete_cfg(acc, ctx);
49             }
50             _ => (),
51         },
52         (None, Some(_)) => (),
53         _ => complete_new_attribute(acc, ctx, attribute),
54     }
55     Some(())
56 }
57
58 fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
59     let is_inner = attribute.kind() == ast::AttrKind::Inner;
60     let attribute_annotated_item_kind =
61         attribute.syntax().parent().map(|it| it.kind()).filter(|_| {
62             is_inner
63             // If we got nothing coming after the attribute it could be anything so filter it the kind out
64                 || non_trivia_sibling(attribute.syntax().clone().into(), Direction::Next).is_some()
65         });
66     let attributes = attribute_annotated_item_kind.and_then(|kind| {
67         if ast::Expr::can_cast(kind) {
68             Some(EXPR_ATTRIBUTES)
69         } else {
70             KIND_TO_ATTRIBUTES.get(&kind).copied()
71         }
72     });
73
74     let add_completion = |attr_completion: &AttrCompletion| {
75         let mut item =
76             CompletionItem::new(SymbolKind::Attribute, ctx.source_range(), attr_completion.label);
77
78         if let Some(lookup) = attr_completion.lookup {
79             item.lookup_by(lookup);
80         }
81
82         if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
83             item.insert_snippet(cap, snippet);
84         }
85
86         if is_inner || !attr_completion.prefer_inner {
87             item.add_to(acc);
88         }
89     };
90
91     match attributes {
92         Some(applicable) => applicable
93             .iter()
94             .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
95             .flat_map(|idx| ATTRIBUTES.get(idx))
96             .for_each(add_completion),
97         None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
98         None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
99     }
100
101     // FIXME: write a test for this when we can
102     ctx.scope.process_all_names(&mut |name, scope_def| {
103         if let hir::ScopeDef::MacroDef(mac) = scope_def {
104             if mac.kind() == hir::MacroKind::Attr {
105                 let mut item = CompletionItem::new(
106                     SymbolKind::Attribute,
107                     ctx.source_range(),
108                     name.to_smol_str(),
109                 );
110                 if let Some(docs) = mac.docs(ctx.sema.db) {
111                     item.documentation(docs);
112                 }
113                 item.add_to(acc);
114             }
115         }
116     });
117 }
118
119 struct AttrCompletion {
120     label: &'static str,
121     lookup: Option<&'static str>,
122     snippet: Option<&'static str>,
123     prefer_inner: bool,
124 }
125
126 impl AttrCompletion {
127     fn key(&self) -> &'static str {
128         self.lookup.unwrap_or(self.label)
129     }
130
131     const fn prefer_inner(self) -> AttrCompletion {
132         AttrCompletion { prefer_inner: true, ..self }
133     }
134 }
135
136 const fn attr(
137     label: &'static str,
138     lookup: Option<&'static str>,
139     snippet: Option<&'static str>,
140 ) -> AttrCompletion {
141     AttrCompletion { label, lookup, snippet, prefer_inner: false }
142 }
143
144 macro_rules! attrs {
145     // attributes applicable to all items
146     [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
147         attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
148     };
149     // attributes applicable to all adts
150     [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
151         attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
152     };
153     // attributes applicable to all linkable things aka functions/statics
154     [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
155         attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
156     };
157     // error fallback for nicer error message
158     [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
159         compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
160     };
161     // general push down accumulation
162     [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
163         attrs!(@ { $($tt)* } { $($acc)*, $lit })
164     };
165     [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
166         compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
167     };
168     // final output construction
169     [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
170     // starting matcher
171     [$($tt:tt),*] => {
172         attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
173     };
174 }
175
176 #[rustfmt::skip]
177 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
178     use SyntaxKind::*;
179     [
180         (
181             SOURCE_FILE,
182             attrs!(
183                 item,
184                 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
185                 "recursion_limit", "type_length_limit", "windows_subsystem"
186             ),
187         ),
188         (MODULE, attrs!(item, "macro_use", "no_implicit_prelude", "path")),
189         (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
190         (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
191         (MACRO_DEF, attrs!(item)),
192         (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
193         (USE, attrs!(item)),
194         (TYPE_ALIAS, attrs!(item)),
195         (STRUCT, attrs!(item, adt, "non_exhaustive")),
196         (ENUM, attrs!(item, adt, "non_exhaustive")),
197         (UNION, attrs!(item, adt)),
198         (CONST, attrs!(item)),
199         (
200             FN,
201             attrs!(
202                 item, linkable,
203                 "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
204                 "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
205                 "test", "track_caller"
206             ),
207         ),
208         (STATIC, attrs!(item, linkable, "global_allocator", "used")),
209         (TRAIT, attrs!(item, "must_use")),
210         (IMPL, attrs!(item, "automatically_derived")),
211         (ASSOC_ITEM_LIST, attrs!(item)),
212         (EXTERN_BLOCK, attrs!(item, "link")),
213         (EXTERN_ITEM_LIST, attrs!(item, "link")),
214         (MACRO_CALL, attrs!()),
215         (SELF_PARAM, attrs!()),
216         (PARAM, attrs!()),
217         (RECORD_FIELD, attrs!()),
218         (VARIANT, attrs!("non_exhaustive")),
219         (TYPE_PARAM, attrs!()),
220         (CONST_PARAM, attrs!()),
221         (LIFETIME_PARAM, attrs!()),
222         (LET_STMT, attrs!()),
223         (EXPR_STMT, attrs!()),
224         (LITERAL, attrs!()),
225         (RECORD_EXPR_FIELD_LIST, attrs!()),
226         (RECORD_EXPR_FIELD, attrs!()),
227         (MATCH_ARM_LIST, attrs!()),
228         (MATCH_ARM, attrs!()),
229         (IDENT_PAT, attrs!()),
230         (RECORD_PAT_FIELD, attrs!()),
231     ]
232     .into_iter()
233     .collect()
234 });
235 const EXPR_ATTRIBUTES: &[&str] = attrs!();
236
237 /// <https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index>
238 // Keep these sorted for the binary search!
239 const ATTRIBUTES: &[AttrCompletion] = &[
240     attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
241     attr("automatically_derived", None, None),
242     attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
243     attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
244     attr("cold", None, None),
245     attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
246         .prefer_inner(),
247     attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
248     attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
249     attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
250     attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
251     attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
252     attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
253     attr(
254         r#"export_name = "…""#,
255         Some("export_name"),
256         Some(r#"export_name = "${0:exported_symbol_name}""#),
257     ),
258     attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
259     attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
260     attr("global_allocator", None, None),
261     attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
262     attr("inline", Some("inline"), Some("inline")),
263     attr("link", None, None),
264     attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
265     attr(
266         r#"link_section = "…""#,
267         Some("link_section"),
268         Some(r#"link_section = "${0:section_name}""#),
269     ),
270     attr("macro_export", None, None),
271     attr("macro_use", None, None),
272     attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
273     attr("no_implicit_prelude", None, None).prefer_inner(),
274     attr("no_link", None, None).prefer_inner(),
275     attr("no_main", None, None).prefer_inner(),
276     attr("no_mangle", None, None),
277     attr("no_std", None, None).prefer_inner(),
278     attr("non_exhaustive", None, None),
279     attr("panic_handler", None, None),
280     attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
281     attr("proc_macro", None, None),
282     attr("proc_macro_attribute", None, None),
283     attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
284     attr(
285         r#"recursion_limit = "…""#,
286         Some("recursion_limit"),
287         Some(r#"recursion_limit = "${0:128}""#),
288     )
289     .prefer_inner(),
290     attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
291     attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
292     attr(
293         r#"target_feature = "…""#,
294         Some("target_feature"),
295         Some(r#"target_feature = "${0:feature}""#),
296     ),
297     attr("test", None, None),
298     attr("track_caller", None, None),
299     attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
300         .prefer_inner(),
301     attr("used", None, None),
302     attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
303     attr(
304         r#"windows_subsystem = "…""#,
305         Some("windows_subsystem"),
306         Some(r#"windows_subsystem = "${0:subsystem}""#),
307     )
308     .prefer_inner(),
309 ];
310
311 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
312     let r_paren = input.r_paren_token()?;
313     let tokens = input
314         .syntax()
315         .children_with_tokens()
316         .skip(1)
317         .take_while(|it| it.as_token() != Some(&r_paren));
318     let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
319     Some(
320         input_expressions
321             .into_iter()
322             .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
323             .filter_map(|mut tokens| ast::Expr::parse(&tokens.join("")).ok())
324             .collect::<Vec<ast::Expr>>(),
325     )
326 }
327
328 #[test]
329 fn attributes_are_sorted() {
330     let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
331     let mut prev = attrs.next().unwrap();
332
333     attrs.for_each(|next| {
334         assert!(
335             prev < next,
336             r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,
337             prev,
338             next
339         );
340         prev = next;
341     });
342 }