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, 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 "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 CompletionKind::Attribute,
74 attr_completion.label,
76 item.kind(CompletionItemKind::Attribute);
78 if let Some(lookup) = attr_completion.lookup {
79 item.lookup_by(lookup);
82 if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
83 item.insert_snippet(cap, snippet);
86 if is_inner || !attr_completion.prefer_inner {
92 Some(applicable) => applicable
94 .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
95 .flat_map(|idx| ATTRIBUTES.get(idx))
96 .for_each(add_completion),
97 None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
98 None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
101 // FIXME: write a test for this when we can
102 ctx.scope.process_all_names(&mut |name, scope_def| {
103 if let hir::ScopeDef::MacroDef(mac) = scope_def {
104 if mac.kind() == hir::MacroKind::Attr {
105 let mut item = CompletionItem::new(
106 CompletionKind::Attribute,
110 item.kind(CompletionItemKind::Attribute);
111 if let Some(docs) = mac.docs(ctx.sema.db) {
112 item.documentation(docs);
120 struct AttrCompletion {
122 lookup: Option<&'static str>,
123 snippet: Option<&'static str>,
127 impl AttrCompletion {
128 fn key(&self) -> &'static str {
129 self.lookup.unwrap_or(self.label)
132 const fn prefer_inner(self) -> AttrCompletion {
133 AttrCompletion { prefer_inner: true, ..self }
139 lookup: Option<&'static str>,
140 snippet: Option<&'static str>,
141 ) -> AttrCompletion {
142 AttrCompletion { label, lookup, snippet, prefer_inner: false }
146 // attributes applicable to all items
147 [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
148 attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" })
150 // attributes applicable to all adts
151 [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
152 attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
154 // attributes applicable to all linkable things aka functions/statics
155 [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
156 attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
158 // error fallback for nicer error message
159 [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
160 compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
162 // general push down accumulation
163 [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
164 attrs!(@ { $($tt)* } { $($acc)*, $lit })
166 [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
167 compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
169 // final output construction
170 [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
173 attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" })
178 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
180 std::array::IntoIter::new([
185 "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
186 "recursion_limit", "type_length_limit", "windows_subsystem"
189 (MODULE, attrs!(item, "macro_use", "no_implicit_prelude", "path")),
190 (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
191 (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
192 (MACRO_DEF, attrs!(item)),
193 (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
195 (TYPE_ALIAS, attrs!(item)),
196 (STRUCT, attrs!(item, adt, "non_exhaustive")),
197 (ENUM, attrs!(item, adt, "non_exhaustive")),
198 (UNION, attrs!(item, adt)),
199 (CONST, attrs!(item)),
204 "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro",
205 "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
206 "test", "track_caller"
209 (STATIC, attrs!(item, linkable, "global_allocator", "used")),
210 (TRAIT, attrs!(item, "must_use")),
211 (IMPL, attrs!(item, "automatically_derived")),
212 (ASSOC_ITEM_LIST, attrs!(item)),
213 (EXTERN_BLOCK, attrs!(item, "link")),
214 (EXTERN_ITEM_LIST, attrs!(item, "link")),
215 (MACRO_CALL, attrs!()),
216 (SELF_PARAM, attrs!()),
218 (RECORD_FIELD, attrs!()),
219 (VARIANT, attrs!("non_exhaustive")),
220 (TYPE_PARAM, attrs!()),
221 (CONST_PARAM, attrs!()),
222 (LIFETIME_PARAM, attrs!()),
223 (LET_STMT, attrs!()),
224 (EXPR_STMT, attrs!()),
226 (RECORD_EXPR_FIELD_LIST, attrs!()),
227 (RECORD_EXPR_FIELD, attrs!()),
228 (MATCH_ARM_LIST, attrs!()),
229 (MATCH_ARM, attrs!()),
230 (IDENT_PAT, attrs!()),
231 (RECORD_PAT_FIELD, attrs!()),
235 const EXPR_ATTRIBUTES: &[&str] = attrs!();
237 /// <https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index>
238 // Keep these sorted for the binary search!
239 const ATTRIBUTES: &[AttrCompletion] = &[
240 attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
241 attr("automatically_derived", None, None),
242 attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
243 attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
244 attr("cold", None, None),
245 attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
247 attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
248 attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
249 attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
250 attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
251 attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
252 attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
254 r#"export_name = "…""#,
256 Some(r#"export_name = "${0:exported_symbol_name}""#),
258 attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
259 attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
260 attr("global_allocator", None, None),
261 attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
262 attr("inline", Some("inline"), Some("inline")),
263 attr("link", None, None),
264 attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
266 r#"link_section = "…""#,
267 Some("link_section"),
268 Some(r#"link_section = "${0:section_name}""#),
270 attr("macro_export", None, None),
271 attr("macro_use", None, None),
272 attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
273 attr("no_implicit_prelude", None, None).prefer_inner(),
274 attr("no_link", None, None).prefer_inner(),
275 attr("no_main", None, None).prefer_inner(),
276 attr("no_mangle", None, None),
277 attr("no_std", None, None).prefer_inner(),
278 attr("non_exhaustive", None, None),
279 attr("panic_handler", None, None),
280 attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
281 attr("proc_macro", None, None),
282 attr("proc_macro_attribute", None, None),
283 attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
285 r#"recursion_limit = "…""#,
286 Some("recursion_limit"),
287 Some(r#"recursion_limit = "${0:128}""#),
290 attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
291 attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
293 r#"target_feature = "…""#,
294 Some("target_feature"),
295 Some(r#"target_feature = "${0:feature}""#),
297 attr("test", None, None),
298 attr("track_caller", None, None),
299 attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
301 attr("used", None, None),
302 attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
304 r#"windows_subsystem = "…""#,
305 Some("windows_subsystem"),
306 Some(r#"windows_subsystem = "${0:subsystem}""#),
311 fn parse_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
312 let r_paren = input.r_paren_token()?;
315 .children_with_tokens()
317 .take_while(|it| it.as_token() != Some(&r_paren));
318 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
322 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
323 .filter_map(|mut tokens| ast::Path::parse(&tokens.join("")).ok())
324 .collect::<Vec<ast::Path>>(),
328 fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
329 let r_paren = input.r_paren_token()?;
332 .children_with_tokens()
334 .take_while(|it| it.as_token() != Some(&r_paren));
335 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
339 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
340 .filter_map(|mut tokens| ast::Expr::parse(&tokens.join("")).ok())
341 .collect::<Vec<ast::Expr>>(),
346 fn attributes_are_sorted() {
347 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
348 let mut prev = attrs.next().unwrap();
350 attrs.for_each(|next| {
353 r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#,