Skip to main content

rustc_feature/
builtin_attrs.rs

1//! Built-in attributes and `cfg` flag gating.
2
3use std::sync::LazyLock;
4
5use rustc_data_structures::fx::FxHashSet;
6use rustc_span::{Symbol, sym};
7
8use crate::Features;
9
10type GateFn = fn(&Features) -> bool;
11
12pub type GatedCfg = (Symbol, Symbol, GateFn);
13
14/// `cfg(...)`'s that are feature gated.
15const GATED_CFGS: &[GatedCfg] = &[
16    // (name in cfg, feature, function to check if the feature is enabled)
17    (sym::overflow_checks, sym::cfg_overflow_checks, Features::cfg_overflow_checks),
18    (sym::ub_checks, sym::cfg_ub_checks, Features::cfg_ub_checks),
19    (sym::contract_checks, sym::cfg_contract_checks, Features::cfg_contract_checks),
20    (sym::target_thread_local, sym::cfg_target_thread_local, Features::cfg_target_thread_local),
21    (
22        sym::target_has_atomic_load_store,
23        sym::cfg_target_has_atomic,
24        Features::cfg_target_has_atomic,
25    ),
26    (sym::sanitize, sym::cfg_sanitize, Features::cfg_sanitize),
27    (sym::version, sym::cfg_version, Features::cfg_version),
28    (sym::relocation_model, sym::cfg_relocation_model, Features::cfg_relocation_model),
29    (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
30    (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
31    // this is consistent with naming of the compiler flag it's for
32    (sym::fmt_debug, sym::fmt_debug, Features::fmt_debug),
33    (
34        sym::target_has_reliable_f16,
35        sym::cfg_target_has_reliable_f16_f128,
36        Features::cfg_target_has_reliable_f16_f128,
37    ),
38    (
39        sym::target_has_reliable_f16_math,
40        sym::cfg_target_has_reliable_f16_f128,
41        Features::cfg_target_has_reliable_f16_f128,
42    ),
43    (
44        sym::target_has_reliable_f128,
45        sym::cfg_target_has_reliable_f16_f128,
46        Features::cfg_target_has_reliable_f16_f128,
47    ),
48    (
49        sym::target_has_reliable_f128_math,
50        sym::cfg_target_has_reliable_f16_f128,
51        Features::cfg_target_has_reliable_f16_f128,
52    ),
53    (sym::target_has_threads, sym::cfg_target_has_threads, Features::cfg_target_has_threads),
54    (sym::target_object_format, sym::cfg_target_object_format, Features::cfg_target_object_format),
55];
56
57/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
58pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
59    GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
60}
61
62#[derive(#[automatically_derived]
impl ::core::clone::Clone for AttributeStability {
    #[inline]
    fn clone(&self) -> AttributeStability {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<fn(&Features) -> bool>;
        let _: ::core::clone::AssertParamIsClone<&'static [&'static str]>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AttributeStability {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AttributeStability::Unstable {
                gate_name: __self_0, gate_check: __self_1, notes: __self_2 }
                =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Unstable", "gate_name", __self_0, "gate_check", __self_1,
                    "notes", &__self_2),
            AttributeStability::Stable =>
                ::core::fmt::Formatter::write_str(f, "Stable"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for AttributeStability { }Copy)]
63pub enum AttributeStability {
64    /// An attribute that is unstable behind a specified feature fagte
65    Unstable {
66        /// The feature gate, for example `rustc_attrs` for rustc_* attributes.
67        gate_name: Symbol,
68        /// Check function to be called during the `PostExpansionVisitor` pass, which will be one of the `Features::*` functions
69        gate_check: fn(&Features) -> bool,
70        /// Notes to be displayed when an attempt is made to use the attribute without its feature gate.
71        notes: &'static [&'static str],
72    },
73    /// A stable attribute, can be used on all release channels
74    Stable,
75}
76
77/// Attributes that have a special meaning to rustc or rustdoc.
78#[rustfmt::skip]
79pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[
80    // ==========================================================================
81    // Stable attributes:
82    // ==========================================================================
83
84    // Conditional compilation:
85    sym::cfg,
86    sym::cfg_attr,
87
88    // Testing:
89    sym::ignore,
90    sym::should_panic,
91
92    // Macros:
93    sym::automatically_derived,
94    sym::macro_use,
95    sym::macro_escape, // Deprecated synonym for `macro_use`.
96    sym::macro_export,
97    sym::proc_macro,
98    sym::proc_macro_derive,
99    sym::proc_macro_attribute,
100
101    // Lints:
102    sym::warn,
103    sym::allow,
104    sym::expect,
105    sym::forbid,
106    sym::deny,
107    sym::must_use,
108    sym::must_not_suspend,
109    sym::deprecated,
110
111    // Crate properties:
112    sym::crate_name,
113    sym::crate_type,
114
115    // ABI, linking, symbols, and FFI
116    sym::link,
117    sym::link_name,
118    sym::no_link,
119    sym::repr,
120    // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity
121    sym::rustc_align,
122    sym::rustc_align_static,
123    sym::export_name,
124    sym::link_section,
125    sym::no_mangle,
126    sym::used,
127    sym::link_ordinal,
128    sym::naked,
129    // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
130    sym::rustc_pass_indirectly_in_non_rustic_abis,
131
132    // Limits:
133    sym::recursion_limit,
134    sym::type_length_limit,
135    sym::move_size_limit,
136
137    // Entry point:
138    sym::no_main,
139
140    // Modules, prelude, and resolution:
141    sym::path,
142    sym::no_std,
143    sym::no_implicit_prelude,
144    sym::non_exhaustive,
145
146    // Runtime
147    sym::windows_subsystem,
148    sym::panic_handler, // RFC 2070
149
150    // Code generation:
151    sym::inline,
152    sym::cold,
153    sym::no_builtins,
154    sym::target_feature,
155    sym::track_caller,
156    sym::instruction_set,
157    sym::force_target_feature,
158    sym::sanitize,
159    sym::coverage,
160
161    sym::doc,
162
163    // Debugging
164    sym::debugger_visualizer,
165    sym::collapse_debuginfo,
166
167    // ==========================================================================
168    // Unstable attributes:
169    // ==========================================================================
170
171    // Linking:
172    sym::export_stable,
173
174    // Testing:
175    sym::test_runner,
176
177    sym::reexport_test_harness_main,
178
179    // RFC #1268
180    sym::marker,
181    sym::thread_local,
182    sym::no_core,
183    // RFC 2412
184    sym::optimize,
185
186    sym::ffi_pure,
187    sym::ffi_const,
188    sym::register_tool,
189    // `#[cfi_encoding = ""]`
190    sym::cfi_encoding,
191
192    // `#[coroutine]` attribute to be applied to closures to make them coroutines instead
193    sym::coroutine,
194
195    // RFC 3543
196    // `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]`
197    sym::patchable_function_entry,
198
199    // The `#[loop_match]` and `#[const_continue]` attributes are part of the
200    // lang experiment for RFC 3720 tracked in:
201    //
202    // - https://github.com/rust-lang/rust/issues/132306
203    sym::const_continue,
204    sym::loop_match,
205
206    // The `#[pin_v2]` attribute is part of the `pin_ergonomics` experiment
207    // that allows structurally pinning, tracked in:
208    //
209    // - https://github.com/rust-lang/rust/issues/130494
210    sym::pin_v2,
211
212    // The `#[splat]` attribute is part of the `splat` experiment
213    // that improves the ergonomics of function overloading, tracked in:
214    //
215    // - https://github.com/rust-lang/rust/issues/153629
216    sym::splat,
217
218    // The `#[unroll]` attribute.
219    //
220    // - https://github.com/rust-lang/rust/pull/156816
221    sym::unroll,
222
223    // `#[instrument_fn = "on|off"]` to insert or inhibit instrumentation function
224    // calls inside a function, usually around the prologue.
225    //
226    // - https://github.com/rust-lang/rust/issues/157081
227    sym::instrument_fn,
228
229    // ==========================================================================
230    // Internal attributes: Stability, deprecation, and unsafe:
231    // ==========================================================================
232
233    sym::feature,
234    // DuplicatesOk since it has its own validation
235    sym::stable,
236    sym::unstable,
237    sym::unstable_feature_bound,
238    sym::unstable_removed,
239    sym::rustc_const_unstable,
240    sym::rustc_const_stable,
241    sym::rustc_default_body_unstable,
242    sym::allow_internal_unstable,
243    sym::allow_internal_unsafe,
244    sym::rustc_eii_foreign_item,
245    sym::rustc_allowed_through_unstable_modules,
246    sym::rustc_deprecated_safe_2024,
247    sym::rustc_pub_transparent,
248
249    // ==========================================================================
250    // Internal attributes: Type system related:
251    // ==========================================================================
252
253    sym::fundamental,
254    sym::may_dangle,
255
256    sym::rustc_never_type_options,
257
258    // ==========================================================================
259    // Internal attributes: Runtime related:
260    // ==========================================================================
261
262    sym::rustc_allocator,
263    sym::rustc_nounwind,
264    sym::rustc_reallocator,
265    sym::rustc_deallocator,
266    sym::rustc_allocator_zeroed,
267    sym::rustc_allocator_zeroed_variant,
268    sym::default_lib_allocator,
269    sym::needs_allocator,
270    sym::panic_runtime,
271    sym::needs_panic_runtime,
272    sym::compiler_builtins,
273    sym::profiler_runtime,
274
275    // ==========================================================================
276    // Internal attributes, Linkage:
277    // ==========================================================================
278
279    sym::linkage,
280    sym::rustc_std_internal_symbol,
281    sym::rustc_objc_class,
282    sym::rustc_objc_selector,
283
284    // ==========================================================================
285    // Internal attributes, Macro related:
286    // ==========================================================================
287
288    sym::rustc_builtin_macro,
289    sym::rustc_proc_macro_decls,
290    sym::rustc_macro_transparency,
291    sym::rustc_autodiff,
292    sym::rustc_offload_kernel,
293
294    // ==========================================================================
295    // Internal attributes, Diagnostics related:
296    // ==========================================================================
297
298    sym::rustc_on_unimplemented,
299    sym::rustc_confusables,
300    // Enumerates "identity-like" conversion methods to suggest on type mismatch.
301    sym::rustc_conversion_suggestion,
302    // Prevents field reads in the marked trait or method to be considered
303    // during dead code analysis.
304    sym::rustc_trivial_field_reads,
305    // Used by the `rustc::potential_query_instability` lint to warn methods which
306    // might not be stable during incremental compilation.
307    sym::rustc_lint_query_instability,
308    // Used by the `rustc::untracked_query_information` lint to warn methods which
309    // might not be stable during incremental compilation.
310    sym::rustc_lint_untracked_query_information,
311    // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions`
312    // types (as well as any others in future).
313    sym::rustc_lint_opt_ty,
314    // Used by the `rustc::bad_opt_access` lint on fields
315    // types (as well as any others in future).
316    sym::rustc_lint_opt_deny_field_access,
317    sym::rustc_diagnostic_opaque,
318
319    // ==========================================================================
320    // Internal attributes, Const related:
321    // ==========================================================================
322
323    sym::rustc_promotable,
324    sym::rustc_legacy_const_generics,
325    // Do not const-check this function's body. It will always get replaced during CTFE via `hook_special_const_fn`.
326    sym::rustc_do_not_const_check,
327    sym::rustc_const_stable_indirect,
328    sym::rustc_intrinsic_const_stable_indirect,
329    sym::rustc_allow_const_fn_unstable,
330
331    // ==========================================================================
332    // Internal attributes, Layout related:
333    // ==========================================================================
334
335    sym::rustc_simd_monomorphize_lane_limit,
336    sym::rustc_nonnull_optimization_guaranteed,
337
338    // ==========================================================================
339    // Internal attributes, Misc:
340    // ==========================================================================
341    sym::lang,
342    sym::rustc_as_ptr,
343    sym::rustc_should_not_be_called_on_const_items,
344    sym::rustc_pass_by_value,
345    sym::rustc_never_returns_null_ptr,
346    sym::rustc_no_implicit_autorefs,
347    sym::rustc_coherence_is_core,
348    sym::rustc_coinductive,
349    sym::rustc_comptime,
350    sym::rustc_allow_incoherent_impl,
351    sym::rustc_preserve_ub_checks,
352    sym::rustc_deny_explicit_impl,
353    sym::rustc_dyn_incompatible_trait,
354    sym::rustc_has_incoherent_inherent_impls,
355    sym::rustc_non_const_trait_method,
356
357    sym::rustc_canonical_symbol,
358    sym::rustc_diagnostic_item,
359    sym::prelude_import,
360    sym::rustc_paren_sugar,
361    sym::rustc_inherit_overflow_checks,
362    sym::rustc_reservation_impl,
363    sym::rustc_test_entrypoint_marker,
364    sym::rustc_test_marker,
365    sym::rustc_unsafe_specialization_marker,
366    sym::rustc_specialization_trait,
367    sym::rustc_main,
368    sym::rustc_skip_during_method_dispatch,
369    sym::rustc_must_implement_one_of,
370    sym::rustc_doc_primitive,
371    sym::rustc_intrinsic,
372    sym::rustc_no_mir_inline,
373    sym::rustc_force_inline,
374    sym::rustc_scalable_vector,
375    sym::rustc_must_match_exhaustively,
376    sym::rustc_no_writable,
377
378    // ==========================================================================
379    // Internal attributes, Testing:
380    // ==========================================================================
381
382    sym::rustc_effective_visibility,
383    sym::rustc_dump_inferred_outlives,
384    sym::rustc_capture_analysis,
385    sym::rustc_insignificant_dtor,
386    sym::rustc_no_implicit_bounds,
387    sym::rustc_strict_coherence,
388    sym::rustc_dump_variances,
389    sym::rustc_dump_variances_of_opaques,
390    sym::rustc_dump_generics,
391    sym::rustc_dump_hidden_type_of_opaques,
392    sym::rustc_dump_layout,
393    sym::rustc_abi,
394    sym::rustc_regions,
395    sym::rustc_delayed_bug_from_inside_query,
396    sym::rustc_dump_user_args,
397    sym::rustc_evaluate_where_clauses,
398    sym::rustc_if_this_changed,
399    sym::rustc_then_this_would_need,
400    sym::rustc_clean,
401    sym::rustc_partition_reused,
402    sym::rustc_partition_codegened,
403    sym::rustc_expected_cgu_reuse,
404    sym::rustc_dump_symbol_name,
405    sym::rustc_dump_def_path,
406    sym::rustc_mir,
407    sym::custom_mir,
408    sym::rustc_dump_item_bounds,
409    sym::rustc_dump_predicates,
410    sym::rustc_dump_def_parents,
411    sym::rustc_dump_object_lifetime_defaults,
412    sym::rustc_dump_vtable,
413    sym::rustc_dummy,
414    sym::pattern_complexity_limit,
415];
416
417pub fn is_builtin_attr_name(name: Symbol) -> bool {
418    BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
419}
420
421pub static BUILTIN_ATTRIBUTE_MAP: LazyLock<FxHashSet<Symbol>> = LazyLock::new(|| {
422    let mut map = FxHashSet::default();
423    for attr in BUILTIN_ATTRIBUTES.iter() {
424        if !map.insert(*attr) {
425            {
    ::core::panicking::panic_fmt(format_args!("duplicate builtin attribute `{0}`",
            attr));
};panic!("duplicate builtin attribute `{}`", attr);
426        }
427    }
428    map
429});