1 //! Completion for attributes
3 //! This module uses a bit of static metadata to provide completions
4 //! for built-in attributes.
9 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES, RUSTDOC_LINTS},
10 parse_tt_as_comma_sep_paths,
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};
19 use crate::{context::CompletionContext, item::CompletionItem, Completions};
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()?),
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);
44 cfg::complete_cfg(acc, ctx);
49 (_, None) => complete_new_attribute(acc, ctx, attribute),
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(|_| {
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()
62 let attributes = attribute_annotated_item_kind.and_then(|kind| {
63 if ast::Expr::can_cast(kind) {
66 KIND_TO_ATTRIBUTES.get(&kind).copied()
70 let add_completion = |attr_completion: &AttrCompletion| {
72 CompletionItem::new(SymbolKind::Attribute, ctx.source_range(), attr_completion.label);
74 if let Some(lookup) = attr_completion.lookup {
75 item.lookup_by(lookup);
78 if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
79 item.insert_snippet(cap, snippet);
82 if is_inner || !attr_completion.prefer_inner {
88 Some(applicable) => applicable
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),
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,
106 if let Some(docs) = mac.docs(ctx.sema.db) {
107 item.documentation(docs);
115 struct AttrCompletion {
117 lookup: Option<&'static str>,
118 snippet: Option<&'static str>,
122 impl AttrCompletion {
123 fn key(&self) -> &'static str {
124 self.lookup.unwrap_or(self.label)
127 const fn prefer_inner(self) -> AttrCompletion {
128 AttrCompletion { prefer_inner: true, ..self }
134 lookup: Option<&'static str>,
135 snippet: Option<&'static str>,
136 ) -> AttrCompletion {
137 AttrCompletion { label, lookup, snippet, prefer_inner: false }
141 // attributes applicable to all items
142 [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
143 attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
145 // attributes applicable to all adts
146 [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
147 attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
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" })
153 // error fallback for nicer error message
154 [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
155 compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
157 // general push down accumulation
158 [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
159 attrs!(@ { $($tt)* } { $($acc)*, $lit })
161 [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
162 compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
164 // final output construction
165 [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
168 attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
173 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
180 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
181 "recursion_limit", "type_length_limit", "windows_subsystem"
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")),
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)),
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"
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!()),
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!()),
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!()),
231 const EXPR_ATTRIBUTES: &[&str] = attrs!();
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}""#))
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)"#)),
250 r#"export_name = "…""#,
252 Some(r#"export_name = "${0:exported_symbol_name}""#),
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}""#)),
262 r#"link_section = "…""#,
263 Some("link_section"),
264 Some(r#"link_section = "${0:section_name}""#),
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})")),
281 r#"recursion_limit = "…""#,
282 Some("recursion_limit"),
283 Some(r#"recursion_limit = "${0:128}""#),
286 attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
287 attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
289 r#"target_feature = "…""#,
290 Some("target_feature"),
291 Some(r#"target_feature = "${0:feature}""#),
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}"))
297 attr("used", None, None),
298 attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
300 r#"windows_subsystem = "…""#,
301 Some("windows_subsystem"),
302 Some(r#"windows_subsystem = "${0:subsystem}""#),
307 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
308 let r_paren = input.r_paren_token()?;
311 .children_with_tokens()
313 .take_while(|it| it.as_token() != Some(&r_paren));
314 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
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>>(),
325 fn attributes_are_sorted() {
326 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
327 let mut prev = attrs.next().unwrap();
329 attrs.for_each(|next| {
332 r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,