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 incremental,
325 default_linker,
326 std_features,
327
328 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 warn!(current_rust_config.incremental, incremental, "rust");
393
394 Ok(())
395}
396
397impl Config {
398 pub fn apply_rust_config(
399 &mut self,
400 toml_rust: Option<Rust>,
401 warnings: Warnings,
402 description: &mut Option<String>,
403 ) {
404 let mut debug = None;
405 let mut rustc_debug_assertions = None;
406 let mut std_debug_assertions = None;
407 let mut tools_debug_assertions = None;
408 let mut overflow_checks = None;
409 let mut overflow_checks_std = None;
410 let mut debug_logging = None;
411 let mut debuginfo_level = None;
412 let mut debuginfo_level_rustc = None;
413 let mut debuginfo_level_std = None;
414 let mut debuginfo_level_tools = None;
415 let mut debuginfo_level_tests = None;
416 let mut optimize = None;
417 let mut lld_enabled = None;
418 let mut std_features = None;
419
420 if let Some(rust) = toml_rust {
421 let Rust {
422 optimize: optimize_toml,
423 debug: debug_toml,
424 codegen_units,
425 codegen_units_std,
426 rustc_debug_assertions: rustc_debug_assertions_toml,
427 std_debug_assertions: std_debug_assertions_toml,
428 tools_debug_assertions: tools_debug_assertions_toml,
429 overflow_checks: overflow_checks_toml,
430 overflow_checks_std: overflow_checks_std_toml,
431 debug_logging: debug_logging_toml,
432 debuginfo_level: debuginfo_level_toml,
433 debuginfo_level_rustc: debuginfo_level_rustc_toml,
434 debuginfo_level_std: debuginfo_level_std_toml,
435 debuginfo_level_tools: debuginfo_level_tools_toml,
436 debuginfo_level_tests: debuginfo_level_tests_toml,
437 backtrace,
438 incremental,
439 randomize_layout,
440 default_linker,
441 channel: _, description: rust_description,
443 musl_root,
444 rpath,
445 verbose_tests,
446 optimize_tests,
447 codegen_tests,
448 omit_git_hash: _, dist_src,
450 save_toolstates,
451 codegen_backends,
452 lld: lld_enabled_toml,
453 llvm_tools,
454 llvm_bitcode_linker,
455 deny_warnings,
456 backtrace_on_ice,
457 verify_llvm_ir,
458 thin_lto_import_instr_limit,
459 remap_debuginfo,
460 jemalloc,
461 test_compare_mode,
462 llvm_libunwind,
463 control_flow_guard,
464 ehcont_guard,
465 new_symbol_mangling,
466 profile_generate,
467 profile_use,
468 download_rustc,
469 lto,
470 validate_mir_opts,
471 frame_pointers,
472 stack_protector,
473 strip,
474 lld_mode,
475 std_features: std_features_toml,
476 } = rust;
477
478 let debug_assertions_requested = matches!(rustc_debug_assertions_toml, Some(true))
489 || (matches!(debug_toml, Some(true))
490 && !matches!(rustc_debug_assertions_toml, Some(false)));
491
492 if debug_assertions_requested
493 && let Some(ref opt) = download_rustc
494 && opt.is_string_or_true()
495 {
496 eprintln!(
497 "WARN: currently no CI rustc builds have rustc debug assertions \
498 enabled. Please either set `rust.debug-assertions` to `false` if you \
499 want to use download CI rustc or set `rust.download-rustc` to `false`."
500 );
501 }
502
503 self.download_rustc_commit = self.download_ci_rustc_commit(
504 download_rustc,
505 debug_assertions_requested,
506 self.llvm_assertions,
507 );
508
509 debug = debug_toml;
510 rustc_debug_assertions = rustc_debug_assertions_toml;
511 std_debug_assertions = std_debug_assertions_toml;
512 tools_debug_assertions = tools_debug_assertions_toml;
513 overflow_checks = overflow_checks_toml;
514 overflow_checks_std = overflow_checks_std_toml;
515 debug_logging = debug_logging_toml;
516 debuginfo_level = debuginfo_level_toml;
517 debuginfo_level_rustc = debuginfo_level_rustc_toml;
518 debuginfo_level_std = debuginfo_level_std_toml;
519 debuginfo_level_tools = debuginfo_level_tools_toml;
520 debuginfo_level_tests = debuginfo_level_tests_toml;
521 lld_enabled = lld_enabled_toml;
522 std_features = std_features_toml;
523
524 optimize = optimize_toml;
525 self.rust_new_symbol_mangling = new_symbol_mangling;
526 set(&mut self.rust_optimize_tests, optimize_tests);
527 set(&mut self.codegen_tests, codegen_tests);
528 set(&mut self.rust_rpath, rpath);
529 set(&mut self.rust_strip, strip);
530 set(&mut self.rust_frame_pointers, frame_pointers);
531 self.rust_stack_protector = stack_protector;
532 set(&mut self.jemalloc, jemalloc);
533 set(&mut self.test_compare_mode, test_compare_mode);
534 set(&mut self.backtrace, backtrace);
535 if rust_description.is_some() {
536 eprintln!(
537 "Warning: rust.description is deprecated. Use build.description instead."
538 );
539 }
540 if description.is_none() {
541 *description = rust_description;
542 }
543 set(&mut self.rust_dist_src, dist_src);
544 set(&mut self.verbose_tests, verbose_tests);
545 if let Some(true) = incremental {
547 self.incremental = true;
548 }
549 set(&mut self.lld_mode, lld_mode);
550 set(&mut self.llvm_bitcode_linker_enabled, llvm_bitcode_linker);
551
552 self.rust_randomize_layout = randomize_layout.unwrap_or_default();
553 self.llvm_tools_enabled = llvm_tools.unwrap_or(true);
554
555 self.llvm_enzyme = self.channel == "dev" || self.channel == "nightly";
556 self.rustc_default_linker = default_linker;
557 self.musl_root = musl_root.map(PathBuf::from);
558 self.save_toolstates = save_toolstates.map(PathBuf::from);
559 set(
560 &mut self.deny_warnings,
561 match warnings {
562 Warnings::Deny => Some(true),
563 Warnings::Warn => Some(false),
564 Warnings::Default => deny_warnings,
565 },
566 );
567 set(&mut self.backtrace_on_ice, backtrace_on_ice);
568 set(&mut self.rust_verify_llvm_ir, verify_llvm_ir);
569 self.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit;
570 set(&mut self.rust_remap_debuginfo, remap_debuginfo);
571 set(&mut self.control_flow_guard, control_flow_guard);
572 set(&mut self.ehcont_guard, ehcont_guard);
573 self.llvm_libunwind_default =
574 llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
575
576 if let Some(ref backends) = codegen_backends {
577 let available_backends = ["llvm", "cranelift", "gcc"];
578
579 self.rust_codegen_backends = backends.iter().map(|s| {
580 if let Some(backend) = s.strip_prefix(CODEGEN_BACKEND_PREFIX) {
581 if available_backends.contains(&backend) {
582 panic!("Invalid value '{s}' for 'rust.codegen-backends'. Instead, please use '{backend}'.");
583 } else {
584 println!("HELP: '{s}' for 'rust.codegen-backends' might fail. \
585 Codegen backends are mostly defined without the '{CODEGEN_BACKEND_PREFIX}' prefix. \
586 In this case, it would be referred to as '{backend}'.");
587 }
588 }
589
590 s.clone()
591 }).collect();
592 }
593
594 self.rust_codegen_units = codegen_units.map(threads_from_config);
595 self.rust_codegen_units_std = codegen_units_std.map(threads_from_config);
596
597 if self.rust_profile_use.is_none() {
598 self.rust_profile_use = profile_use;
599 }
600
601 if self.rust_profile_generate.is_none() {
602 self.rust_profile_generate = profile_generate;
603 }
604
605 self.rust_lto =
606 lto.as_deref().map(|value| RustcLto::from_str(value).unwrap()).unwrap_or_default();
607 self.rust_validate_mir_opts = validate_mir_opts;
608 }
609
610 self.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true));
611
612 if self.build.triple == "x86_64-unknown-linux-gnu"
626 && self.hosts == [self.build]
627 && (self.channel == "dev" || self.channel == "nightly")
628 {
629 let no_llvm_config = self
630 .target_config
631 .get(&self.build)
632 .is_some_and(|target_config| target_config.llvm_config.is_none());
633 let enable_lld = self.llvm_from_ci || no_llvm_config;
634 self.lld_enabled = lld_enabled.unwrap_or(enable_lld);
636 } else {
637 set(&mut self.lld_enabled, lld_enabled);
638 }
639
640 let default_std_features = BTreeSet::from([String::from("panic-unwind")]);
641 self.rust_std_features = std_features.unwrap_or(default_std_features);
642
643 let default = debug == Some(true);
644 self.rustc_debug_assertions = rustc_debug_assertions.unwrap_or(default);
645 self.std_debug_assertions = std_debug_assertions.unwrap_or(self.rustc_debug_assertions);
646 self.tools_debug_assertions = tools_debug_assertions.unwrap_or(self.rustc_debug_assertions);
647 self.rust_overflow_checks = overflow_checks.unwrap_or(default);
648 self.rust_overflow_checks_std = overflow_checks_std.unwrap_or(self.rust_overflow_checks);
649
650 self.rust_debug_logging = debug_logging.unwrap_or(self.rustc_debug_assertions);
651
652 let with_defaults = |debuginfo_level_specific: Option<_>| {
653 debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
654 DebuginfoLevel::Limited
655 } else {
656 DebuginfoLevel::None
657 })
658 };
659 self.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
660 self.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
661 self.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
662 self.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None);
663 }
664}