]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/attribute.rs
Merge #10649
[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},
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             CompletionItemKind::Attribute,
73             ctx.source_range(),
74             attr_completion.label,
75         );
76
77         if let Some(lookup) = attr_completion.lookup {
78             item.lookup_by(lookup);
79         }
80
81         if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
82             item.insert_snippet(cap, snippet);
83         }
84
85         if is_inner || !attr_completion.prefer_inner {
86             item.add_to(acc);
87         }
88     };
89
90     match attributes {
91         Some(applicable) => applicable
92             .iter()
93             .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
94             .flat_map(|idx| ATTRIBUTES.get(idx))
95             .for_each(add_completion),
96         None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
97         None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
98     }
99
100     // FIXME: write a test for this when we can
101     ctx.scope.process_all_names(&mut |name, scope_def| {
102         if let hir::ScopeDef::MacroDef(mac) = scope_def {
103             if mac.kind() == hir::MacroKind::Attr {
104                 let mut item = CompletionItem::new(
105                     CompletionItemKind::Attribute,
106                     ctx.source_range(),
107                     name.to_string(),
108                 );
109                 if let Some(docs) = mac.docs(ctx.sema.db) {
110                     item.documentation(docs);
111                 }
112                 item.add_to(acc);
113             }
114         }
115     });
116 }
117
118 struct AttrCompletion {
119     label: &'static str,
120     lookup: Option<&'static str>,
121     snippet: Option<&'static str>,
122     prefer_inner: bool,
123 }
124
125 impl AttrCompletion {
126     fn key(&self) -> &'static str {
127         self.lookup.unwrap_or(self.label)
128     }
129
130     const fn prefer_inner(self) -> AttrCompletion {
131         AttrCompletion { prefer_inner: true, ..self }
132     }
133 }
134
135 const fn attr(
136     label: &'static str,
137     lookup: Option<&'static str>,
138     snippet: Option<&'static str>,
139 ) -> AttrCompletion {
140     AttrCompletion { label, lookup, snippet, prefer_inner: false }
141 }
142
143 macro_rules! attrs {
144     // attributes applicable to all items
145     [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
146         attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
147     };
148     // attributes applicable to all adts
149     [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
150         attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
151     };
152     // attributes applicable to all linkable things aka functions/statics
153     [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
154         attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
155     };
156     // error fallback for nicer error message
157     [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
158         compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
159     };
160     // general push down accumulation
161     [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
162         attrs!(@ { $($tt)* } { $($acc)*, $lit })
163     };
164     [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
165         compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
166     };
167     // final output construction
168     [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
169     // starting matcher
170     [$($tt:tt),*] => {
171         attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
172     };
173 }
174
175 #[rustfmt::skip]
176 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
177     use SyntaxKind::*;
178     [
179         (
180             SOURCE_FILE,
181             attrs!(
182                 item,
183                 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
184                 "recursion_limit", "type_length_limit", "windows_subsystem"
185             ),
186         ),
187         (MODULE, attrs!(item, "macro_use", "no_implicit_prelude", "path")),
188         (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
189         (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
190         (MACRO_DEF, attrs!(item)),
191         (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
192         (USE, attrs!(item)),
193         (TYPE_ALIAS, attrs!(item)),
194         (STRUCT, attrs!(item, adt, "non_exhaustive")),
195         (ENUM, attrs!(item, adt, "non_exhaustive")),
196         (UNION, attrs!(item, adt)),
197         (CONST, attrs!(item)),
198         (
199             FN,
200             attrs!(
201                 item, linkable,
202                 "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
203                 "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
204                 "test", "track_caller"
205             ),
206         ),
207         (STATIC, attrs!(item, linkable, "global_allocator", "used")),
208         (TRAIT, attrs!(item, "must_use")),
209         (IMPL, attrs!(item, "automatically_derived")),
210         (ASSOC_ITEM_LIST, attrs!(item)),
211         (EXTERN_BLOCK, attrs!(item, "link")),
212         (EXTERN_ITEM_LIST, attrs!(item, "link")),
213         (MACRO_CALL, attrs!()),
214         (SELF_PARAM, attrs!()),
215         (PARAM, attrs!()),
216         (RECORD_FIELD, attrs!()),
217         (VARIANT, attrs!("non_exhaustive")),
218         (TYPE_PARAM, attrs!()),
219         (CONST_PARAM, attrs!()),
220         (LIFETIME_PARAM, attrs!()),
221         (LET_STMT, attrs!()),
222         (EXPR_STMT, attrs!()),
223         (LITERAL, attrs!()),
224         (RECORD_EXPR_FIELD_LIST, attrs!()),
225         (RECORD_EXPR_FIELD, attrs!()),
226         (MATCH_ARM_LIST, attrs!()),
227         (MATCH_ARM, attrs!()),
228         (IDENT_PAT, attrs!()),
229         (RECORD_PAT_FIELD, attrs!()),
230     ]
231     .into_iter()
232     .collect()
233 });
234 const EXPR_ATTRIBUTES: &[&str] = attrs!();
235
236 /// <https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index>
237 // Keep these sorted for the binary search!
238 const ATTRIBUTES: &[AttrCompletion] = &[
239     attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
240     attr("automatically_derived", None, None),
241     attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
242     attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
243     attr("cold", None, None),
244     attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
245         .prefer_inner(),
246     attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
247     attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
248     attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
249     attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
250     attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
251     attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
252     attr(
253         r#"export_name = "…""#,
254         Some("export_name"),
255         Some(r#"export_name = "${0:exported_symbol_name}""#),
256     ),
257     attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
258     attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
259     attr("global_allocator", None, None),
260     attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
261     attr("inline", Some("inline"), Some("inline")),
262     attr("link", None, None),
263     attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
264     attr(
265         r#"link_section = "…""#,
266         Some("link_section"),
267         Some(r#"link_section = "${0:section_name}""#),
268     ),
269     attr("macro_export", None, None),
270     attr("macro_use", None, None),
271     attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
272     attr("no_implicit_prelude", None, None).prefer_inner(),
273     attr("no_link", None, None).prefer_inner(),
274     attr("no_main", None, None).prefer_inner(),
275     attr("no_mangle", None, None),
276     attr("no_std", None, None).prefer_inner(),
277     attr("non_exhaustive", None, None),
278     attr("panic_handler", None, None),
279     attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
280     attr("proc_macro", None, None),
281     attr("proc_macro_attribute", None, None),
282     attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
283     attr(
284         r#"recursion_limit = "…""#,
285         Some("recursion_limit"),
286         Some(r#"recursion_limit = "${0:128}""#),
287     )
288     .prefer_inner(),
289     attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
290     attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
291     attr(
292         r#"target_feature = "…""#,
293         Some("target_feature"),
294         Some(r#"target_feature = "${0:feature}""#),
295     ),
296     attr("test", None, None),
297     attr("track_caller", None, None),
298     attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
299         .prefer_inner(),
300     attr("used", None, None),
301     attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
302     attr(
303         r#"windows_subsystem = "…""#,
304         Some("windows_subsystem"),
305         Some(r#"windows_subsystem = "${0:subsystem}""#),
306     )
307     .prefer_inner(),
308 ];
309
310 fn parse_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
311     let r_paren = input.r_paren_token()?;
312     let tokens = input
313         .syntax()
314         .children_with_tokens()
315         .skip(1)
316         .take_while(|it| it.as_token() != Some(&r_paren));
317     let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
318     Some(
319         input_expressions
320             .into_iter()
321             .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
322             .filter_map(|mut tokens| ast::Path::parse(&tokens.join("")).ok())
323             .collect::<Vec<ast::Path>>(),
324     )
325 }
326
327 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
328     let r_paren = input.r_paren_token()?;
329     let tokens = input
330         .syntax()
331         .children_with_tokens()
332         .skip(1)
333         .take_while(|it| it.as_token() != Some(&r_paren));
334     let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
335     Some(
336         input_expressions
337             .into_iter()
338             .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
339             .filter_map(|mut tokens| ast::Expr::parse(&tokens.join("")).ok())
340             .collect::<Vec<ast::Expr>>(),
341     )
342 }
343
344 #[test]
345 fn attributes_are_sorted() {
346     let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
347     let mut prev = attrs.next().unwrap();
348
349     attrs.for_each(|next| {
350         assert!(
351             prev < next,
352             r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,
353             prev,
354             next
355         );
356         prev = next;
357     });
358 }