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