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