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