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};
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, CompletionKind},
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 "derive" => derive::complete_derive(acc, ctx, token_tree),
33 "repr" => repr::complete_repr(acc, ctx, token_tree),
34 "feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES),
35 "allow" | "warn" | "deny" | "forbid" => {
36 lint::complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINTS);
37 lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS);
40 cfg::complete_cfg(acc, ctx);
44 (None, Some(_)) => (),
45 _ => complete_new_attribute(acc, ctx, attribute),
50 fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
51 let is_inner = attribute.kind() == ast::AttrKind::Inner;
52 let attribute_annotated_item_kind =
53 attribute.syntax().parent().map(|it| it.kind()).filter(|_| {
55 // If we got nothing coming after the attribute it could be anything so filter it the kind out
56 || non_trivia_sibling(attribute.syntax().clone().into(), Direction::Next).is_some()
58 let attributes = attribute_annotated_item_kind.and_then(|kind| {
59 if ast::Expr::can_cast(kind) {
62 KIND_TO_ATTRIBUTES.get(&kind).copied()
66 let add_completion = |attr_completion: &AttrCompletion| {
67 let mut item = CompletionItem::new(
68 CompletionKind::Attribute,
70 attr_completion.label,
72 item.kind(CompletionItemKind::Attribute);
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 CompletionKind::Attribute,
106 item.kind(CompletionItemKind::Attribute);
107 if let Some(docs) = mac.docs(ctx.sema.db) {
108 item.documentation(docs);
116 struct AttrCompletion {
118 lookup: Option<&'static str>,
119 snippet: Option<&'static str>,
123 impl AttrCompletion {
124 fn key(&self) -> &'static str {
125 self.lookup.unwrap_or(self.label)
128 const fn prefer_inner(self) -> AttrCompletion {
129 AttrCompletion { prefer_inner: true, ..self }
135 lookup: Option<&'static str>,
136 snippet: Option<&'static str>,
137 ) -> AttrCompletion {
138 AttrCompletion { label, lookup, snippet, prefer_inner: false }
142 // attributes applicable to all items
143 [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
144 attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
146 // attributes applicable to all adts
147 [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
148 attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
150 // attributes applicable to all linkable things aka functions/statics
151 [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
152 attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
154 // error fallback for nicer error message
155 [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
156 compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
158 // general push down accumulation
159 [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
160 attrs!(@ { $($tt)* } { $($acc)*, $lit })
162 [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
163 compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
165 // final output construction
166 [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
169 attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
174 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
176 std::array::IntoIter::new([
181 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
182 "recursion_limit", "type_length_limit", "windows_subsystem"
185 (MODULE, attrs!(item, "macro_use", "no_implicit_prelude", "path")),
186 (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
187 (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
188 (MACRO_DEF, attrs!(item)),
189 (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
191 (TYPE_ALIAS, attrs!(item)),
192 (STRUCT, attrs!(item, adt, "non_exhaustive")),
193 (ENUM, attrs!(item, adt, "non_exhaustive")),
194 (UNION, attrs!(item, adt)),
195 (CONST, attrs!(item)),
200 "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
201 "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
202 "test", "track_caller"
205 (STATIC, attrs!(item, linkable, "global_allocator", "used")),
206 (TRAIT, attrs!(item, "must_use")),
207 (IMPL, attrs!(item, "automatically_derived")),
208 (ASSOC_ITEM_LIST, attrs!(item)),
209 (EXTERN_BLOCK, attrs!(item, "link")),
210 (EXTERN_ITEM_LIST, attrs!(item, "link")),
211 (MACRO_CALL, attrs!()),
212 (SELF_PARAM, attrs!()),
214 (RECORD_FIELD, attrs!()),
215 (VARIANT, attrs!("non_exhaustive")),
216 (TYPE_PARAM, attrs!()),
217 (CONST_PARAM, attrs!()),
218 (LIFETIME_PARAM, attrs!()),
219 (LET_STMT, attrs!()),
220 (EXPR_STMT, attrs!()),
222 (RECORD_EXPR_FIELD_LIST, attrs!()),
223 (RECORD_EXPR_FIELD, attrs!()),
224 (MATCH_ARM_LIST, attrs!()),
225 (MATCH_ARM, attrs!()),
226 (IDENT_PAT, attrs!()),
227 (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_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
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::Path::parse(&tokens.join("")).ok())
320 .collect::<Vec<ast::Path>>(),
324 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
325 let r_paren = input.r_paren_token()?;
328 .children_with_tokens()
330 .take_while(|it| it.as_token() != Some(&r_paren));
331 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
335 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
336 .filter_map(|mut tokens| ast::Expr::parse(&tokens.join("")).ok())
337 .collect::<Vec<ast::Expr>>(),
342 fn attributes_are_sorted() {
343 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
344 let mut prev = attrs.next().unwrap();
346 attrs.for_each(|next| {
349 r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,