rustc_session/config/
cfg.rs

1//! cfg and check-cfg configuration
2//!
3//! This module contains the definition of [`Cfg`] and [`CheckCfg`]
4//! as well as the logic for creating the default configuration for a
5//! given [`Session`].
6//!
7//! It also contains the filling of the well known configs, which should
8//! ALWAYS be in sync with the default_configuration.
9//!
10//! ## Adding a new cfg
11//!
12//! Adding a new feature requires two new symbols one for the cfg itself
13//! and the second one for the unstable feature gate, those are defined in
14//! `rustc_span::symbol`.
15//!
16//! As well as the following points,
17//!  - Add the activation logic in [`default_configuration`]
18//!  - Add the cfg to [`CheckCfg::fill_well_known`] (and related files),
19//!    so that the compiler can know the cfg is expected
20//!  - Add the cfg in [`disallow_cfgs`] to disallow users from setting it via `--cfg`
21//!  - Add the feature gating in `compiler/rustc_feature/src/builtin_attrs.rs`
22
23use std::hash::Hash;
24use std::iter;
25
26use rustc_abi::Align;
27use rustc_ast::ast;
28use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
29use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS;
30use rustc_span::{Symbol, sym};
31use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target};
32
33use crate::config::{CrateType, FmtDebug};
34use crate::{Session, errors};
35
36/// The parsed `--cfg` options that define the compilation environment of the
37/// crate, used to drive conditional compilation.
38///
39/// An `FxIndexSet` is used to ensure deterministic ordering of error messages
40/// relating to `--cfg`.
41pub type Cfg = FxIndexSet<(Symbol, Option<Symbol>)>;
42
43/// The parsed `--check-cfg` options.
44#[derive(Default)]
45pub struct CheckCfg {
46    /// Is well known names activated
47    pub exhaustive_names: bool,
48    /// Is well known values activated
49    pub exhaustive_values: bool,
50    /// All the expected values for a config name
51    pub expecteds: FxHashMap<Symbol, ExpectedValues<Symbol>>,
52    /// Well known names (only used for diagnostics purposes)
53    pub well_known_names: FxHashSet<Symbol>,
54}
55
56pub enum ExpectedValues<T> {
57    Some(FxHashSet<Option<T>>),
58    Any,
59}
60
61impl<T: Eq + Hash> ExpectedValues<T> {
62    fn insert(&mut self, value: T) -> bool {
63        match self {
64            ExpectedValues::Some(expecteds) => expecteds.insert(Some(value)),
65            ExpectedValues::Any => false,
66        }
67    }
68}
69
70impl<T: Eq + Hash> Extend<T> for ExpectedValues<T> {
71    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
72        match self {
73            ExpectedValues::Some(expecteds) => expecteds.extend(iter.into_iter().map(Some)),
74            ExpectedValues::Any => {}
75        }
76    }
77}
78
79impl<'a, T: Eq + Hash + Copy + 'a> Extend<&'a T> for ExpectedValues<T> {
80    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
81        match self {
82            ExpectedValues::Some(expecteds) => expecteds.extend(iter.into_iter().map(|a| Some(*a))),
83            ExpectedValues::Any => {}
84        }
85    }
86}
87
88/// Disallow builtin cfgs from the CLI.
89pub(crate) fn disallow_cfgs(sess: &Session, user_cfgs: &Cfg) {
90    let disallow = |cfg: &(Symbol, Option<Symbol>), controlled_by| {
91        let cfg_name = cfg.0;
92        let cfg = if let Some(value) = cfg.1 {
93            format!(r#"{}="{}""#, cfg_name, value)
94        } else {
95            format!("{}", cfg_name)
96        };
97        sess.psess.opt_span_buffer_lint(
98            EXPLICIT_BUILTIN_CFGS_IN_FLAGS,
99            None,
100            ast::CRATE_NODE_ID,
101            errors::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }.into(),
102        )
103    };
104
105    // We want to restrict setting builtin cfgs that will produce incoherent behavior
106    // between the cfg and the rustc cli flag that sets it.
107    //
108    // The tests are in tests/ui/cfg/disallowed-cli-cfgs.rs.
109
110    // By-default all builtin cfgs are disallowed, only those are allowed:
111    //  - test: as it makes sense to the have the `test` cfg active without the builtin
112    //          test harness. See Cargo `harness = false` config.
113    //
114    // Cargo `--cfg test`: https://github.com/rust-lang/cargo/blob/bc89bffa5987d4af8f71011c7557119b39e44a65/src/cargo/core/compiler/mod.rs#L1124
115
116    for cfg in user_cfgs {
117        match cfg {
118            (sym::overflow_checks, None) => disallow(cfg, "-C overflow-checks"),
119            (sym::debug_assertions, None) => disallow(cfg, "-C debug-assertions"),
120            (sym::ub_checks, None) => disallow(cfg, "-Z ub-checks"),
121            (sym::contract_checks, None) => disallow(cfg, "-Z contract-checks"),
122            (sym::sanitize, None | Some(_)) => disallow(cfg, "-Z sanitizer"),
123            (
124                sym::sanitizer_cfi_generalize_pointers | sym::sanitizer_cfi_normalize_integers,
125                None | Some(_),
126            ) => disallow(cfg, "-Z sanitizer=cfi"),
127            (sym::proc_macro, None) => disallow(cfg, "--crate-type proc-macro"),
128            (sym::panic, Some(sym::abort | sym::unwind)) => disallow(cfg, "-C panic"),
129            (sym::target_feature, Some(_)) => disallow(cfg, "-C target-feature"),
130            (sym::unix, None)
131            | (sym::windows, None)
132            | (sym::relocation_model, Some(_))
133            | (sym::target_abi, None | Some(_))
134            | (sym::target_arch, Some(_))
135            | (sym::target_endian, Some(_))
136            | (sym::target_env, None | Some(_))
137            | (sym::target_family, Some(_))
138            | (sym::target_os, Some(_))
139            | (sym::target_pointer_width, Some(_))
140            | (sym::target_vendor, None | Some(_))
141            | (sym::target_has_atomic, Some(_))
142            | (sym::target_has_atomic_equal_alignment, Some(_))
143            | (sym::target_has_atomic_load_store, Some(_))
144            | (sym::target_has_reliable_f16, None | Some(_))
145            | (sym::target_has_reliable_f16_math, None | Some(_))
146            | (sym::target_has_reliable_f128, None | Some(_))
147            | (sym::target_has_reliable_f128_math, None | Some(_))
148            | (sym::target_thread_local, None) => disallow(cfg, "--target"),
149            (sym::fmt_debug, None | Some(_)) => disallow(cfg, "-Z fmt-debug"),
150            (sym::emscripten_wasm_eh, None | Some(_)) => disallow(cfg, "-Z emscripten_wasm_eh"),
151            _ => {}
152        }
153    }
154}
155
156/// Generate the default configs for a given session
157pub(crate) fn default_configuration(sess: &Session) -> Cfg {
158    let mut ret = Cfg::default();
159
160    macro_rules! ins_none {
161        ($key:expr) => {
162            ret.insert(($key, None));
163        };
164    }
165    macro_rules! ins_str {
166        ($key:expr, $val_str:expr) => {
167            ret.insert(($key, Some(Symbol::intern($val_str))));
168        };
169    }
170    macro_rules! ins_sym {
171        ($key:expr, $val_sym:expr) => {
172            ret.insert(($key, Some($val_sym)));
173        };
174    }
175
176    // Symbols are inserted in alphabetical order as much as possible.
177    // The exceptions are where control flow forces things out of order.
178    //
179    // Run `rustc --print cfg` to see the configuration in practice.
180    //
181    // NOTE: These insertions should be kept in sync with
182    // `CheckCfg::fill_well_known` below.
183
184    if sess.opts.debug_assertions {
185        ins_none!(sym::debug_assertions);
186    }
187
188    if sess.is_nightly_build() {
189        match sess.opts.unstable_opts.fmt_debug {
190            FmtDebug::Full => {
191                ins_sym!(sym::fmt_debug, sym::full);
192            }
193            FmtDebug::Shallow => {
194                ins_sym!(sym::fmt_debug, sym::shallow);
195            }
196            FmtDebug::None => {
197                ins_sym!(sym::fmt_debug, sym::none);
198            }
199        }
200    }
201
202    if sess.overflow_checks() {
203        ins_none!(sym::overflow_checks);
204    }
205
206    ins_sym!(sym::panic, sess.panic_strategy().desc_symbol());
207
208    // JUSTIFICATION: before wrapper fn is available
209    #[allow(rustc::bad_opt_access)]
210    if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
211        ins_none!(sym::proc_macro);
212    }
213
214    if sess.is_nightly_build() {
215        ins_sym!(sym::relocation_model, sess.target.relocation_model.desc_symbol());
216    }
217
218    for mut s in sess.opts.unstable_opts.sanitizer {
219        // KASAN is still ASAN under the hood, so it uses the same attribute.
220        if s == SanitizerSet::KERNELADDRESS {
221            s = SanitizerSet::ADDRESS;
222        }
223        ins_str!(sym::sanitize, &s.to_string());
224    }
225
226    if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
227        ins_none!(sym::sanitizer_cfi_generalize_pointers);
228    }
229    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
230        ins_none!(sym::sanitizer_cfi_normalize_integers);
231    }
232
233    ins_str!(sym::target_abi, &sess.target.abi);
234    ins_str!(sym::target_arch, &sess.target.arch);
235    ins_str!(sym::target_endian, sess.target.endian.as_str());
236    ins_str!(sym::target_env, &sess.target.env);
237
238    for family in sess.target.families.as_ref() {
239        ins_str!(sym::target_family, family);
240        if family == "windows" {
241            ins_none!(sym::windows);
242        } else if family == "unix" {
243            ins_none!(sym::unix);
244        }
245    }
246
247    // `target_has_atomic*`
248    let layout = sess.target.parse_data_layout().unwrap_or_else(|err| {
249        sess.dcx().emit_fatal(err);
250    });
251    let mut has_atomic = false;
252    for (i, align) in [
253        (8, layout.i8_align.abi),
254        (16, layout.i16_align.abi),
255        (32, layout.i32_align.abi),
256        (64, layout.i64_align.abi),
257        (128, layout.i128_align.abi),
258    ] {
259        if i >= sess.target.min_atomic_width() && i <= sess.target.max_atomic_width() {
260            if !has_atomic {
261                has_atomic = true;
262                if sess.is_nightly_build() {
263                    if sess.target.atomic_cas {
264                        ins_none!(sym::target_has_atomic);
265                    }
266                    ins_none!(sym::target_has_atomic_load_store);
267                }
268            }
269            let mut insert_atomic = |sym, align: Align| {
270                if sess.target.atomic_cas {
271                    ins_sym!(sym::target_has_atomic, sym);
272                }
273                if align.bits() == i {
274                    ins_sym!(sym::target_has_atomic_equal_alignment, sym);
275                }
276                ins_sym!(sym::target_has_atomic_load_store, sym);
277            };
278            insert_atomic(sym::integer(i), align);
279            if sess.target.pointer_width as u64 == i {
280                insert_atomic(sym::ptr, layout.pointer_align().abi);
281            }
282        }
283    }
284
285    ins_str!(sym::target_os, &sess.target.os);
286    ins_sym!(sym::target_pointer_width, sym::integer(sess.target.pointer_width));
287
288    if sess.opts.unstable_opts.has_thread_local.unwrap_or(sess.target.has_thread_local) {
289        ins_none!(sym::target_thread_local);
290    }
291
292    ins_str!(sym::target_vendor, &sess.target.vendor);
293
294    // If the user wants a test runner, then add the test cfg.
295    if sess.is_test_crate() {
296        ins_none!(sym::test);
297    }
298
299    if sess.ub_checks() {
300        ins_none!(sym::ub_checks);
301    }
302
303    // Nightly-only implementation detail for the `panic_unwind` and `unwind` crates.
304    if sess.is_nightly_build() && sess.opts.unstable_opts.emscripten_wasm_eh {
305        ins_none!(sym::emscripten_wasm_eh);
306    }
307
308    if sess.contract_checks() {
309        ins_none!(sym::contract_checks);
310    }
311
312    ret
313}
314
315impl CheckCfg {
316    /// Fill the current [`CheckCfg`] with all the well known cfgs
317    pub fn fill_well_known(&mut self, current_target: &Target) {
318        if !self.exhaustive_values && !self.exhaustive_names {
319            return;
320        }
321
322        // for `#[cfg(foo)]` (ie. cfg value is none)
323        let no_values = || {
324            let mut values = FxHashSet::default();
325            values.insert(None);
326            ExpectedValues::Some(values)
327        };
328
329        // preparation for inserting some values
330        let empty_values = || {
331            let values = FxHashSet::default();
332            ExpectedValues::Some(values)
333        };
334
335        macro_rules! ins {
336            ($name:expr, $values:expr) => {{
337                self.well_known_names.insert($name);
338                self.expecteds.entry($name).or_insert_with($values)
339            }};
340        }
341
342        // Symbols are inserted in alphabetical order as much as possible.
343        // The exceptions are where control flow forces things out of order.
344        //
345        // NOTE: This should be kept in sync with `default_configuration`.
346        // Note that symbols inserted conditionally in `default_configuration`
347        // are inserted unconditionally here.
348        //
349        // One exception is the `test` cfg which is consider to be a "user-space"
350        // cfg, despite being also set by in `default_configuration` above.
351        // It allows the build system to "deny" using the config by not marking it
352        // as expected (e.g. `lib.test = false` for Cargo).
353        //
354        // When adding a new config here you should also update
355        // `tests/ui/check-cfg/well-known-values.rs` (in order to test the
356        // expected values of the new config) and bless the all directory.
357        //
358        // Don't forget to update `src/doc/rustc/src/check-cfg.md`
359        // in the unstable book as well!
360
361        ins!(sym::debug_assertions, no_values);
362
363        ins!(sym::fmt_debug, empty_values).extend(FmtDebug::all());
364
365        // These four are never set by rustc, but we set them anyway; they
366        // should not trigger the lint because `cargo clippy`, `cargo doc`,
367        // `cargo test`, `cargo miri run` and `cargo fmt` (respectively)
368        // can set them.
369        ins!(sym::clippy, no_values);
370        ins!(sym::doc, no_values);
371        ins!(sym::doctest, no_values);
372        ins!(sym::miri, no_values);
373        ins!(sym::rustfmt, no_values);
374
375        ins!(sym::overflow_checks, no_values);
376
377        ins!(sym::panic, empty_values).extend(&PanicStrategy::all());
378
379        ins!(sym::proc_macro, no_values);
380
381        ins!(sym::relocation_model, empty_values).extend(RelocModel::all());
382
383        let sanitize_values = SanitizerSet::all()
384            .into_iter()
385            .map(|sanitizer| Symbol::intern(sanitizer.as_str().unwrap()));
386        ins!(sym::sanitize, empty_values).extend(sanitize_values);
387
388        ins!(sym::sanitizer_cfi_generalize_pointers, no_values);
389        ins!(sym::sanitizer_cfi_normalize_integers, no_values);
390
391        ins!(sym::target_feature, empty_values).extend(
392            rustc_target::target_features::all_rust_features()
393                .filter(|(_, s)| s.in_cfg())
394                .map(|(f, _s)| f)
395                .chain(rustc_target::target_features::RUSTC_SPECIFIC_FEATURES.iter().cloned())
396                .map(Symbol::intern),
397        );
398
399        // sym::target_*
400        {
401            const VALUES: [&Symbol; 8] = [
402                &sym::target_abi,
403                &sym::target_arch,
404                &sym::target_endian,
405                &sym::target_env,
406                &sym::target_family,
407                &sym::target_os,
408                &sym::target_pointer_width,
409                &sym::target_vendor,
410            ];
411
412            // Initialize (if not already initialized)
413            for &e in VALUES {
414                if !self.exhaustive_values {
415                    ins!(e, || ExpectedValues::Any);
416                } else {
417                    ins!(e, empty_values);
418                }
419            }
420
421            if self.exhaustive_values {
422                // Get all values map at once otherwise it would be costly.
423                // (8 values * 220 targets ~= 1760 times, at the time of writing this comment).
424                let [
425                    Some(values_target_abi),
426                    Some(values_target_arch),
427                    Some(values_target_endian),
428                    Some(values_target_env),
429                    Some(values_target_family),
430                    Some(values_target_os),
431                    Some(values_target_pointer_width),
432                    Some(values_target_vendor),
433                ] = self.expecteds.get_disjoint_mut(VALUES)
434                else {
435                    panic!("unable to get all the check-cfg values buckets");
436                };
437
438                for target in Target::builtins().chain(iter::once(current_target.clone())) {
439                    values_target_abi.insert(Symbol::intern(&target.options.abi));
440                    values_target_arch.insert(Symbol::intern(&target.arch));
441                    values_target_endian.insert(Symbol::intern(target.options.endian.as_str()));
442                    values_target_env.insert(Symbol::intern(&target.options.env));
443                    values_target_family.extend(
444                        target.options.families.iter().map(|family| Symbol::intern(family)),
445                    );
446                    values_target_os.insert(Symbol::intern(&target.options.os));
447                    values_target_pointer_width.insert(sym::integer(target.pointer_width));
448                    values_target_vendor.insert(Symbol::intern(&target.options.vendor));
449                }
450            }
451        }
452
453        let atomic_values = &[
454            sym::ptr,
455            sym::integer(8usize),
456            sym::integer(16usize),
457            sym::integer(32usize),
458            sym::integer(64usize),
459            sym::integer(128usize),
460        ];
461        for sym in [
462            sym::target_has_atomic,
463            sym::target_has_atomic_equal_alignment,
464            sym::target_has_atomic_load_store,
465        ] {
466            ins!(sym, no_values).extend(atomic_values);
467        }
468
469        ins!(sym::target_thread_local, no_values);
470
471        ins!(sym::ub_checks, no_values);
472        ins!(sym::contract_checks, no_values);
473
474        ins!(sym::unix, no_values);
475        ins!(sym::windows, no_values);
476    }
477}