]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/builtin_attr.rs
feat: Resolve builtin-attr and tools in ide layer
[rust.git] / crates / hir_def / src / builtin_attr.rs
1 //! Builtin attributes resolved by nameres.
2 //!
3 //! The actual definitions were copied from rustc's `compiler/rustc_feature/src/builtin_attrs.rs`.
4 //!
5 //! It was last synchronized with upstream commit ae90dcf0207c57c3034f00b07048d63f8b2363c8.
6 //!
7 //! The macros were adjusted to only expand to the attribute name, since that is all we need to do
8 //! name resolution, and `BUILTIN_ATTRIBUTES` is almost entirely unchanged from the original, to
9 //! ease updating.
10
11 use once_cell::sync::OnceCell;
12 use rustc_hash::FxHashMap;
13
14 /// Ignored attribute namespaces used by tools.
15 pub const TOOL_MODULES: &[&str] = &["rustfmt", "clippy"];
16
17 pub struct BuiltinAttribute {
18     pub name: &'static str,
19     pub template: AttributeTemplate,
20 }
21
22 /// A template that the attribute input must match.
23 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
24 pub struct AttributeTemplate {
25     pub word: bool,
26     pub list: Option<&'static str>,
27     pub name_value_str: Option<&'static str>,
28 }
29
30 static BUILTIN_LOOKUP_TABLE: OnceCell<FxHashMap<&'static str, usize>> = OnceCell::new();
31
32 pub fn find_builtin_attr_idx(name: &str) -> Option<usize> {
33     BUILTIN_LOOKUP_TABLE
34         .get_or_init(|| {
35             INERT_ATTRIBUTES.iter().map(|attr| attr.name).enumerate().map(|(a, b)| (b, a)).collect()
36         })
37         .get(name)
38         .copied()
39 }
40
41 // impl AttributeTemplate {
42 //     const DEFAULT: AttributeTemplate =
43 //         AttributeTemplate { word: false, list: None, name_value_str: None };
44 // }
45
46 /// A convenience macro for constructing attribute templates.
47 /// E.g., `template!(Word, List: "description")` means that the attribute
48 /// supports forms `#[attr]` and `#[attr(description)]`.
49 macro_rules! template {
50     (Word) => { template!(@ true, None, None) };
51     (List: $descr: expr) => { template!(@ false, Some($descr), None) };
52     (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
53     (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
54     (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
55     (List: $descr1: expr, NameValueStr: $descr2: expr) => {
56         template!(@ false, Some($descr1), Some($descr2))
57     };
58     (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
59         template!(@ true, Some($descr1), Some($descr2))
60     };
61     (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
62         word: $word, list: $list, name_value_str: $name_value_str
63     } };
64 }
65
66 macro_rules! ungated {
67     ($attr:ident, $typ:expr, $tpl:expr $(,)?) => {
68         BuiltinAttribute { name: stringify!($attr), template: $tpl }
69     };
70 }
71
72 macro_rules! gated {
73     ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => {
74         BuiltinAttribute { name: stringify!($attr), template: $tpl }
75     };
76     ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
77         BuiltinAttribute { name: stringify!($attr), template: $tpl }
78     };
79 }
80
81 macro_rules! rustc_attr {
82     (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => {
83         rustc_attr!(
84             $attr,
85             $typ,
86             $tpl,
87             concat!(
88                 "the `#[",
89                 stringify!($attr),
90                 "]` attribute is just used for rustc unit tests \
91                 and will never be stable",
92             ),
93         )
94     };
95     ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
96         BuiltinAttribute { name: stringify!($attr), template: $tpl }
97     };
98 }
99
100 /// "Inert" built-in attributes that have a special meaning to rustc or rustdoc.
101 #[rustfmt::skip]
102 pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[
103     // ==========================================================================
104     // Stable attributes:
105     // ==========================================================================
106
107     // Conditional compilation:
108     ungated!(cfg, Normal, template!(List: "predicate")),
109     ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ...")),
110
111     // Testing:
112     ungated!(ignore, Normal, template!(Word, NameValueStr: "reason")),
113     ungated!(
114         should_panic, Normal,
115         template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
116     ),
117     // FIXME(Centril): This can be used on stable but shouldn't.
118     ungated!(reexport_test_harness_main, Normal, template!(NameValueStr: "name")),
119
120     // Macros:
121     ungated!(automatically_derived, Normal, template!(Word)),
122     // FIXME(#14407)
123     ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ...")),
124     ungated!(macro_escape, Normal, template!(Word)), // Deprecated synonym for `macro_use`.
125     ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros")),
126     ungated!(proc_macro, Normal, template!(Word)),
127     ungated!(
128         proc_macro_derive, Normal,
129         template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"),
130     ),
131     ungated!(proc_macro_attribute, Normal, template!(Word)),
132
133     // Lints:
134     ungated!(warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
135     ungated!(allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
136     ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
137     ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
138     ungated!(must_use, AssumedUsed, template!(Word, NameValueStr: "reason")),
139     // FIXME(#14407)
140     ungated!(
141         deprecated, Normal,
142         template!(
143             Word,
144             List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
145             NameValueStr: "reason"
146         ),
147     ),
148
149     // Crate properties:
150     ungated!(crate_name, CrateLevel, template!(NameValueStr: "name")),
151     ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|...")),
152     ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored")),
153
154     // ABI, linking, symbols, and FFI
155     ungated!(
156         link, AssumedUsed,
157         template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...""#),
158     ),
159     ungated!(link_name, AssumedUsed, template!(NameValueStr: "name")),
160     ungated!(no_link, AssumedUsed, template!(Word)),
161     ungated!(repr, AssumedUsed, template!(List: "C")),
162     ungated!(export_name, AssumedUsed, template!(NameValueStr: "name")),
163     ungated!(link_section, AssumedUsed, template!(NameValueStr: "name")),
164     ungated!(no_mangle, AssumedUsed, template!(Word)),
165     ungated!(used, AssumedUsed, template!(Word)),
166
167     // Limits:
168     ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")),
169     ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")),
170     gated!(
171         const_eval_limit, CrateLevel, template!(NameValueStr: "N"), const_eval_limit,
172         experimental!(const_eval_limit)
173     ),
174     gated!(
175         move_size_limit, CrateLevel, template!(NameValueStr: "N"), large_assignments,
176         experimental!(move_size_limit)
177     ),
178
179     // Entry point:
180     ungated!(main, Normal, template!(Word)),
181     ungated!(start, Normal, template!(Word)),
182     ungated!(no_start, CrateLevel, template!(Word)),
183     ungated!(no_main, CrateLevel, template!(Word)),
184
185     // Modules, prelude, and resolution:
186     ungated!(path, Normal, template!(NameValueStr: "file")),
187     ungated!(no_std, CrateLevel, template!(Word)),
188     ungated!(no_implicit_prelude, Normal, template!(Word)),
189     ungated!(non_exhaustive, AssumedUsed, template!(Word)),
190
191     // Runtime
192     ungated!(windows_subsystem, AssumedUsed, template!(NameValueStr: "windows|console")),
193     ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
194
195     // Code generation:
196     ungated!(inline, AssumedUsed, template!(Word, List: "always|never")),
197     ungated!(cold, AssumedUsed, template!(Word)),
198     ungated!(no_builtins, AssumedUsed, template!(Word)),
199     ungated!(target_feature, AssumedUsed, template!(List: r#"enable = "name""#)),
200     ungated!(track_caller, AssumedUsed, template!(Word)),
201     gated!(
202         no_sanitize, AssumedUsed,
203         template!(List: "address, memory, thread"),
204         experimental!(no_sanitize)
205     ),
206     gated!(no_coverage, AssumedUsed, template!(Word), experimental!(no_coverage)),
207
208     // FIXME: #14408 assume docs are used since rustdoc looks at them.
209     ungated!(doc, AssumedUsed, template!(List: "hidden|inline|...", NameValueStr: "string")),
210
211     // ==========================================================================
212     // Unstable attributes:
213     // ==========================================================================
214
215     // Linking:
216     gated!(naked, AssumedUsed, template!(Word), naked_functions, experimental!(naked)),
217     gated!(
218         link_ordinal, AssumedUsed, template!(List: "ordinal"), raw_dylib,
219         experimental!(link_ordinal)
220     ),
221
222     // Plugins:
223     // XXX Modified for use in rust-analyzer
224     gated!(plugin_registrar, Normal, template!(Word), experimental!()),
225     gated!(plugin, CrateLevel, template!(Word), experimental!()),
226
227     // Testing:
228     gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
229     gated!(
230         test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
231         "custom test frameworks are an unstable feature",
232     ),
233     // RFC #1268
234     gated!(marker, AssumedUsed, template!(Word), marker_trait_attr, experimental!(marker)),
235     gated!(
236         thread_local, AssumedUsed, template!(Word),
237         "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
238     ),
239     gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
240     // RFC 2412
241     gated!(
242         optimize, AssumedUsed, template!(List: "size|speed"), optimize_attribute,
243         experimental!(optimize),
244     ),
245     // RFC 2867
246     gated!(instruction_set, AssumedUsed, template!(List: "set"), isa_attribute, experimental!(instruction_set)),
247
248     gated!(ffi_returns_twice, AssumedUsed, template!(Word), experimental!(ffi_returns_twice)),
249     gated!(ffi_pure, AssumedUsed, template!(Word), experimental!(ffi_pure)),
250     gated!(ffi_const, AssumedUsed, template!(Word), experimental!(ffi_const)),
251     gated!(
252         register_attr, CrateLevel, template!(List: "attr1, attr2, ..."),
253         experimental!(register_attr),
254     ),
255     gated!(
256         register_tool, CrateLevel, template!(List: "tool1, tool2, ..."),
257         experimental!(register_tool),
258     ),
259
260     gated!(cmse_nonsecure_entry, AssumedUsed, template!(Word), experimental!(cmse_nonsecure_entry)),
261     // RFC 2632
262     gated!(
263         default_method_body_is_const, AssumedUsed, template!(Word), const_trait_impl,
264         "`default_method_body_is_const` is a temporary placeholder for declaring default bodies \
265         as `const`, which may be removed or renamed in the future."
266     ),
267
268     // ==========================================================================
269     // Internal attributes: Stability, deprecation, and unsafe:
270     // ==========================================================================
271
272     ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
273     // FIXME(#14407) -- only looked at on-demand so we can't
274     // guarantee they'll have already been checked.
275     ungated!(
276         rustc_deprecated, AssumedUsed,
277         template!(List: r#"since = "version", reason = "...""#)
278     ),
279     // FIXME(#14407)
280     ungated!(stable, AssumedUsed, template!(List: r#"feature = "name", since = "version""#)),
281     // FIXME(#14407)
282     ungated!(
283         unstable, AssumedUsed,
284         template!(List: r#"feature = "name", reason = "...", issue = "N""#),
285     ),
286     // FIXME(#14407)
287     ungated!(rustc_const_unstable, AssumedUsed, template!(List: r#"feature = "name""#)),
288     // FIXME(#14407)
289     ungated!(rustc_const_stable, AssumedUsed, template!(List: r#"feature = "name""#)),
290     gated!(
291         allow_internal_unstable, AssumedUsed, template!(Word, List: "feat1, feat2, ..."),
292         "allow_internal_unstable side-steps feature gating and stability checks",
293     ),
294     gated!(
295         rustc_allow_const_fn_unstable, AssumedUsed, template!(Word, List: "feat1, feat2, ..."),
296         "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"
297     ),
298     gated!(
299         allow_internal_unsafe, Normal, template!(Word),
300         "allow_internal_unsafe side-steps the unsafe_code lint",
301     ),
302
303     // ==========================================================================
304     // Internal attributes: Type system related:
305     // ==========================================================================
306
307     gated!(fundamental, AssumedUsed, template!(Word), experimental!(fundamental)),
308     gated!(
309         may_dangle, Normal, template!(Word), dropck_eyepatch,
310         "`may_dangle` has unstable semantics and may be removed in the future",
311     ),
312
313     // ==========================================================================
314     // Internal attributes: Runtime related:
315     // ==========================================================================
316
317     rustc_attr!(rustc_allocator, AssumedUsed, template!(Word), IMPL_DETAIL),
318     rustc_attr!(rustc_allocator_nounwind, AssumedUsed, template!(Word), IMPL_DETAIL),
319     gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
320     gated!(
321         default_lib_allocator, AssumedUsed, template!(Word), allocator_internals,
322         experimental!(default_lib_allocator),
323     ),
324     gated!(
325         needs_allocator, Normal, template!(Word), allocator_internals,
326         experimental!(needs_allocator),
327     ),
328     gated!(panic_runtime, AssumedUsed, template!(Word), experimental!(panic_runtime)),
329     gated!(needs_panic_runtime, AssumedUsed, template!(Word), experimental!(needs_panic_runtime)),
330     gated!(
331         compiler_builtins, AssumedUsed, template!(Word),
332         "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
333         which contains compiler-rt intrinsics and will never be stable",
334     ),
335     gated!(
336         profiler_runtime, AssumedUsed, template!(Word),
337         "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
338         which contains the profiler runtime and will never be stable",
339     ),
340
341     // ==========================================================================
342     // Internal attributes, Linkage:
343     // ==========================================================================
344
345     gated!(
346         linkage, AssumedUsed, template!(NameValueStr: "external|internal|..."),
347         "the `linkage` attribute is experimental and not portable across platforms",
348     ),
349     rustc_attr!(rustc_std_internal_symbol, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
350
351     // ==========================================================================
352     // Internal attributes, Macro related:
353     // ==========================================================================
354
355     rustc_attr!(
356         rustc_builtin_macro, AssumedUsed,
357         template!(Word, List: "name, /*opt*/ attributes(name1, name2, ...)"),
358         IMPL_DETAIL,
359     ),
360     rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE),
361     rustc_attr!(
362         rustc_macro_transparency, AssumedUsed,
363         template!(NameValueStr: "transparent|semitransparent|opaque"),
364         "used internally for testing macro hygiene",
365     ),
366
367     // ==========================================================================
368     // Internal attributes, Diagnostics related:
369     // ==========================================================================
370
371     rustc_attr!(
372         rustc_on_unimplemented, AssumedUsed,
373         template!(
374             List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
375             NameValueStr: "message"
376         ),
377         INTERNAL_UNSTABLE
378     ),
379     // Enumerates "identity-like" conversion methods to suggest on type mismatch.
380     rustc_attr!(rustc_conversion_suggestion, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
381
382     // ==========================================================================
383     // Internal attributes, Const related:
384     // ==========================================================================
385
386     rustc_attr!(rustc_promotable, AssumedUsed, template!(Word), IMPL_DETAIL),
387     rustc_attr!(rustc_legacy_const_generics, AssumedUsed, template!(List: "N"), INTERNAL_UNSTABLE),
388
389     // ==========================================================================
390     // Internal attributes, Layout related:
391     // ==========================================================================
392
393     rustc_attr!(
394         rustc_layout_scalar_valid_range_start, AssumedUsed, template!(List: "value"),
395         "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
396         niche optimizations in libcore and will never be stable",
397     ),
398     rustc_attr!(
399         rustc_layout_scalar_valid_range_end, AssumedUsed, template!(List: "value"),
400         "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
401         niche optimizations in libcore and will never be stable",
402     ),
403     rustc_attr!(
404         rustc_nonnull_optimization_guaranteed, AssumedUsed, template!(Word),
405         "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
406         niche optimizations in libcore and will never be stable",
407     ),
408
409     // ==========================================================================
410     // Internal attributes, Misc:
411     // ==========================================================================
412     gated!(
413         lang, Normal, template!(NameValueStr: "name"), lang_items,
414         "language items are subject to change",
415     ),
416     gated!(rustc_diagnostic_item, Normal, template!(NameValueStr: "name"), experimental!()), // XXX Modified for use in rust-analyzer
417     gated!(
418         // Used in resolve:
419         prelude_import, AssumedUsed, template!(Word),
420         "`#[prelude_import]` is for use by rustc only",
421     ),
422     gated!(
423         rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
424         "unboxed_closures are still evolving",
425     ),
426     rustc_attr!(
427         rustc_inherit_overflow_checks, AssumedUsed, template!(Word),
428         "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
429         overflow checking behavior of several libcore functions that are inlined \
430         across crates and will never be stable",
431     ),
432     rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
433                 "the `#[rustc_reservation_impl]` attribute is internally used \
434                  for reserving for `for<T> From<!> for T` impl"
435     ),
436     rustc_attr!(
437         rustc_test_marker, Normal, template!(Word),
438         "the `#[rustc_test_marker]` attribute is used internally to track tests",
439     ),
440     rustc_attr!(
441         rustc_unsafe_specialization_marker, Normal, template!(Word),
442         "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
443     ),
444     rustc_attr!(
445         rustc_specialization_trait, Normal, template!(Word),
446         "the `#[rustc_specialization_trait]` attribute is used to check specializations"
447     ),
448     rustc_attr!(
449         rustc_main, Normal, template!(Word),
450         "the `#[rustc_main]` attribute is used internally to specify test entry point function",
451     ),
452     rustc_attr!(
453         rustc_skip_array_during_method_dispatch, Normal, template!(Word),
454         "the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \
455         from method dispatch when the receiver is an array, for compatibility in editions < 2021."
456     ),
457
458     // ==========================================================================
459     // Internal attributes, Testing:
460     // ==========================================================================
461
462     rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
463     rustc_attr!(TEST, rustc_capture_analysis, Normal, template!(Word)),
464     rustc_attr!(TEST, rustc_insignificant_dtor, Normal, template!(Word)),
465     rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
466     rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
467     rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
468     rustc_attr!(
469         TEST, rustc_error, AssumedUsed,
470         template!(Word, List: "delay_span_bug_from_inside_query")
471     ),
472     rustc_attr!(TEST, rustc_dump_user_substs, AssumedUsed, template!(Word)),
473     rustc_attr!(TEST, rustc_evaluate_where_clauses, AssumedUsed, template!(Word)),
474     rustc_attr!(TEST, rustc_if_this_changed, AssumedUsed, template!(Word, List: "DepNode")),
475     rustc_attr!(TEST, rustc_then_this_would_need, AssumedUsed, template!(List: "DepNode")),
476     rustc_attr!(
477         TEST, rustc_clean, AssumedUsed,
478         template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
479     ),
480     rustc_attr!(
481         TEST, rustc_partition_reused, AssumedUsed,
482         template!(List: r#"cfg = "...", module = "...""#),
483     ),
484     rustc_attr!(
485         TEST, rustc_partition_codegened, AssumedUsed,
486         template!(List: r#"cfg = "...", module = "...""#),
487     ),
488     rustc_attr!(
489         TEST, rustc_expected_cgu_reuse, AssumedUsed,
490         template!(List: r#"cfg = "...", module = "...", kind = "...""#),
491     ),
492     rustc_attr!(TEST, rustc_synthetic, AssumedUsed, template!(Word)),
493     rustc_attr!(TEST, rustc_symbol_name, AssumedUsed, template!(Word)),
494     rustc_attr!(TEST, rustc_polymorphize_error, AssumedUsed, template!(Word)),
495     rustc_attr!(TEST, rustc_def_path, AssumedUsed, template!(Word)),
496     rustc_attr!(TEST, rustc_mir, AssumedUsed, template!(List: "arg1, arg2, ...")),
497     rustc_attr!(TEST, rustc_dump_program_clauses, AssumedUsed, template!(Word)),
498     rustc_attr!(TEST, rustc_dump_env_program_clauses, AssumedUsed, template!(Word)),
499     rustc_attr!(TEST, rustc_object_lifetime_default, AssumedUsed, template!(Word)),
500     rustc_attr!(TEST, rustc_dump_vtable, AssumedUsed, template!(Word)),
501     rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
502     gated!(
503         omit_gdb_pretty_printer_section, AssumedUsed, template!(Word),
504         "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
505     ),
506 ];