Skip to main content

rustc_feature/
lib.rs

1//! # Feature gates
2//!
3//! This crate declares the set of past and present unstable features in the compiler.
4//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
5//! at the moment.
6//!
7//! Features are enabled in programs via the crate-level attributes of
8//! `#![feature(...)]` with a comma-separated list of features.
9//!
10//! For the purpose of future feature-tracking, once a feature gate is added,
11//! even if it is stabilized or removed, *do not remove it*. Instead, move the
12//! symbol to the `accepted` or `removed` modules respectively.
13
14mod accepted;
15mod builtin_attrs;
16mod removed;
17mod unstable;
18
19#[cfg(test)]
20mod tests;
21
22use std::num::NonZero;
23
24use rustc_span::Symbol;
25
26#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Feature {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Feature",
            "name", &self.name, "since", &self.since, "issue", &&self.issue)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Feature {
    #[inline]
    fn clone(&self) -> Feature {
        Feature {
            name: ::core::clone::Clone::clone(&self.name),
            since: ::core::clone::Clone::clone(&self.since),
            issue: ::core::clone::Clone::clone(&self.issue),
        }
    }
}Clone)]
27pub struct Feature {
28    pub name: Symbol,
29    /// For unstable features: the version the feature was added in.
30    /// For accepted features: the version the feature got stabilized in.
31    /// For removed features we are inconsistent; sometimes this is the
32    /// version it got added, sometimes the version it got removed.
33    pub since: &'static str,
34    issue: Option<NonZero<u32>>,
35}
36
37#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnstableFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for UnstableFeatures {
    #[inline]
    fn clone(&self) -> UnstableFeatures { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for UnstableFeatures { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for UnstableFeatures {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                UnstableFeatures::Disallow => "Disallow",
                UnstableFeatures::Allow => "Allow",
                UnstableFeatures::Cheat => "Cheat",
            })
    }
}Debug, #[automatically_derived]
impl ::core::hash::Hash for UnstableFeatures {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
38pub enum UnstableFeatures {
39    /// Disallow use of unstable features, as on beta/stable channels.
40    Disallow,
41    /// Allow use of unstable features, as on nightly.
42    Allow,
43    /// Errors are bypassed for bootstrapping. This is required any time
44    /// during the build that feature-related lints are set to warn or above
45    /// because the build turns on warnings-as-errors and uses lots of unstable
46    /// features. As a result, this is always required for building Rust itself.
47    Cheat,
48}
49
50impl UnstableFeatures {
51    /// This takes into account `RUSTC_BOOTSTRAP`.
52    ///
53    /// If `krate` is [`Some`], then setting `RUSTC_BOOTSTRAP=krate` will enable the nightly
54    /// features. Otherwise, only `RUSTC_BOOTSTRAP=1` will work.
55    pub fn from_environment(krate: Option<&str>) -> Self {
56        Self::from_environment_value(krate, std::env::var("RUSTC_BOOTSTRAP"))
57    }
58
59    /// Avoid unsafe `std::env::set_var()` by allowing tests to inject
60    /// `std::env::var("RUSTC_BOOTSTRAP")` with the `env_var_rustc_bootstrap`
61    /// arg.
62    fn from_environment_value(
63        krate: Option<&str>,
64        env_var_rustc_bootstrap: Result<String, std::env::VarError>,
65    ) -> Self {
66        // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
67        let disable_unstable_features =
68            ::core::option::Option::None::<&'static str>option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some_and(|s| s != "0");
69        // Returns whether `krate` should be counted as unstable
70        let is_unstable_crate =
71            |var: &str| krate.is_some_and(|name| var.split(',').any(|new_krate| new_krate == name));
72
73        if let Ok(val) = env_var_rustc_bootstrap.as_deref() {
74            match val {
75                val if val == "1" || is_unstable_crate(val) => return UnstableFeatures::Cheat,
76                // Hypnotize ourselves so that we think we are a stable compiler and thus don't
77                // allow any unstable features.
78                "-1" => return UnstableFeatures::Disallow,
79                _ => {}
80            }
81        }
82
83        if disable_unstable_features { UnstableFeatures::Disallow } else { UnstableFeatures::Allow }
84    }
85
86    pub fn is_nightly_build(&self) -> bool {
87        match *self {
88            UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
89            UnstableFeatures::Disallow => false,
90        }
91    }
92}
93
94fn find_lang_feature_issue(feature: Symbol) -> Option<NonZero<u32>> {
95    // Search in all the feature lists.
96    if let Some(f) = UNSTABLE_LANG_FEATURES.iter().find(|f| f.name == feature) {
97        return f.issue;
98    }
99    if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature) {
100        return f.issue;
101    }
102    if let Some(f) = REMOVED_LANG_FEATURES.iter().find(|f| f.feature.name == feature) {
103        return f.feature.issue;
104    }
105    {
    ::core::panicking::panic_fmt(format_args!("feature `{0}` is not declared anywhere",
            feature));
};panic!("feature `{feature}` is not declared anywhere");
106}
107
108const fn to_nonzero(n: Option<u32>) -> Option<NonZero<u32>> {
109    // Can be replaced with `n.and_then(NonZero::new)` if that is ever usable
110    // in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
111    match n {
112        None => None,
113        Some(n) => NonZero::new(n),
114    }
115}
116
117pub enum GateIssue {
118    Language,
119    Library(Option<NonZero<u32>>),
120}
121
122pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u32>> {
123    match issue {
124        GateIssue::Language => find_lang_feature_issue(feature),
125        GateIssue::Library(lib) => lib,
126    }
127}
128
129pub use accepted::ACCEPTED_LANG_FEATURES;
130pub use builtin_attrs::{
131    AttributeStability, BUILTIN_ATTRIBUTE_SET, BUILTIN_ATTRIBUTES, GatedCfg, find_gated_cfg,
132    is_builtin_attr_name,
133};
134pub use removed::REMOVED_LANG_FEATURES;
135pub use unstable::{
136    DEPENDENT_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, INCOMPATIBLE_FEATURES,
137    TRACK_FEATURE, UNSTABLE_LANG_FEATURES,
138};