1 //! Completion for attributes
3 //! This module uses a bit of static metadata to provide completions
4 //! for built-in attributes.
6 use once_cell::sync::Lazy;
7 use rustc_hash::{FxHashMap, FxHashSet};
8 use syntax::{ast, AstNode, SyntaxKind, T};
11 context::CompletionContext,
12 generated_lint_completions::{CLIPPY_LINTS, FEATURES},
13 item::{CompletionItem, CompletionItemKind, CompletionKind},
19 pub(crate) use self::lint::LintCompletion;
21 pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
22 if ctx.mod_declaration_under_caret.is_some() {
26 let attribute = ctx.attribute_under_caret.as_ref()?;
27 match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) {
28 (Some(path), Some(token_tree)) => match path.text().as_str() {
29 "derive" => derive::complete_derive(acc, ctx, token_tree),
30 "feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES),
31 "allow" | "warn" | "deny" | "forbid" => {
32 lint::complete_lint(acc, ctx, token_tree.clone(), lint::DEFAULT_LINT_COMPLETIONS);
33 lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS);
37 (None, Some(_)) => (),
38 _ => complete_new_attribute(acc, ctx, attribute),
43 fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
44 let attribute_annotated_item_kind = attribute.syntax().parent().map(|it| it.kind());
45 let attributes = attribute_annotated_item_kind.and_then(|kind| {
46 if ast::Expr::can_cast(kind) {
49 KIND_TO_ATTRIBUTES.get(&kind).copied()
52 let is_inner = attribute.kind() == ast::AttrKind::Inner;
54 let add_completion = |attr_completion: &AttrCompletion| {
55 let mut item = CompletionItem::new(
56 CompletionKind::Attribute,
58 attr_completion.label,
60 item.kind(CompletionItemKind::Attribute);
62 if let Some(lookup) = attr_completion.lookup {
63 item.lookup_by(lookup);
66 if let Some((snippet, cap)) = attr_completion.snippet.zip(ctx.config.snippet_cap) {
67 item.insert_snippet(cap, snippet);
70 if is_inner || !attr_completion.prefer_inner {
71 acc.add(item.build());
76 Some(applicable) => applicable
78 .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok())
79 .flat_map(|idx| ATTRIBUTES.get(idx))
80 .for_each(add_completion),
81 None if is_inner => ATTRIBUTES.iter().for_each(add_completion),
82 None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion),
86 struct AttrCompletion {
88 lookup: Option<&'static str>,
89 snippet: Option<&'static str>,
94 fn key(&self) -> &'static str {
95 self.lookup.unwrap_or(self.label)
98 const fn prefer_inner(self) -> AttrCompletion {
99 AttrCompletion { prefer_inner: true, ..self }
105 lookup: Option<&'static str>,
106 snippet: Option<&'static str>,
107 ) -> AttrCompletion {
108 AttrCompletion { label, lookup, snippet, prefer_inner: false }
112 [$($($mac:ident!),+;)? $($key:literal),*] => {
113 &["allow", "cfg", "cfg_attr", "deny", "forbid", "warn", $($($mac!()),+,)? $($key),*] as _
116 macro_rules! item_attrs {
122 static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
123 std::array::IntoIter::new([
124 (SyntaxKind::SOURCE_FILE, attrs!(item_attrs!;"crate_name")),
125 (SyntaxKind::MODULE, attrs!(item_attrs!;)),
126 (SyntaxKind::ITEM_LIST, attrs!(item_attrs!;)),
127 (SyntaxKind::MACRO_RULES, attrs!(item_attrs!;)),
128 (SyntaxKind::MACRO_DEF, attrs!(item_attrs!;)),
129 (SyntaxKind::EXTERN_CRATE, attrs!(item_attrs!;)),
130 (SyntaxKind::USE, attrs!(item_attrs!;)),
131 (SyntaxKind::FN, attrs!(item_attrs!;"cold", "must_use")),
132 (SyntaxKind::TYPE_ALIAS, attrs!(item_attrs!;)),
133 (SyntaxKind::STRUCT, attrs!(item_attrs!;"must_use")),
134 (SyntaxKind::ENUM, attrs!(item_attrs!;"must_use")),
135 (SyntaxKind::UNION, attrs!(item_attrs!;"must_use")),
136 (SyntaxKind::CONST, attrs!(item_attrs!;)),
137 (SyntaxKind::STATIC, attrs!(item_attrs!;)),
138 (SyntaxKind::TRAIT, attrs!(item_attrs!; "must_use")),
139 (SyntaxKind::IMPL, attrs!(item_attrs!;"automatically_derived")),
140 (SyntaxKind::ASSOC_ITEM_LIST, attrs!(item_attrs!;)),
141 (SyntaxKind::EXTERN_BLOCK, attrs!(item_attrs!;)),
142 (SyntaxKind::EXTERN_ITEM_LIST, attrs!(item_attrs!;)),
143 (SyntaxKind::MACRO_CALL, attrs!()),
144 (SyntaxKind::SELF_PARAM, attrs!()),
145 (SyntaxKind::PARAM, attrs!()),
146 (SyntaxKind::RECORD_FIELD, attrs!()),
147 (SyntaxKind::VARIANT, attrs!()),
148 (SyntaxKind::TYPE_PARAM, attrs!()),
149 (SyntaxKind::CONST_PARAM, attrs!()),
150 (SyntaxKind::LIFETIME_PARAM, attrs!()),
151 (SyntaxKind::LET_STMT, attrs!()),
152 (SyntaxKind::EXPR_STMT, attrs!()),
153 (SyntaxKind::LITERAL, attrs!()),
154 (SyntaxKind::RECORD_EXPR_FIELD_LIST, attrs!()),
155 (SyntaxKind::RECORD_EXPR_FIELD, attrs!()),
156 (SyntaxKind::MATCH_ARM_LIST, attrs!()),
157 (SyntaxKind::MATCH_ARM, attrs!()),
158 (SyntaxKind::IDENT_PAT, attrs!()),
159 (SyntaxKind::RECORD_PAT_FIELD, attrs!()),
163 const EXPR_ATTRIBUTES: &[&str] = attrs!();
165 /// https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index
166 // Keep these sorted for the binary search!
167 const ATTRIBUTES: &[AttrCompletion] = &[
168 attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
169 attr("automatically_derived", None, None),
170 attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
171 attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
172 attr("cold", None, None),
173 attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#))
175 attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
176 attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)),
177 attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
178 attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
179 attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)),
180 attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)),
182 r#"export_name = "…""#,
184 Some(r#"export_name = "${0:exported_symbol_name}""#),
186 attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
187 attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
188 // FIXME: resolve through macro resolution?
189 attr("global_allocator", None, None).prefer_inner(),
190 attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
191 attr("inline", Some("inline"), Some("inline")),
192 attr("link", None, None),
193 attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
195 r#"link_section = "…""#,
196 Some("link_section"),
197 Some(r#"link_section = "${0:section_name}""#),
199 attr("macro_export", None, None),
200 attr("macro_use", None, None),
201 attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)),
202 attr("no_implicit_prelude", None, None).prefer_inner(),
203 attr("no_link", None, None).prefer_inner(),
204 attr("no_main", None, None).prefer_inner(),
205 attr("no_mangle", None, None),
206 attr("no_std", None, None).prefer_inner(),
207 attr("non_exhaustive", None, None),
208 attr("panic_handler", None, None).prefer_inner(),
209 attr(r#"path = "…""#, Some("path"), Some(r#"path ="${0:path}""#)),
210 attr("proc_macro", None, None),
211 attr("proc_macro_attribute", None, None),
212 attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
213 attr("recursion_limit = …", Some("recursion_limit"), Some("recursion_limit = ${0:128}"))
215 attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
216 attr("should_panic", Some("should_panic"), Some(r#"should_panic"#)),
218 r#"target_feature = "…""#,
219 Some("target_feature"),
220 Some(r#"target_feature = "${0:feature}""#),
222 attr("test", None, None),
223 attr("track_caller", None, None),
224 attr("type_length_limit = …", Some("type_length_limit"), Some("type_length_limit = ${0:128}"))
226 attr("used", None, None),
227 attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
229 r#"windows_subsystem = "…""#,
230 Some("windows_subsystem"),
231 Some(r#"windows_subsystem = "${0:subsystem}""#),
237 fn attributes_are_sorted() {
238 let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key());
239 let mut prev = attrs.next().unwrap();
241 attrs.for_each(|next| {
244 r#"Attributes are not sorted, "{}" should come after "{}""#,
252 fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> {
253 match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) {
254 (Some(left_paren), Some(right_paren))
255 if left_paren.kind() == T!['('] && right_paren.kind() == T![')'] =>
257 let mut input_derives = FxHashSet::default();
258 let mut current_derive = String::new();
259 for token in derive_input
261 .children_with_tokens()
262 .filter_map(|token| token.into_token())
263 .skip_while(|token| token != &left_paren)
265 .take_while(|token| token != &right_paren)
267 if T![,] == token.kind() {
268 if !current_derive.is_empty() {
269 input_derives.insert(current_derive);
270 current_derive = String::new();
273 current_derive.push_str(token.text().trim());
277 if !current_derive.is_empty() {
278 input_derives.insert(current_derive);
288 use expect_test::{expect, Expect};
290 use crate::{test_utils::completion_list, CompletionKind};
292 fn check(ra_fixture: &str, expect: Expect) {
293 let actual = completion_list(ra_fixture, CompletionKind::Attribute);
294 expect.assert_eq(&actual);
298 fn complete_attribute_on_struct() {
317 fn test_attribute_completion_inside_nested_attr() {
318 check(r#"#[cfg($0)]"#, expect![[]])