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(Debug, 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(Clone, Copy, Debug, 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            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        let bootstrap = env_var_rustc_bootstrap.ok();
74        if let Some(val) = bootstrap.as_deref() {
75            match val {
76                val if val == "1" || is_unstable_crate(val) => return UnstableFeatures::Cheat,
77                // Hypnotize ourselves so that we think we are a stable compiler and thus don't
78                // allow any unstable features.
79                "-1" => return UnstableFeatures::Disallow,
80                _ => {}
81            }
82        }
83
84        if disable_unstable_features { UnstableFeatures::Disallow } else { UnstableFeatures::Allow }
85    }
86
87    pub fn is_nightly_build(&self) -> bool {
88        match *self {
89            UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
90            UnstableFeatures::Disallow => false,
91        }
92    }
93}
94
95fn find_lang_feature_issue(feature: Symbol) -> Option<NonZero<u32>> {
96    // Search in all the feature lists.
97    if let Some(f) = UNSTABLE_LANG_FEATURES.iter().find(|f| f.name == feature) {
98        return f.issue;
99    }
100    if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature) {
101        return f.issue;
102    }
103    if let Some(f) = REMOVED_LANG_FEATURES.iter().find(|f| f.feature.name == feature) {
104        return f.feature.issue;
105    }
106    panic!("feature `{feature}` is not declared anywhere");
107}
108
109const fn to_nonzero(n: Option<u32>) -> Option<NonZero<u32>> {
110    // Can be replaced with `n.and_then(NonZero::new)` if that is ever usable
111    // in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
112    match n {
113        None => None,
114        Some(n) => NonZero::new(n),
115    }
116}
117
118pub enum GateIssue {
119    Language,
120    Library(Option<NonZero<u32>>),
121}
122
123pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u32>> {
124    match issue {
125        GateIssue::Language => find_lang_feature_issue(feature),
126        GateIssue::Library(lib) => lib,
127    }
128}
129
130pub use accepted::ACCEPTED_LANG_FEATURES;
131pub use builtin_attrs::{
132    AttrSuggestionStyle, AttributeDuplicates, AttributeGate, AttributeSafety, AttributeTemplate,
133    AttributeType, BUILTIN_ATTRIBUTE_MAP, BUILTIN_ATTRIBUTES, BuiltinAttribute, GatedCfg,
134    encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135    is_valid_for_get_attr,
136};
137pub use removed::REMOVED_LANG_FEATURES;
138pub use unstable::{
139    EnabledLangFeature, EnabledLibFeature, Features, INCOMPATIBLE_FEATURES, UNSTABLE_LANG_FEATURES,
140};