1use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer};
7
8use crate::core::build_steps::compile::CODEGEN_BACKEND_PREFIX;
9use crate::core::config::toml::TomlConfig;
10use crate::core::config::{
11 DebuginfoLevel, Merge, ReplaceOpt, RustcLto, StringOrBool, set, threads_from_config,
12};
13use crate::flags::Warnings;
14use crate::{BTreeSet, Config, HashSet, PathBuf, TargetSelection, define_config, exit};
15
16define_config! {
17 struct Rust {
19 optimize: Option<RustOptimize> = "optimize",
20 debug: Option<bool> = "debug",
21 codegen_units: Option<u32> = "codegen-units",
22 codegen_units_std: Option<u32> = "codegen-units-std",
23 rustc_debug_assertions: Option<bool> = "debug-assertions",
24 randomize_layout: Option<bool> = "randomize-layout",
25 std_debug_assertions: Option<bool> = "debug-assertions-std",
26 tools_debug_assertions: Option<bool> = "debug-assertions-tools",
27 overflow_checks: Option<bool> = "overflow-checks",
28 overflow_checks_std: Option<bool> = "overflow-checks-std",
29 debug_logging: Option<bool> = "debug-logging",
30 debuginfo_level: Option<DebuginfoLevel> = "debuginfo-level",
31 debuginfo_level_rustc: Option<DebuginfoLevel> = "debuginfo-level-rustc",
32 debuginfo_level_std: Option<DebuginfoLevel> = "debuginfo-level-std",
33 debuginfo_level_tools: Option<DebuginfoLevel> = "debuginfo-level-tools",
34 debuginfo_level_tests: Option<DebuginfoLevel> = "debuginfo-level-tests",
35 backtrace: Option<bool> = "backtrace",
36 incremental: Option<bool> = "incremental",
37 default_linker: Option<String> = "default-linker",
38 channel: Option<String> = "channel",
39 description: Option<String> = "description",
41 musl_root: Option<String> = "musl-root",
42 rpath: Option<bool> = "rpath",
43 strip: Option<bool> = "strip",
44 frame_pointers: Option<bool> = "frame-pointers",
45 stack_protector: Option<String> = "stack-protector",
46 verbose_tests: Option<bool> = "verbose-tests",
47 optimize_tests: Option<bool> = "optimize-tests",
48 codegen_tests: Option<bool> = "codegen-tests",
49 omit_git_hash: Option<bool> = "omit-git-hash",
50 dist_src: Option<bool> = "dist-src",
51 save_toolstates: Option<String> = "save-toolstates",
52 codegen_backends: Option<Vec<String>> = "codegen-backends",
53 llvm_bitcode_linker: Option<bool> = "llvm-bitcode-linker",
54 lld: Option<bool> = "lld",
55 lld_mode: Option<LldMode> = "use-lld",
56 llvm_tools: Option<bool> = "llvm-tools",
57 deny_warnings: Option<bool> = "deny-warnings",
58 backtrace_on_ice: Option<bool> = "backtrace-on-ice",
59 verify_llvm_ir: Option<bool> = "verify-llvm-ir",
60 thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
61 remap_debuginfo: Option<bool> = "remap-debuginfo",
62 jemalloc: Option<bool> = "jemalloc",
63 test_compare_mode: Option<bool> = "test-compare-mode",
64 llvm_libunwind: Option<String> = "llvm-libunwind",
65 control_flow_guard: Option<bool> = "control-flow-guard",
66 ehcont_guard: Option<bool> = "ehcont-guard",
67 new_symbol_mangling: Option<bool> = "new-symbol-mangling",
68 profile_generate: Option<String> = "profile-generate",
69 profile_use: Option<String> = "profile-use",
70 download_rustc: Option<StringOrBool> = "download-rustc",
72 lto: Option<String> = "lto",
73 validate_mir_opts: Option<u32> = "validate-mir-opts",
74 std_features: Option<BTreeSet<String>> = "std-features",
75 }
76}
77
78#[derive(Copy, Clone, Default, Debug, PartialEq)]
90pub enum LldMode {
91 #[default]
93 Unused,
94 SelfContained,
96 External,
100}
101
102impl LldMode {
103 pub fn is_used(&self) -> bool {
104 match self {
105 LldMode::SelfContained | LldMode::External => true,
106 LldMode::Unused => false,
107 }
108 }
109}
110
111impl<'de> Deserialize<'de> for LldMode {
112 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
113 where
114 D: Deserializer<'de>,
115 {
116 struct LldModeVisitor;
117
118 impl serde::de::Visitor<'_> for LldModeVisitor {
119 type Value = LldMode;
120
121 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 formatter.write_str("one of true, 'self-contained' or 'external'")
123 }
124
125 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
126 where
127 E: serde::de::Error,
128 {
129 Ok(if v { LldMode::External } else { LldMode::Unused })
130 }
131
132 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
133 where
134 E: serde::de::Error,
135 {
136 match v {
137 "external" => Ok(LldMode::External),
138 "self-contained" => Ok(LldMode::SelfContained),
139 _ => Err(E::custom(format!("unknown mode {v}"))),
140 }
141 }
142 }
143
144 deserializer.deserialize_any(LldModeVisitor)
145 }
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
149pub enum RustOptimize {
150 String(String),
151 Int(u8),
152 Bool(bool),
153}
154
155impl Default for RustOptimize {
156 fn default() -> RustOptimize {
157 RustOptimize::Bool(false)
158 }
159}
160
161impl<'de> Deserialize<'de> for RustOptimize {
162 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
163 where
164 D: Deserializer<'de>,
165 {
166 deserializer.deserialize_any(OptimizeVisitor)
167 }
168}
169
170struct OptimizeVisitor;
171
172impl serde::de::Visitor<'_> for OptimizeVisitor {
173 type Value = RustOptimize;
174
175 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 formatter.write_str(r#"one of: 0, 1, 2, 3, "s", "z", true, false"#)
177 }
178
179 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
180 where
181 E: serde::de::Error,
182 {
183 if matches!(value, "s" | "z") {
184 Ok(RustOptimize::String(value.to_string()))
185 } else {
186 Err(serde::de::Error::custom(format_optimize_error_msg(value)))
187 }
188 }
189
190 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
191 where
192 E: serde::de::Error,
193 {
194 if matches!(value, 0..=3) {
195 Ok(RustOptimize::Int(value as u8))
196 } else {
197 Err(serde::de::Error::custom(format_optimize_error_msg(value)))
198 }
199 }
200
201 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
202 where
203 E: serde::de::Error,
204 {
205 Ok(RustOptimize::Bool(value))
206 }
207}
208
209fn format_optimize_error_msg(v: impl std::fmt::Display) -> String {
210 format!(
211 r#"unrecognized option for rust optimize: "{v}", expected one of 0, 1, 2, 3, "s", "z", true, false"#
212 )
213}
214
215impl RustOptimize {
216 pub(crate) fn is_release(&self) -> bool {
217 match &self {
218 RustOptimize::Bool(true) | RustOptimize::String(_) => true,
219 RustOptimize::Int(i) => *i > 0,
220 RustOptimize::Bool(false) => false,
221 }
222 }
223
224 pub(crate) fn get_opt_level(&self) -> Option<String> {
225 match &self {
226 RustOptimize::String(s) => Some(s.clone()),
227 RustOptimize::Int(i) => Some(i.to_string()),
228 RustOptimize::Bool(_) => None,
229 }
230 }
231}
232
233pub fn check_incompatible_options_for_ci_rustc(
236 host: TargetSelection,
237 current_config_toml: TomlConfig,
238 ci_config_toml: TomlConfig,
239) -> Result<(), String> {
240 macro_rules! err {
241 ($current:expr, $expected:expr, $config_section:expr) => {
242 if let Some(current) = &$current {
243 if Some(current) != $expected.as_ref() {
244 return Err(format!(
245 "ERROR: Setting `{}` is incompatible with `rust.download-rustc`. \
246 Current value: {:?}, Expected value(s): {}{:?}",
247 format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
248 $current,
249 if $expected.is_some() { "None/" } else { "" },
250 $expected,
251 ));
252 };
253 };
254 };
255 }
256
257 macro_rules! warn {
258 ($current:expr, $expected:expr, $config_section:expr) => {
259 if let Some(current) = &$current {
260 if Some(current) != $expected.as_ref() {
261 println!(
262 "WARNING: `{}` has no effect with `rust.download-rustc`. \
263 Current value: {:?}, Expected value(s): {}{:?}",
264 format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
265 $current,
266 if $expected.is_some() { "None/" } else { "" },
267 $expected,
268 );
269 };
270 };
271 };
272 }
273
274 let current_profiler = current_config_toml.build.as_ref().and_then(|b| b.profiler);
275 let profiler = ci_config_toml.build.as_ref().and_then(|b| b.profiler);
276 err!(current_profiler, profiler, "build");
277
278 let current_optimized_compiler_builtins =
279 current_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins);
280 let optimized_compiler_builtins =
281 ci_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins);
282 err!(current_optimized_compiler_builtins, optimized_compiler_builtins, "build");
283
284 let host_str = host.to_string();
287 if let Some(current_cfg) = current_config_toml.target.as_ref().and_then(|c| c.get(&host_str))
288 && current_cfg.profiler.is_some()
289 {
290 let ci_target_toml = ci_config_toml.target.as_ref().and_then(|c| c.get(&host_str));
291 let ci_cfg = ci_target_toml.ok_or(format!(
292 "Target specific config for '{host_str}' is not present for CI-rustc"
293 ))?;
294
295 let profiler = &ci_cfg.profiler;
296 err!(current_cfg.profiler, profiler, "build");
297
298 let optimized_compiler_builtins = &ci_cfg.optimized_compiler_builtins;
299 err!(current_cfg.optimized_compiler_builtins, optimized_compiler_builtins, "build");
300 }
301
302 let (Some(current_rust_config), Some(ci_rust_config)) =
303 (current_config_toml.rust, ci_config_toml.rust)
304 else {
305 return Ok(());
306 };
307
308 let Rust {
309 optimize,
311 randomize_layout,
312 debug_logging,
313 debuginfo_level_rustc,
314 llvm_tools,
315 llvm_bitcode_linker,
316 lto,
317 stack_protector,
318 strip,
319 lld_mode,
320 jemalloc,
321 rpath,
322 channel,
323 description,
324 default_linker,
325 std_features,
326
327 incremental: _,
329 debug: _,
330 codegen_units: _,
331 codegen_units_std: _,
332 rustc_debug_assertions: _,
333 std_debug_assertions: _,
334 tools_debug_assertions: _,
335 overflow_checks: _,
336 overflow_checks_std: _,
337 debuginfo_level: _,
338 debuginfo_level_std: _,
339 debuginfo_level_tools: _,
340 debuginfo_level_tests: _,
341 backtrace: _,
342 musl_root: _,
343 verbose_tests: _,
344 optimize_tests: _,
345 codegen_tests: _,
346 omit_git_hash: _,
347 dist_src: _,
348 save_toolstates: _,
349 codegen_backends: _,
350 lld: _,
351 deny_warnings: _,
352 backtrace_on_ice: _,
353 verify_llvm_ir: _,
354 thin_lto_import_instr_limit: _,
355 remap_debuginfo: _,
356 test_compare_mode: _,
357 llvm_libunwind: _,
358 control_flow_guard: _,
359 ehcont_guard: _,
360 new_symbol_mangling: _,
361 profile_generate: _,
362 profile_use: _,
363 download_rustc: _,
364 validate_mir_opts: _,
365 frame_pointers: _,
366 } = ci_rust_config;
367
368 err!(current_rust_config.optimize, optimize, "rust");
376 err!(current_rust_config.randomize_layout, randomize_layout, "rust");
377 err!(current_rust_config.debug_logging, debug_logging, "rust");
378 err!(current_rust_config.debuginfo_level_rustc, debuginfo_level_rustc, "rust");
379 err!(current_rust_config.rpath, rpath, "rust");
380 err!(current_rust_config.strip, strip, "rust");
381 err!(current_rust_config.lld_mode, lld_mode, "rust");
382 err!(current_rust_config.llvm_tools, llvm_tools, "rust");
383 err!(current_rust_config.llvm_bitcode_linker, llvm_bitcode_linker, "rust");
384 err!(current_rust_config.jemalloc, jemalloc, "rust");
385 err!(current_rust_config.default_linker, default_linker, "rust");
386 err!(current_rust_config.stack_protector, stack_protector, "rust");
387 err!(current_rust_config.lto, lto, "rust");
388 err!(current_rust_config.std_features, std_features, "rust");
389
390 warn!(current_rust_config.channel, channel, "rust");
391 warn!(current_rust_config.description, description, "rust");
392
393 Ok(())
394}
395
396pub(crate) const VALID_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"];
397
398pub(crate) fn validate_codegen_backends(backends: Vec<String>, section: &str) -> Vec<String> {
399 for backend in &backends {
400 if let Some(stripped) = backend.strip_prefix(CODEGEN_BACKEND_PREFIX) {
401 panic!(
402 "Invalid value '{backend}' for '{section}.codegen-backends'. \
403 Codegen backends are defined without the '{CODEGEN_BACKEND_PREFIX}' prefix. \
404 Please, use '{stripped}' instead."
405 )
406 }
407 if !VALID_CODEGEN_BACKENDS.contains(&backend.as_str()) {
408 println!(
409 "HELP: '{backend}' for '{section}.codegen-backends' might fail. \
410 List of known good values: {VALID_CODEGEN_BACKENDS:?}"
411 );
412 }
413 }
414 backends
415}
416
417impl Config {
418 pub fn apply_rust_config(
419 &mut self,
420 toml_rust: Option<Rust>,
421 warnings: Warnings,
422 description: &mut Option<String>,
423 ) {
424 let mut debug = None;
425 let mut rustc_debug_assertions = None;
426 let mut std_debug_assertions = None;
427 let mut tools_debug_assertions = None;
428 let mut overflow_checks = None;
429 let mut overflow_checks_std = None;
430 let mut debug_logging = None;
431 let mut debuginfo_level = None;
432 let mut debuginfo_level_rustc = None;
433 let mut debuginfo_level_std = None;
434 let mut debuginfo_level_tools = None;
435 let mut debuginfo_level_tests = None;
436 let mut optimize = None;
437 let mut lld_enabled = None;
438 let mut std_features = None;
439
440 if let Some(rust) = toml_rust {
441 let Rust {
442 optimize: optimize_toml,
443 debug: debug_toml,
444 codegen_units,
445 codegen_units_std,
446 rustc_debug_assertions: rustc_debug_assertions_toml,
447 std_debug_assertions: std_debug_assertions_toml,
448 tools_debug_assertions: tools_debug_assertions_toml,
449 overflow_checks: overflow_checks_toml,
450 overflow_checks_std: overflow_checks_std_toml,
451 debug_logging: debug_logging_toml,
452 debuginfo_level: debuginfo_level_toml,
453 debuginfo_level_rustc: debuginfo_level_rustc_toml,
454 debuginfo_level_std: debuginfo_level_std_toml,
455 debuginfo_level_tools: debuginfo_level_tools_toml,
456 debuginfo_level_tests: debuginfo_level_tests_toml,
457 backtrace,
458 incremental,
459 randomize_layout,
460 default_linker,
461 channel: _, description: rust_description,
463 musl_root,
464 rpath,
465 verbose_tests,
466 optimize_tests,
467 codegen_tests,
468 omit_git_hash: _, dist_src,
470 save_toolstates,
471 codegen_backends,
472 lld: lld_enabled_toml,
473 llvm_tools,
474 llvm_bitcode_linker,
475 deny_warnings,
476 backtrace_on_ice,
477 verify_llvm_ir,
478 thin_lto_import_instr_limit,
479 remap_debuginfo,
480 jemalloc,
481 test_compare_mode,
482 llvm_libunwind,
483 control_flow_guard,
484 ehcont_guard,
485 new_symbol_mangling,
486 profile_generate,
487 profile_use,
488 download_rustc,
489 lto,
490 validate_mir_opts,
491 frame_pointers,
492 stack_protector,
493 strip,
494 lld_mode,
495 std_features: std_features_toml,
496 } = rust;
497
498 let debug_assertions_requested = matches!(rustc_debug_assertions_toml, Some(true))
509 || (matches!(debug_toml, Some(true))
510 && !matches!(rustc_debug_assertions_toml, Some(false)));
511
512 if debug_assertions_requested
513 && let Some(ref opt) = download_rustc
514 && opt.is_string_or_true()
515 {
516 eprintln!(
517 "WARN: currently no CI rustc builds have rustc debug assertions \
518 enabled. Please either set `rust.debug-assertions` to `false` if you \
519 want to use download CI rustc or set `rust.download-rustc` to `false`."
520 );
521 }
522
523 self.download_rustc_commit = self.download_ci_rustc_commit(
524 download_rustc,
525 debug_assertions_requested,
526 self.llvm_assertions,
527 );
528
529 debug = debug_toml;
530 rustc_debug_assertions = rustc_debug_assertions_toml;
531 std_debug_assertions = std_debug_assertions_toml;
532 tools_debug_assertions = tools_debug_assertions_toml;
533 overflow_checks = overflow_checks_toml;
534 overflow_checks_std = overflow_checks_std_toml;
535 debug_logging = debug_logging_toml;
536 debuginfo_level = debuginfo_level_toml;
537 debuginfo_level_rustc = debuginfo_level_rustc_toml;
538 debuginfo_level_std = debuginfo_level_std_toml;
539 debuginfo_level_tools = debuginfo_level_tools_toml;
540 debuginfo_level_tests = debuginfo_level_tests_toml;
541 lld_enabled = lld_enabled_toml;
542 std_features = std_features_toml;
543
544 optimize = optimize_toml;
545 self.rust_new_symbol_mangling = new_symbol_mangling;
546 set(&mut self.rust_optimize_tests, optimize_tests);
547 set(&mut self.codegen_tests, codegen_tests);
548 set(&mut self.rust_rpath, rpath);
549 set(&mut self.rust_strip, strip);
550 set(&mut self.rust_frame_pointers, frame_pointers);
551 self.rust_stack_protector = stack_protector;
552 set(&mut self.jemalloc, jemalloc);
553 set(&mut self.test_compare_mode, test_compare_mode);
554 set(&mut self.backtrace, backtrace);
555 if rust_description.is_some() {
556 eprintln!(
557 "Warning: rust.description is deprecated. Use build.description instead."
558 );
559 }
560 if description.is_none() {
561 *description = rust_description;
562 }
563 set(&mut self.rust_dist_src, dist_src);
564 set(&mut self.verbose_tests, verbose_tests);
565 if let Some(true) = incremental {
567 self.incremental = true;
568 }
569 set(&mut self.lld_mode, lld_mode);
570 set(&mut self.llvm_bitcode_linker_enabled, llvm_bitcode_linker);
571
572 self.rust_randomize_layout = randomize_layout.unwrap_or_default();
573 self.llvm_tools_enabled = llvm_tools.unwrap_or(true);
574
575 self.llvm_enzyme = self.channel == "dev" || self.channel == "nightly";
576 self.rustc_default_linker = default_linker;
577 self.musl_root = musl_root.map(PathBuf::from);
578 self.save_toolstates = save_toolstates.map(PathBuf::from);
579 set(
580 &mut self.deny_warnings,
581 match warnings {
582 Warnings::Deny => Some(true),
583 Warnings::Warn => Some(false),
584 Warnings::Default => deny_warnings,
585 },
586 );
587 set(&mut self.backtrace_on_ice, backtrace_on_ice);
588 set(&mut self.rust_verify_llvm_ir, verify_llvm_ir);
589 self.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit;
590 set(&mut self.rust_remap_debuginfo, remap_debuginfo);
591 set(&mut self.control_flow_guard, control_flow_guard);
592 set(&mut self.ehcont_guard, ehcont_guard);
593 self.llvm_libunwind_default =
594 llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
595 set(
596 &mut self.rust_codegen_backends,
597 codegen_backends.map(|backends| validate_codegen_backends(backends, "rust")),
598 );
599
600 self.rust_codegen_units = codegen_units.map(threads_from_config);
601 self.rust_codegen_units_std = codegen_units_std.map(threads_from_config);
602
603 if self.rust_profile_use.is_none() {
604 self.rust_profile_use = profile_use;
605 }
606
607 if self.rust_profile_generate.is_none() {
608 self.rust_profile_generate = profile_generate;
609 }
610
611 self.rust_lto =
612 lto.as_deref().map(|value| RustcLto::from_str(value).unwrap()).unwrap_or_default();
613 self.rust_validate_mir_opts = validate_mir_opts;
614 }
615
616 self.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true));
617
618 if self.host_target.triple == "x86_64-unknown-linux-gnu"
632 && self.hosts == [self.host_target]
633 && (self.channel == "dev" || self.channel == "nightly")
634 {
635 let no_llvm_config = self
636 .target_config
637 .get(&self.host_target)
638 .is_some_and(|target_config| target_config.llvm_config.is_none());
639 let enable_lld = self.llvm_from_ci || no_llvm_config;
640 self.lld_enabled = lld_enabled.unwrap_or(enable_lld);
642 } else {
643 set(&mut self.lld_enabled, lld_enabled);
644 }
645
646 let default_std_features = BTreeSet::from([String::from("panic-unwind")]);
647 self.rust_std_features = std_features.unwrap_or(default_std_features);
648
649 let default = debug == Some(true);
650 self.rustc_debug_assertions = rustc_debug_assertions.unwrap_or(default);
651 self.std_debug_assertions = std_debug_assertions.unwrap_or(self.rustc_debug_assertions);
652 self.tools_debug_assertions = tools_debug_assertions.unwrap_or(self.rustc_debug_assertions);
653 self.rust_overflow_checks = overflow_checks.unwrap_or(default);
654 self.rust_overflow_checks_std = overflow_checks_std.unwrap_or(self.rust_overflow_checks);
655
656 self.rust_debug_logging = debug_logging.unwrap_or(self.rustc_debug_assertions);
657
658 let with_defaults = |debuginfo_level_specific: Option<_>| {
659 debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
660 DebuginfoLevel::Limited
661 } else {
662 DebuginfoLevel::None
663 })
664 };
665 self.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
666 self.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
667 self.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
668 self.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None);
669 }
670}