bootstrap/core/config/toml/
rust.rs

1//! This module defines the `Rust` struct, which represents the `[rust]` table
2//! in the `bootstrap.toml` configuration file.
3
4use serde::{Deserialize, Deserializer};
5
6use crate::core::config::toml::TomlConfig;
7use crate::core::config::{DebuginfoLevel, Merge, ReplaceOpt, StringOrBool};
8use crate::{BTreeSet, CodegenBackendKind, HashSet, PathBuf, TargetSelection, define_config, exit};
9
10define_config! {
11    /// TOML representation of how the Rust build is configured.
12    #[derive(Default)]
13    struct Rust {
14        optimize: Option<RustOptimize> = "optimize",
15        debug: Option<bool> = "debug",
16        codegen_units: Option<u32> = "codegen-units",
17        codegen_units_std: Option<u32> = "codegen-units-std",
18        rustc_debug_assertions: Option<bool> = "debug-assertions",
19        randomize_layout: Option<bool> = "randomize-layout",
20        std_debug_assertions: Option<bool> = "debug-assertions-std",
21        tools_debug_assertions: Option<bool> = "debug-assertions-tools",
22        overflow_checks: Option<bool> = "overflow-checks",
23        overflow_checks_std: Option<bool> = "overflow-checks-std",
24        debug_logging: Option<bool> = "debug-logging",
25        debuginfo_level: Option<DebuginfoLevel> = "debuginfo-level",
26        debuginfo_level_rustc: Option<DebuginfoLevel> = "debuginfo-level-rustc",
27        debuginfo_level_std: Option<DebuginfoLevel> = "debuginfo-level-std",
28        debuginfo_level_tools: Option<DebuginfoLevel> = "debuginfo-level-tools",
29        debuginfo_level_tests: Option<DebuginfoLevel> = "debuginfo-level-tests",
30        backtrace: Option<bool> = "backtrace",
31        incremental: Option<bool> = "incremental",
32        default_linker: Option<String> = "default-linker",
33        channel: Option<String> = "channel",
34        musl_root: Option<String> = "musl-root",
35        rpath: Option<bool> = "rpath",
36        strip: Option<bool> = "strip",
37        frame_pointers: Option<bool> = "frame-pointers",
38        stack_protector: Option<String> = "stack-protector",
39        verbose_tests: Option<bool> = "verbose-tests",
40        optimize_tests: Option<bool> = "optimize-tests",
41        codegen_tests: Option<bool> = "codegen-tests",
42        omit_git_hash: Option<bool> = "omit-git-hash",
43        dist_src: Option<bool> = "dist-src",
44        save_toolstates: Option<String> = "save-toolstates",
45        codegen_backends: Option<Vec<String>> = "codegen-backends",
46        llvm_bitcode_linker: Option<bool> = "llvm-bitcode-linker",
47        lld: Option<bool> = "lld",
48        bootstrap_override_lld: Option<BootstrapOverrideLld> = "bootstrap-override-lld",
49        // FIXME: Remove this option in Spring 2026
50        bootstrap_override_lld_legacy: Option<BootstrapOverrideLld> = "use-lld",
51        llvm_tools: Option<bool> = "llvm-tools",
52        deny_warnings: Option<bool> = "deny-warnings",
53        backtrace_on_ice: Option<bool> = "backtrace-on-ice",
54        verify_llvm_ir: Option<bool> = "verify-llvm-ir",
55        thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
56        remap_debuginfo: Option<bool> = "remap-debuginfo",
57        jemalloc: Option<bool> = "jemalloc",
58        test_compare_mode: Option<bool> = "test-compare-mode",
59        llvm_libunwind: Option<String> = "llvm-libunwind",
60        control_flow_guard: Option<bool> = "control-flow-guard",
61        ehcont_guard: Option<bool> = "ehcont-guard",
62        new_symbol_mangling: Option<bool> = "new-symbol-mangling",
63        profile_generate: Option<String> = "profile-generate",
64        profile_use: Option<String> = "profile-use",
65        // ignored; this is set from an env var set by bootstrap.py
66        download_rustc: Option<StringOrBool> = "download-rustc",
67        lto: Option<String> = "lto",
68        validate_mir_opts: Option<u32> = "validate-mir-opts",
69        std_features: Option<BTreeSet<String>> = "std-features",
70        break_on_ice: Option<bool> = "break-on-ice",
71        parallel_frontend_threads: Option<u32> = "parallel-frontend-threads",
72    }
73}
74
75/// Determines if we should override the linker used for linking Rust code built
76/// during the bootstrapping process to be LLD.
77///
78/// The primary use-case for this is to make local (re)builds of Rust code faster
79/// when using bootstrap.
80///
81/// This does not affect the *behavior* of the built/distributed compiler when invoked
82/// outside of bootstrap.
83/// It might affect its performance/binary size though, as that can depend on the
84/// linker that links rustc.
85///
86/// There are two ways of overriding the linker to be LLD:
87/// - Self-contained LLD: use `rust-lld` from the compiler's sysroot
88/// - External: use an external `lld` binary
89///
90/// It is configured depending on the target:
91/// 1) Everything except MSVC
92/// - Self-contained: `-Clinker-features=+lld -Clink-self-contained=+linker`
93/// - External: `-Clinker-features=+lld`
94/// 2) MSVC
95/// - Self-contained: `-Clinker=<path to rust-lld>`
96/// - External: `-Clinker=lld`
97#[derive(Copy, Clone, Default, Debug, PartialEq)]
98pub enum BootstrapOverrideLld {
99    /// Do not override the linker LLD
100    #[default]
101    None,
102    /// Use `rust-lld` from the compiler's sysroot
103    SelfContained,
104    /// Use an externally provided `lld` binary.
105    /// Note that the linker name cannot be overridden, the binary has to be named `lld` and it has
106    /// to be in $PATH.
107    External,
108}
109
110impl BootstrapOverrideLld {
111    pub fn is_used(&self) -> bool {
112        match self {
113            BootstrapOverrideLld::SelfContained | BootstrapOverrideLld::External => true,
114            BootstrapOverrideLld::None => false,
115        }
116    }
117}
118
119impl<'de> Deserialize<'de> for BootstrapOverrideLld {
120    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
121    where
122        D: Deserializer<'de>,
123    {
124        struct LldModeVisitor;
125
126        impl serde::de::Visitor<'_> for LldModeVisitor {
127            type Value = BootstrapOverrideLld;
128
129            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130                formatter.write_str("one of true, 'self-contained' or 'external'")
131            }
132
133            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
134            where
135                E: serde::de::Error,
136            {
137                Ok(if v { BootstrapOverrideLld::External } else { BootstrapOverrideLld::None })
138            }
139
140            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
141            where
142                E: serde::de::Error,
143            {
144                match v {
145                    "external" => Ok(BootstrapOverrideLld::External),
146                    "self-contained" => Ok(BootstrapOverrideLld::SelfContained),
147                    _ => Err(E::custom(format!("unknown mode {v}"))),
148                }
149            }
150        }
151
152        deserializer.deserialize_any(LldModeVisitor)
153    }
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
157pub enum RustOptimize {
158    String(String),
159    Int(u8),
160    Bool(bool),
161}
162
163impl Default for RustOptimize {
164    fn default() -> RustOptimize {
165        RustOptimize::Bool(false)
166    }
167}
168
169impl<'de> Deserialize<'de> for RustOptimize {
170    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
171    where
172        D: Deserializer<'de>,
173    {
174        deserializer.deserialize_any(OptimizeVisitor)
175    }
176}
177
178struct OptimizeVisitor;
179
180impl serde::de::Visitor<'_> for OptimizeVisitor {
181    type Value = RustOptimize;
182
183    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        formatter.write_str(r#"one of: 0, 1, 2, 3, "s", "z", true, false"#)
185    }
186
187    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
188    where
189        E: serde::de::Error,
190    {
191        if matches!(value, "s" | "z") {
192            Ok(RustOptimize::String(value.to_string()))
193        } else {
194            Err(serde::de::Error::custom(format_optimize_error_msg(value)))
195        }
196    }
197
198    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
199    where
200        E: serde::de::Error,
201    {
202        if matches!(value, 0..=3) {
203            Ok(RustOptimize::Int(value as u8))
204        } else {
205            Err(serde::de::Error::custom(format_optimize_error_msg(value)))
206        }
207    }
208
209    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
210    where
211        E: serde::de::Error,
212    {
213        Ok(RustOptimize::Bool(value))
214    }
215}
216
217fn format_optimize_error_msg(v: impl std::fmt::Display) -> String {
218    format!(
219        r#"unrecognized option for rust optimize: "{v}", expected one of 0, 1, 2, 3, "s", "z", true, false"#
220    )
221}
222
223impl RustOptimize {
224    pub(crate) fn is_release(&self) -> bool {
225        match &self {
226            RustOptimize::Bool(true) | RustOptimize::String(_) => true,
227            RustOptimize::Int(i) => *i > 0,
228            RustOptimize::Bool(false) => false,
229        }
230    }
231
232    pub(crate) fn get_opt_level(&self) -> Option<String> {
233        match &self {
234            RustOptimize::String(s) => Some(s.clone()),
235            RustOptimize::Int(i) => Some(i.to_string()),
236            RustOptimize::Bool(_) => None,
237        }
238    }
239}
240
241/// Compares the current Rust options against those in the CI rustc builder and detects any incompatible options.
242/// It does this by destructuring the `Rust` instance to make sure every `Rust` field is covered and not missing.
243pub fn check_incompatible_options_for_ci_rustc(
244    host: TargetSelection,
245    current_config_toml: TomlConfig,
246    ci_config_toml: TomlConfig,
247) -> Result<(), String> {
248    macro_rules! err {
249        ($current:expr, $expected:expr, $config_section:expr) => {
250            if let Some(current) = &$current {
251                if Some(current) != $expected.as_ref() {
252                    return Err(format!(
253                        "ERROR: Setting `{}` is incompatible with `rust.download-rustc`. \
254                        Current value: {:?}, Expected value(s): {}{:?}",
255                        format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
256                        $current,
257                        if $expected.is_some() { "None/" } else { "" },
258                        $expected,
259                    ));
260                };
261            };
262        };
263    }
264
265    macro_rules! warn {
266        ($current:expr, $expected:expr, $config_section:expr) => {
267            if let Some(current) = &$current {
268                if Some(current) != $expected.as_ref() {
269                    println!(
270                        "WARNING: `{}` has no effect with `rust.download-rustc`. \
271                        Current value: {:?}, Expected value(s): {}{:?}",
272                        format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
273                        $current,
274                        if $expected.is_some() { "None/" } else { "" },
275                        $expected,
276                    );
277                };
278            };
279        };
280    }
281
282    let current_profiler = current_config_toml.build.as_ref().and_then(|b| b.profiler);
283    let profiler = ci_config_toml.build.as_ref().and_then(|b| b.profiler);
284    err!(current_profiler, profiler, "build");
285
286    let current_optimized_compiler_builtins =
287        current_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
288    let optimized_compiler_builtins =
289        ci_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
290    err!(current_optimized_compiler_builtins, optimized_compiler_builtins, "build");
291
292    // We always build the in-tree compiler on cross targets, so we only care
293    // about the host target here.
294    let host_str = host.to_string();
295    if let Some(current_cfg) = current_config_toml.target.as_ref().and_then(|c| c.get(&host_str))
296        && current_cfg.profiler.is_some()
297    {
298        let ci_target_toml = ci_config_toml.target.as_ref().and_then(|c| c.get(&host_str));
299        let ci_cfg = ci_target_toml.ok_or(format!(
300            "Target specific config for '{host_str}' is not present for CI-rustc"
301        ))?;
302
303        let profiler = &ci_cfg.profiler;
304        err!(current_cfg.profiler, profiler, "build");
305
306        let optimized_compiler_builtins = &ci_cfg.optimized_compiler_builtins;
307        err!(current_cfg.optimized_compiler_builtins, optimized_compiler_builtins, "build");
308    }
309
310    let (Some(current_rust_config), Some(ci_rust_config)) =
311        (current_config_toml.rust, ci_config_toml.rust)
312    else {
313        return Ok(());
314    };
315
316    let Rust {
317        // Following options are the CI rustc incompatible ones.
318        optimize,
319        randomize_layout,
320        debug_logging,
321        debuginfo_level_rustc,
322        llvm_tools,
323        llvm_bitcode_linker,
324        lto,
325        stack_protector,
326        strip,
327        jemalloc,
328        rpath,
329        channel,
330        default_linker,
331        std_features,
332
333        // Rest of the options can simply be ignored.
334        incremental: _,
335        debug: _,
336        codegen_units: _,
337        codegen_units_std: _,
338        rustc_debug_assertions: _,
339        std_debug_assertions: _,
340        tools_debug_assertions: _,
341        overflow_checks: _,
342        overflow_checks_std: _,
343        debuginfo_level: _,
344        debuginfo_level_std: _,
345        debuginfo_level_tools: _,
346        debuginfo_level_tests: _,
347        backtrace: _,
348        musl_root: _,
349        verbose_tests: _,
350        optimize_tests: _,
351        codegen_tests: _,
352        omit_git_hash: _,
353        dist_src: _,
354        save_toolstates: _,
355        codegen_backends: _,
356        lld: _,
357        deny_warnings: _,
358        backtrace_on_ice: _,
359        verify_llvm_ir: _,
360        thin_lto_import_instr_limit: _,
361        remap_debuginfo: _,
362        test_compare_mode: _,
363        llvm_libunwind: _,
364        control_flow_guard: _,
365        ehcont_guard: _,
366        new_symbol_mangling: _,
367        profile_generate: _,
368        profile_use: _,
369        download_rustc: _,
370        validate_mir_opts: _,
371        frame_pointers: _,
372        break_on_ice: _,
373        parallel_frontend_threads: _,
374        bootstrap_override_lld: _,
375        bootstrap_override_lld_legacy: _,
376    } = ci_rust_config;
377
378    // There are two kinds of checks for CI rustc incompatible options:
379    //    1. Checking an option that may change the compiler behaviour/output.
380    //    2. Checking an option that have no effect on the compiler behaviour/output.
381    //
382    // If the option belongs to the first category, we call `err` macro for a hard error;
383    // otherwise, we just print a warning with `warn` macro.
384
385    err!(current_rust_config.optimize, optimize, "rust");
386    err!(current_rust_config.randomize_layout, randomize_layout, "rust");
387    err!(current_rust_config.debug_logging, debug_logging, "rust");
388    err!(current_rust_config.debuginfo_level_rustc, debuginfo_level_rustc, "rust");
389    err!(current_rust_config.rpath, rpath, "rust");
390    err!(current_rust_config.strip, strip, "rust");
391    err!(current_rust_config.llvm_tools, llvm_tools, "rust");
392    err!(current_rust_config.llvm_bitcode_linker, llvm_bitcode_linker, "rust");
393    err!(current_rust_config.jemalloc, jemalloc, "rust");
394    err!(current_rust_config.default_linker, default_linker, "rust");
395    err!(current_rust_config.stack_protector, stack_protector, "rust");
396    err!(current_rust_config.lto, lto, "rust");
397    err!(current_rust_config.std_features, std_features, "rust");
398
399    warn!(current_rust_config.channel, channel, "rust");
400
401    Ok(())
402}
403
404pub(crate) const BUILTIN_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"];
405
406pub(crate) fn parse_codegen_backends(
407    backends: Vec<String>,
408    section: &str,
409) -> Vec<CodegenBackendKind> {
410    const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
411
412    let mut found_backends = vec![];
413    for backend in &backends {
414        if let Some(stripped) = backend.strip_prefix(CODEGEN_BACKEND_PREFIX) {
415            panic!(
416                "Invalid value '{backend}' for '{section}.codegen-backends'. \
417                Codegen backends are defined without the '{CODEGEN_BACKEND_PREFIX}' prefix. \
418                Please, use '{stripped}' instead."
419            )
420        }
421        if !BUILTIN_CODEGEN_BACKENDS.contains(&backend.as_str()) {
422            println!(
423                "HELP: '{backend}' for '{section}.codegen-backends' might fail. \
424                List of known codegen backends: {BUILTIN_CODEGEN_BACKENDS:?}"
425            );
426        }
427        let backend = match backend.as_str() {
428            "llvm" => CodegenBackendKind::Llvm,
429            "cranelift" => CodegenBackendKind::Cranelift,
430            "gcc" => CodegenBackendKind::Gcc,
431            backend => CodegenBackendKind::Custom(backend.to_string()),
432        };
433        found_backends.push(backend);
434    }
435    if found_backends.is_empty() {
436        eprintln!("ERROR: `{section}.codegen-backends` should not be set to `[]`");
437        exit!(1);
438    }
439    found_backends
440}