1 //! Completion for attributes
3 //! This module uses a bit of static metadata to provide completions
4 //! for built-in attributes.
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};
14 context::CompletionContext,
15 item::{CompletionItem, CompletionItemKind},
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()?),
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)?),
35 lint::complete_lint(acc, ctx, &parse_comma_sep_paths(token_tree)?, FEATURES)
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);
44 cfg::complete_cfg(acc, ctx);
48 (None, Some(_)) => (),
49 _ => 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| {
71 let mut item = CompletionItem::new(
72 CompletionItemKind::Attribute,
74 attr_completion.label,
77 if let Some(lookup) = attr_completion.lookup {
78 item.lookup_by(lookup);
81 if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
82 item.insert_snippet(cap, snippet);
85 if is_inner || !attr_completion.prefer_inner {
91 Some(applicable) => applicable
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),
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,
109 if let Some(docs) = mac.docs(ctx.sema.db) {
110 item.documentation(docs);
118 struct AttrCompletion {
120 lookup: Option<&'static str>,
121 snippet: Option<&'static str>,
125 impl AttrCompletion {
126 fn key(&self) -> &'static str {
127 self.lookup.unwrap_or(self.label)
130 const fn prefer_inner(self) -> AttrCompletion {
131 AttrCompletion { prefer_inner: true, ..self }
137 lookup: Option<&'static str>,
138 snippet: Option<&'static str>,
139 ) -> AttrCompletion {
140 AttrCompletion { label, lookup, snippet, prefer_inner: false }
144 // attributes applicable to all items
145 [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
146 attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
148 // attributes applicable to all adts
149 [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
150 attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
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" })
156 // error fallback for nicer error message
157 [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
158 compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
160 // general push down accumulation
161 [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
162 attrs!(@ { $($tt)* } { $($acc)*, $lit })
164 [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
165 compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
167 // final output construction
168 [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
171 attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
176 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
183 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
184 "recursion_limit", "type_length_limit", "windows_subsystem"
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")),
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)),
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"
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!()),
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!()),
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!()),
234 const EXPR_ATTRIBUTES: &[&str] = attrs!();
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}""#))
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)"#)),
253 r#"export_name = "…""#,
255 Some(r#"export_name = "${0:exported_symbol_name}""#),
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}""#)),
265 r#"link_section = "…""#,
266 Some("link_section"),
267 Some(r#"link_section = "${0:section_name}""#),
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})")),
284 r#"recursion_limit = "…""#,
285 Some("recursion_limit"),
286 Some(r#"recursion_limit = "${0:128}""#),
289 attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
290 attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
292 r#"target_feature = "…""#,
293 Some("target_feature"),
294 Some(r#"target_feature = "${0:feature}""#),
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}"))
300 attr("used", None, None),
301 attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
303 r#"windows_subsystem = "…""#,
304 Some("windows_subsystem"),
305 Some(r#"windows_subsystem = "${0:subsystem}""#),
310 fn parse_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
311 let r_paren = input.r_paren_token()?;
314 .children_with_tokens()
316 .take_while(|it| it.as_token() != Some(&r_paren));
317 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
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>>(),
327 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
328 let r_paren = input.r_paren_token()?;
331 .children_with_tokens()
333 .take_while(|it| it.as_token() != Some(&r_paren));
334 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
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>>(),
345 fn attributes_are_sorted() {
346 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
347 let mut prev = attrs.next().unwrap();
349 attrs.for_each(|next| {
352 r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,