Skip to main content

ide_completion/completions/
attribute.rs

1//! Completion for (built-in) attributes, derives and lints.
2//!
3//! This module uses a bit of static metadata to provide completions for builtin-in attributes and lints.
4
5use std::sync::LazyLock;
6
7use ide_db::{FxHashMap, SymbolKind, syntax_helpers::node_ext::parse_tt_as_comma_sep_paths};
8use itertools::Itertools;
9use syntax::{
10    AstNode, Edition, SyntaxKind, T,
11    ast::{self, AttrKind},
12};
13
14use crate::{
15    Completions,
16    context::{AttrCtx, CompletionContext, PathCompletionCtx, Qualified},
17    item::CompletionItem,
18};
19
20mod cfg;
21mod derive;
22mod diagnostic;
23mod feature;
24mod lint;
25mod macro_use;
26mod repr;
27
28pub(crate) use self::cfg::complete_cfg;
29pub(crate) use self::derive::complete_derive_path;
30
31/// Complete inputs to known builtin attributes as well as derive attributes
32pub(crate) fn complete_known_attribute_input(
33    acc: &mut Completions,
34    ctx: &CompletionContext<'_, '_>,
35    colon_prefix: bool,
36    fake_attribute_under_caret: &ast::TokenTreeMeta,
37    extern_crate: Option<&ast::ExternCrate>,
38) -> Option<()> {
39    let attribute = fake_attribute_under_caret;
40    let path = attribute.path()?;
41    let segments = path.segments().map(|s| s.name_ref()).collect::<Option<Vec<_>>>()?;
42    let segments = segments.iter().map(|n| n.text()).collect::<Vec<_>>();
43    let tt = attribute.token_tree()?;
44
45    match segments.as_slice() {
46        ["repr"] => repr::complete_repr(acc, ctx, &parse_comma_sep_expr(tt)?),
47        ["feature"] => {
48            feature::complete_feature(acc, ctx, &parse_tt_as_comma_sep_paths(tt, ctx.edition)?)
49        }
50        ["allow" | "expect" | "deny" | "forbid" | "warn"] => lint::complete_lint(
51            acc,
52            ctx,
53            colon_prefix,
54            &parse_tt_as_comma_sep_paths(tt, ctx.edition)?,
55        ),
56        ["macro_use"] => macro_use::complete_macro_use(
57            acc,
58            ctx,
59            extern_crate,
60            &parse_tt_as_comma_sep_paths(tt, ctx.edition)?,
61        ),
62        ["diagnostic", "on_unimplemented"] => {
63            diagnostic::complete_on_unimplemented(acc, ctx, &parse_comma_sep_expr(tt)?)
64        }
65        _ => (),
66    }
67    Some(())
68}
69
70pub(crate) fn complete_attribute_path(
71    acc: &mut Completions,
72    ctx: &CompletionContext<'_, '_>,
73    path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>,
74    &AttrCtx { kind, annotated_item_kind, ref derive_helpers }: &AttrCtx,
75) {
76    let is_inner = kind == AttrKind::Inner;
77    let arg_exists = ctx.original_token.next_token().is_some_and(|it| it.kind().is_l_delimiter());
78
79    for (derive_helper, derive_name) in derive_helpers {
80        let mut item = CompletionItem::new(
81            SymbolKind::Attribute,
82            ctx.source_range(),
83            derive_helper.as_str(),
84            ctx.edition,
85        );
86        item.detail(format!("derive helper of `{derive_name}`"));
87        item.add_to(acc, ctx.db);
88    }
89
90    match qualified {
91        Qualified::With {
92            resolution: Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))),
93            super_chain_len,
94            ..
95        } => {
96            acc.add_super_keyword(ctx, *super_chain_len);
97
98            for (name, def) in module.scope(ctx.db, Some(ctx.module)) {
99                match def {
100                    hir::ScopeDef::ModuleDef(hir::ModuleDef::Macro(m)) if m.is_attr(ctx.db) => {
101                        acc.add_macro(ctx, path_ctx, m, name)
102                    }
103                    hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(m)) => {
104                        acc.add_module(ctx, path_ctx, m, name, vec![])
105                    }
106                    _ => (),
107                }
108            }
109            return;
110        }
111        // fresh use tree with leading colon2, only show crate roots
112        Qualified::Absolute => acc.add_crate_roots(ctx, path_ctx),
113        // only show modules in a fresh UseTree
114        Qualified::No => {
115            ctx.process_all_names(&mut |name, def, doc_aliases| match def {
116                hir::ScopeDef::ModuleDef(hir::ModuleDef::Macro(m)) if m.is_attr(ctx.db) => {
117                    if !DUPLICATE_ATTR.contains(&name.as_str()) {
118                        acc.add_macro(ctx, path_ctx, m, name)
119                    }
120                }
121                hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(m)) => {
122                    acc.add_module(ctx, path_ctx, m, name, doc_aliases)
123                }
124                _ => (),
125            });
126            acc.add_nameref_keywords_with_colon(ctx);
127        }
128        Qualified::TypeAnchor { .. } | Qualified::With { .. } => {}
129    }
130    let qualifier_path =
131        if let Qualified::With { path, .. } = qualified { Some(path) } else { None };
132    let qualifier_segments = qualifier_path.iter().flat_map(|q| q.segments()).collect::<Vec<_>>();
133
134    let attributes = annotated_item_kind.and_then(|kind| {
135        if ast::Expr::can_cast(kind) {
136            Some(EXPR_ATTRIBUTES)
137        } else {
138            KIND_TO_ATTRIBUTES.get(&kind).copied()
139        }
140    });
141
142    let add_completion = |attr_completion: &AttrCompletion| {
143        // if we don't already have the qualifiers of the completion, then
144        // add the missing parts to the label and snippet
145        let mut label = attr_completion.label.to_owned();
146        let mut snippet = attr_completion.snippet.map(|s| s.to_owned());
147        let qualifiers = attr_completion.qualifiers;
148        let matching_qualifiers = qualifier_segments
149            .iter()
150            .zip(qualifiers)
151            .take_while(|(s, q)| s.name_ref().is_some_and(|t| t.text() == **q))
152            .count();
153        if let Some(s) = snippet.as_mut()
154            && (arg_exists && s.ends_with(')'))
155            && let Some(at) = s.find('(')
156        {
157            s.truncate(at);
158        }
159        if matching_qualifiers != qualifiers.len() {
160            let prefix = qualifiers[matching_qualifiers..].join("::");
161            label = format!("{prefix}::{label}");
162            if let Some(s) = snippet.as_mut() {
163                *s = format!("{prefix}::{s}");
164            }
165        }
166
167        let mut item =
168            CompletionItem::new(SymbolKind::Attribute, ctx.source_range(), label, ctx.edition);
169
170        if let Some(lookup) = attr_completion.lookup {
171            item.lookup_by(lookup);
172        }
173
174        if let Some((snippet, cap)) = snippet.zip(ctx.config.snippet_cap) {
175            item.insert_snippet(cap, snippet);
176        } else if ctx.config.snippet_cap.is_none()
177            && let Some(text) = attr_completion.bare()
178        {
179            item.insert_text(text);
180        }
181
182        if is_inner || !attr_completion.prefer_inner {
183            item.add_to(acc, ctx.db);
184        }
185    };
186
187    match attributes {
188        Some(applicable) => applicable
189            .iter()
190            .flat_map(|name| ATTRIBUTES.binary_search_by_key(name, |attr| attr.key()).ok())
191            .flat_map(|idx| ATTRIBUTES.get(idx))
192            .for_each(add_completion),
193        None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
194        None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
195    }
196}
197
198struct AttrCompletion {
199    label: &'static str,
200    lookup: Option<&'static str>,
201    snippet: Option<&'static str>,
202    qualifiers: &'static [&'static str],
203    prefer_inner: bool,
204}
205
206impl AttrCompletion {
207    fn key(&self) -> &'static str {
208        self.lookup.unwrap_or(self.label)
209    }
210
211    fn bare(&self) -> Option<String> {
212        let s = r#""…""#;
213        self.label
214            .strip_suffix("(…)")
215            .or_else(|| self.label.strip_suffix("…"))
216            .map(ToOwned::to_owned)
217            .or_else(|| self.label.contains(s).then(|| self.label.replace(s, "")))
218    }
219
220    const fn qualifiers(self, qualifiers: &'static [&'static str]) -> AttrCompletion {
221        AttrCompletion { qualifiers, ..self }
222    }
223
224    const fn prefer_inner(self) -> AttrCompletion {
225        AttrCompletion { prefer_inner: true, ..self }
226    }
227}
228
229const fn attr(
230    label: &'static str,
231    lookup: Option<&'static str>,
232    snippet: Option<&'static str>,
233) -> AttrCompletion {
234    AttrCompletion { label, lookup, snippet, qualifiers: &[], prefer_inner: false }
235}
236
237macro_rules! attrs {
238    // attributes applicable to all items
239    [@ { item $($tt:tt)* } {$($acc:tt)*}] => {
240        attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "docinclude", "must_use", "no_mangle", "unsafe" })
241    };
242    // attributes applicable to all adts
243    [@ { adt $($tt:tt)* } {$($acc:tt)*}] => {
244        attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" })
245    };
246    // attributes applicable to all linkable things aka functions/statics
247    [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => {
248        attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" })
249    };
250    // error fallback for nicer error message
251    [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => {
252        compile_error!(concat!("unknown attr subtype ", stringify!($ty)))
253    };
254    // general push down accumulation
255    [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => {
256        attrs!(@ { $($tt)* } { $($acc)*, $lit })
257    };
258    [@ {$($tt:tt)+} {$($tt2:tt)*}] => {
259        compile_error!(concat!("Unexpected input ", stringify!($($tt)+)))
260    };
261    // final output construction
262    [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ };
263    // starting matcher
264    [$($tt:tt),*] => {
265        attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "expect", "forbid", "warn" })
266    };
267}
268
269#[rustfmt::skip]
270static KIND_TO_ATTRIBUTES: LazyLock<FxHashMap<SyntaxKind, &[&str]>> = LazyLock::new(|| {
271    use SyntaxKind::*;
272    [
273        (
274            SOURCE_FILE,
275            attrs!(
276                item,
277                "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std",
278                "recursion_limit", "type_length_limit", "windows_subsystem"
279            ),
280        ),
281        (MODULE, attrs!(item, "macro_use", "no_implicit_prelude", "path")),
282        (ITEM_LIST, attrs!(item, "no_implicit_prelude")),
283        (MACRO_RULES, attrs!(item, "macro_export", "macro_use")),
284        (MACRO_DEF, attrs!(item)),
285        (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")),
286        (USE, attrs!(item)),
287        (TYPE_ALIAS, attrs!(item)),
288        (STRUCT, attrs!(item, adt, "non_exhaustive")),
289        (ENUM, attrs!(item, adt, "non_exhaustive")),
290        (UNION, attrs!(item, adt)),
291        (CONST, attrs!(item)),
292        (
293            FN,
294            attrs!(
295                item, linkable,
296                "cold", "ignore", "inline", "panic_handler", "proc_macro",
297                "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature",
298                "test", "track_caller"
299            ),
300        ),
301        (STATIC, attrs!(item, linkable, "global_allocator", "used")),
302        (TRAIT, attrs!(item, "diagnostic::on_unimplemented")),
303        (IMPL, attrs!(item, "automatically_derived", "diagnostic::do_not_recommend")),
304        (ASSOC_ITEM_LIST, attrs!(item)),
305        (EXTERN_BLOCK, attrs!(item, "link")),
306        (EXTERN_ITEM_LIST, attrs!(item, "link")),
307        (MACRO_CALL, attrs!()),
308        (SELF_PARAM, attrs!()),
309        (PARAM, attrs!()),
310        (RECORD_FIELD, attrs!()),
311        (VARIANT, attrs!("non_exhaustive")),
312        (TYPE_PARAM, attrs!()),
313        (CONST_PARAM, attrs!()),
314        (LIFETIME_PARAM, attrs!()),
315        (LET_STMT, attrs!()),
316        (EXPR_STMT, attrs!()),
317        (LITERAL, attrs!()),
318        (RECORD_EXPR_FIELD_LIST, attrs!()),
319        (RECORD_EXPR_FIELD, attrs!()),
320        (MATCH_ARM_LIST, attrs!()),
321        (MATCH_ARM, attrs!()),
322        (IDENT_PAT, attrs!()),
323        (RECORD_PAT_FIELD, attrs!()),
324    ]
325    .into_iter()
326    .collect()
327});
328const EXPR_ATTRIBUTES: &[&str] = attrs!();
329
330/// <https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index>
331// Keep these sorted for the binary search!
332const ATTRIBUTES: &[AttrCompletion] = &[
333    attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
334    attr("automatically_derived", None, None),
335    attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
336    attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
337    attr("cold", None, None),
338    attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
339        .prefer_inner(),
340    attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
341    attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
342    attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
343    attr("do_not_recommend", Some("diagnostic::do_not_recommend"), None)
344        .qualifiers(&["diagnostic"]),
345    attr(
346        "on_unimplemented",
347        Some("diagnostic::on_unimplemented"),
348        Some(r#"on_unimplemented(${0:keys})"#),
349    )
350    .qualifiers(&["diagnostic"]),
351    attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
352    attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
353    attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
354    attr(r#"doc = include_str!("…")"#, Some("docinclude"), Some(r#"doc = include_str!("$0")"#)),
355    attr("expect(…)", Some("expect"), Some("expect(${0:lint})")),
356    attr(
357        r#"export_name = "…""#,
358        Some("export_name"),
359        Some(r#"export_name = "${0:exported_symbol_name}""#),
360    ),
361    attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
362    attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
363    attr("global_allocator", None, None),
364    attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
365    attr("inline", Some("inline"), Some("inline")),
366    attr("link", None, None),
367    attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
368    attr(
369        r#"link_section = "…""#,
370        Some("link_section"),
371        Some(r#"link_section = "${0:section_name}""#),
372    ),
373    attr("macro_export", None, None),
374    attr("macro_use", None, None),
375    attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
376    attr("no_implicit_prelude", None, None).prefer_inner(),
377    attr("no_link", None, None).prefer_inner(),
378    attr("no_main", None, None).prefer_inner(),
379    attr("no_mangle", None, None),
380    attr("no_std", None, None).prefer_inner(),
381    attr("non_exhaustive", None, None),
382    attr("panic_handler", None, None),
383    attr(r#"path = "…""#, Some("path"), Some(r#"path = "${0:path}""#)),
384    attr("proc_macro", None, None),
385    attr("proc_macro_attribute", None, None),
386    attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
387    attr(
388        r#"recursion_limit = "…""#,
389        Some("recursion_limit"),
390        Some(r#"recursion_limit = "${0:128}""#),
391    )
392    .prefer_inner(),
393    attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
394    attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
395    attr(
396        r#"target_feature(enable = "…")"#,
397        Some("target_feature"),
398        Some(r#"target_feature(enable = "${0:feature}")"#),
399    ),
400    attr("test", None, None),
401    attr("track_caller", None, None),
402    attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
403        .prefer_inner(),
404    attr("unsafe(…)", Some("unsafe"), Some("unsafe($0)")),
405    attr("used", None, None),
406    attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
407    attr(
408        r#"windows_subsystem = "…""#,
409        Some("windows_subsystem"),
410        Some(r#"windows_subsystem = "${0:subsystem}""#),
411    )
412    .prefer_inner(),
413];
414
415const DUPLICATE_ATTR: &[&str] = &["derive", "test"];
416
417fn parse_comma_sep_expr(input: ast::TokenTree) -> Option<Vec<ast::Expr>> {
418    let r_paren = input.r_paren_token()?;
419    let tokens = input
420        .syntax()
421        .children_with_tokens()
422        .skip(1)
423        .take_while(|it| it.as_token() != Some(&r_paren));
424    let input_expressions = tokens.chunk_by(|tok| tok.kind() == T![,]);
425    Some(
426        input_expressions
427            .into_iter()
428            .filter_map(|(is_sep, group)| (!is_sep).then_some(group))
429            .filter_map(|mut tokens| {
430                syntax::hacks::parse_expr_from_str(&tokens.join(""), Edition::CURRENT)
431            })
432            .collect::<Vec<ast::Expr>>(),
433    )
434}
435
436#[test]
437fn attributes_are_sorted() {
438    let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
439    let mut prev = attrs.next().unwrap();
440
441    attrs.for_each(|next| {
442        assert!(
443            prev < next,
444            r#"ATTRIBUTES array is not sorted, "{prev}" should come after "{next}""#
445        );
446        prev = next;
447    });
448}