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