Skip to main content

cargo/core/
features.rs

1//! Support for nightly features in Cargo itself
2//!
3//! This file is the version of `feature_gate.rs` in upstream Rust for Cargo
4//! itself and is intended to be the avenue for which new features in Cargo are
5//! gated by default and then eventually stabilized. All known stable and
6//! unstable features are tracked in this file.
7//!
8//! If you're reading this then you're likely interested in adding a feature to
9//! Cargo, and the good news is that it shouldn't be too hard! To do this you'll
10//! want to follow these steps:
11//!
12//! 1. Add your feature. Do this by searching for "look here" in this file and
13//!    expanding the macro invocation that lists all features with your new
14//!    feature.
15//!
16//! 2. Find the appropriate place to place the feature gate in Cargo itself. If
17//!    you're extending the manifest format you'll likely just want to modify
18//!    the `Manifest::feature_gate` function, but otherwise you may wish to
19//!    place the feature gate elsewhere in Cargo.
20//!
21//! 3. To actually perform the feature gate, you'll want to have code that looks
22//!    like:
23//!
24//! ```rust,ignore
25//! use core::{Feature, Features};
26//!
27//! let feature = Feature::launch_into_space();
28//! package.manifest().features().require(feature).chain_err(|| {
29//!     "launching Cargo into space right now is unstable and may result in \
30//!      unintended damage to your codebase, use with caution"
31//! })?;
32//! ```
33//!
34//! Notably you'll notice the `require` function called with your `Feature`, and
35//! then you use `chain_err` to tack on more context for why the feature was
36//! required when the feature isn't activated.
37//!
38//! 4. Update the unstable documentation at
39//!    `src/doc/src/reference/unstable.md` to include a short description of
40//!    how to use your new feature.  When the feature is stabilized, be sure
41//!    that the Cargo Guide or Reference is updated to fully document the
42//!    feature and remove the entry from the Unstable section.
43//!
44//! And hopefully that's it! Bear with us though that this is, at the time of
45//! this writing, a very new feature in Cargo. If the process differs from this
46//! we'll be sure to update this documentation!
47
48use std::cell::Cell;
49use std::env;
50use std::fmt;
51use std::str::FromStr;
52
53use failure::Error;
54use serde::{Deserialize, Serialize};
55
56use crate::util::errors::CargoResult;
57
58/// The edition of the compiler (RFC 2052)
59#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, Eq, PartialEq, Serialize, Deserialize)]
60pub enum Edition {
61    /// The 2015 edition
62    Edition2015,
63    /// The 2018 edition
64    Edition2018,
65}
66
67impl fmt::Display for Edition {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match *self {
70            Edition::Edition2015 => f.write_str("2015"),
71            Edition::Edition2018 => f.write_str("2018"),
72        }
73    }
74}
75impl FromStr for Edition {
76    type Err = Error;
77    fn from_str(s: &str) -> Result<Self, Error> {
78        match s {
79            "2015" => Ok(Edition::Edition2015),
80            "2018" => Ok(Edition::Edition2018),
81            s => failure::bail!(
82                "supported edition values are `2015` or `2018`, but `{}` \
83                 is unknown",
84                s
85            ),
86        }
87    }
88}
89
90#[derive(PartialEq)]
91enum Status {
92    Stable,
93    Unstable,
94}
95
96macro_rules! features {
97    (
98        pub struct Features {
99            $([$stab:ident] $feature:ident: bool,)*
100        }
101    ) => (
102        #[derive(Default, Clone, Debug)]
103        pub struct Features {
104            $($feature: bool,)*
105            activated: Vec<String>,
106        }
107
108        impl Feature {
109            $(
110                pub fn $feature() -> &'static Feature {
111                    fn get(features: &Features) -> bool {
112                        stab!($stab) == Status::Stable || features.$feature
113                    }
114                    static FEAT: Feature = Feature {
115                        name: stringify!($feature),
116                        get,
117                    };
118                    &FEAT
119                }
120            )*
121
122            fn is_enabled(&self, features: &Features) -> bool {
123                (self.get)(features)
124            }
125        }
126
127        impl Features {
128            fn status(&mut self, feature: &str) -> Option<(&mut bool, Status)> {
129                if feature.contains("_") {
130                    return None
131                }
132                let feature = feature.replace("-", "_");
133                $(
134                    if feature == stringify!($feature) {
135                        return Some((&mut self.$feature, stab!($stab)))
136                    }
137                )*
138                None
139            }
140        }
141    )
142}
143
144macro_rules! stab {
145    (stable) => {
146        Status::Stable
147    };
148    (unstable) => {
149        Status::Unstable
150    };
151}
152
153/// A listing of all features in Cargo
154///
155/// "look here"
156///
157/// This is the macro that lists all stable and unstable features in Cargo.
158/// You'll want to add to this macro whenever you add a feature to Cargo, also
159/// following the directions above.
160///
161/// Note that all feature names here are valid Rust identifiers, but the `_`
162/// character is translated to `-` when specified in the `cargo-features`
163/// manifest entry in `Cargo.toml`.
164features! {
165    pub struct Features {
166
167        // A dummy feature that doesn't actually gate anything, but it's used in
168        // testing to ensure that we can enable stable features.
169        [stable] test_dummy_stable: bool,
170
171        // A dummy feature that gates the usage of the `im-a-teapot` manifest
172        // entry. This is basically just intended for tests.
173        [unstable] test_dummy_unstable: bool,
174
175        // Downloading packages from alternative registry indexes.
176        [unstable] alternative_registries: bool,
177
178        // Using editions
179        [stable] edition: bool,
180
181        // Renaming a package in the manifest via the `package` key
182        [stable] rename_dependency: bool,
183
184        // Whether a lock file is published with this crate
185        [unstable] publish_lockfile: bool,
186
187        // Overriding profiles for dependencies.
188        [unstable] profile_overrides: bool,
189
190        // Separating the namespaces for features and dependencies
191        [unstable] namespaced_features: bool,
192
193        // "default-run" manifest option,
194        [unstable] default_run: bool,
195
196        // Declarative build scripts.
197        [unstable] metabuild: bool,
198    }
199}
200
201pub struct Feature {
202    name: &'static str,
203    get: fn(&Features) -> bool,
204}
205
206impl Features {
207    pub fn new(features: &[String], warnings: &mut Vec<String>) -> CargoResult<Features> {
208        let mut ret = Features::default();
209        for feature in features {
210            ret.add(feature, warnings)?;
211            ret.activated.push(feature.to_string());
212        }
213        Ok(ret)
214    }
215
216    fn add(&mut self, feature: &str, warnings: &mut Vec<String>) -> CargoResult<()> {
217        let (slot, status) = match self.status(feature) {
218            Some(p) => p,
219            None => failure::bail!("unknown cargo feature `{}`", feature),
220        };
221
222        if *slot {
223            failure::bail!("the cargo feature `{}` has already been activated", feature);
224        }
225
226        match status {
227            Status::Stable => {
228                let warning = format!(
229                    "the cargo feature `{}` is now stable \
230                     and is no longer necessary to be listed \
231                     in the manifest",
232                    feature
233                );
234                warnings.push(warning);
235            }
236            Status::Unstable if !nightly_features_allowed() => failure::bail!(
237                "the cargo feature `{}` requires a nightly version of \
238                 Cargo, but this is the `{}` channel",
239                feature,
240                channel()
241            ),
242            Status::Unstable => {}
243        }
244
245        *slot = true;
246
247        Ok(())
248    }
249
250    pub fn activated(&self) -> &[String] {
251        &self.activated
252    }
253
254    pub fn require(&self, feature: &Feature) -> CargoResult<()> {
255        if feature.is_enabled(self) {
256            Ok(())
257        } else {
258            let feature = feature.name.replace("_", "-");
259            let mut msg = format!("feature `{}` is required", feature);
260
261            if nightly_features_allowed() {
262                let s = format!(
263                    "\n\nconsider adding `cargo-features = [\"{0}\"]` \
264                     to the manifest",
265                    feature
266                );
267                msg.push_str(&s);
268            } else {
269                let s = format!(
270                    "\n\n\
271                     this Cargo does not support nightly features, but if you\n\
272                     switch to nightly channel you can add\n\
273                     `cargo-features = [\"{}\"]` to enable this feature",
274                    feature
275                );
276                msg.push_str(&s);
277            }
278            failure::bail!("{}", msg);
279        }
280    }
281
282    pub fn is_enabled(&self, feature: &Feature) -> bool {
283        feature.is_enabled(self)
284    }
285}
286
287/// A parsed representation of all unstable flags that Cargo accepts.
288///
289/// Cargo, like `rustc`, accepts a suite of `-Z` flags which are intended for
290/// gating unstable functionality to Cargo. These flags are only available on
291/// the nightly channel of Cargo.
292///
293/// This struct doesn't have quite the same convenience macro that the features
294/// have above, but the procedure should still be relatively stable for adding a
295/// new unstable flag:
296///
297/// 1. First, add a field to this `CliUnstable` structure. All flags are allowed
298///    to have a value as the `-Z` flags are either of the form `-Z foo` or
299///    `-Z foo=bar`, and it's up to you how to parse `bar`.
300///
301/// 2. Add an arm to the match statement in `CliUnstable::add` below to match on
302///    your new flag. The key (`k`) is what you're matching on and the value is
303///    in `v`.
304///
305/// 3. (optional) Add a new parsing function to parse your datatype. As of now
306///    there's an example for `bool`, but more can be added!
307///
308/// 4. In Cargo use `config.cli_unstable()` to get a reference to this structure
309///    and then test for your flag or your value and act accordingly.
310///
311/// If you have any trouble with this, please let us know!
312#[derive(Default, Debug)]
313pub struct CliUnstable {
314    pub print_im_a_teapot: bool,
315    pub unstable_options: bool,
316    pub offline: bool,
317    pub no_index_update: bool,
318    pub avoid_dev_deps: bool,
319    pub minimal_versions: bool,
320    pub package_features: bool,
321    pub advanced_env: bool,
322    pub config_profile: bool,
323}
324
325impl CliUnstable {
326    pub fn parse(&mut self, flags: &[String]) -> CargoResult<()> {
327        if !flags.is_empty() && !nightly_features_allowed() {
328            failure::bail!("the `-Z` flag is only accepted on the nightly channel of Cargo")
329        }
330        for flag in flags {
331            self.add(flag)?;
332        }
333        Ok(())
334    }
335
336    fn add(&mut self, flag: &str) -> CargoResult<()> {
337        let mut parts = flag.splitn(2, '=');
338        let k = parts.next().unwrap();
339        let v = parts.next();
340
341        fn parse_bool(value: Option<&str>) -> CargoResult<bool> {
342            match value {
343                None | Some("yes") => Ok(true),
344                Some("no") => Ok(false),
345                Some(s) => failure::bail!("expected `no` or `yes`, found: {}", s),
346            }
347        }
348
349        match k {
350            "print-im-a-teapot" => self.print_im_a_teapot = parse_bool(v)?,
351            "unstable-options" => self.unstable_options = true,
352            "offline" => self.offline = true,
353            "no-index-update" => self.no_index_update = true,
354            "avoid-dev-deps" => self.avoid_dev_deps = true,
355            "minimal-versions" => self.minimal_versions = true,
356            "package-features" => self.package_features = true,
357            "advanced-env" => self.advanced_env = true,
358            "config-profile" => self.config_profile = true,
359            _ => failure::bail!("unknown `-Z` flag specified: {}", k),
360        }
361
362        Ok(())
363    }
364}
365
366fn channel() -> String {
367    if let Ok(override_channel) = env::var("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS") {
368        return override_channel;
369    }
370    if let Ok(staging) = env::var("RUSTC_BOOTSTRAP") {
371        if staging == "1" {
372            return "dev".to_string();
373        }
374    }
375    crate::version()
376        .cfg_info
377        .map(|c| c.release_channel)
378        .unwrap_or_else(|| String::from("dev"))
379}
380
381thread_local!(
382    static NIGHTLY_FEATURES_ALLOWED: Cell<bool> = Cell::new(false);
383    static ENABLE_NIGHTLY_FEATURES: Cell<bool> = Cell::new(false);
384);
385
386/// This is a little complicated.
387/// This should return false if:
388/// - this is an artifact of the rustc distribution process for "stable" or for "beta"
389/// - this is an `#[test]` that does not opt in with `enable_nightly_features`
390/// - this is a integration test that uses `ProcessBuilder`
391///      that does not opt in with `masquerade_as_nightly_cargo`
392/// This should return true if:
393/// - this is an artifact of the rustc distribution process for "nightly"
394/// - this is being used in the rustc distribution process internally
395/// - this is a cargo executable that was built from source
396/// - this is an `#[test]` that called `enable_nightly_features`
397/// - this is a integration test that uses `ProcessBuilder`
398///       that called `masquerade_as_nightly_cargo`
399pub fn nightly_features_allowed() -> bool {
400    if ENABLE_NIGHTLY_FEATURES.with(|c| c.get()) {
401        return true;
402    }
403    match &channel()[..] {
404        "nightly" | "dev" => NIGHTLY_FEATURES_ALLOWED.with(|c| c.get()),
405        _ => false,
406    }
407}
408
409/// Allows nightly features to be enabled for this thread, but only if the
410/// development channel is nightly or dev.
411///
412/// Used by cargo main to ensure that a cargo build from source has nightly features
413pub fn maybe_allow_nightly_features() {
414    NIGHTLY_FEATURES_ALLOWED.with(|c| c.set(true));
415}
416
417/// Forcibly enables nightly features for this thread.
418///
419/// Used by tests to allow the use of nightly features.
420pub fn enable_nightly_features() {
421    ENABLE_NIGHTLY_FEATURES.with(|c| c.set(true));
422}