1use std::collections::BTreeSet;
5use std::path::PathBuf;
6
7use build_helper::ci::CiEnv;
8use serde::{Deserialize, Deserializer};
9
10use crate::CodegenBackendKind;
11use crate::core::config::macros::define_config;
12use crate::core::config::toml::TomlConfig;
13use crate::core::config::{CompressDebuginfo, DebuginfoLevel, StringOrBool, TargetSelection};
14use crate::utils::helpers;
15
16define_config! {
17 #[derive(Default)]
19 struct Rust {
20 optimize: Option<RustOptimize> = "optimize",
21 debug: Option<bool> = "debug",
22 codegen_units: Option<u32> = "codegen-units",
23 codegen_units_std: Option<u32> = "codegen-units-std",
24 rustc_debug_assertions: Option<bool> = "debug-assertions",
25 randomize_layout: Option<bool> = "randomize-layout",
26 std_debug_assertions: Option<bool> = "debug-assertions-std",
27 tools_debug_assertions: Option<bool> = "debug-assertions-tools",
28 overflow_checks: Option<bool> = "overflow-checks",
29 overflow_checks_std: Option<bool> = "overflow-checks-std",
30 debug_logging: Option<bool> = "debug-logging",
31 debuginfo_level: Option<DebuginfoLevel> = "debuginfo-level",
32 debuginfo_level_rustc: Option<DebuginfoLevel> = "debuginfo-level-rustc",
33 debuginfo_level_std: Option<DebuginfoLevel> = "debuginfo-level-std",
34 debuginfo_level_tools: Option<DebuginfoLevel> = "debuginfo-level-tools",
35 debuginfo_level_tests: Option<DebuginfoLevel> = "debuginfo-level-tests",
36 compress_debuginfo: Option<CompressDebuginfo> = "compress-debuginfo",
37 backtrace: Option<bool> = "backtrace",
38 incremental: Option<bool> = "incremental",
39 default_linker: Option<String> = "default-linker",
40 channel: Option<String> = "channel",
41 musl_root: Option<String> = "musl-root",
42 rpath: Option<bool> = "rpath",
43 rustflags: Option<Vec<String>> = "rustflags",
44 strip: Option<bool> = "strip",
45 frame_pointers: Option<bool> = "frame-pointers",
46 stack_protector: Option<String> = "stack-protector",
47 verbose_tests: Option<bool> = "verbose-tests",
48 optimize_tests: Option<bool> = "optimize-tests",
49 codegen_tests: Option<bool> = "codegen-tests",
50 omit_git_hash: Option<bool> = "omit-git-hash",
51 dist_src: Option<bool> = "dist-src",
52 save_toolstates: Option<String> = "save-toolstates",
53 codegen_backends: Option<Vec<String>> = "codegen-backends",
54 llvm_bitcode_linker: Option<bool> = "llvm-bitcode-linker",
55 lld: Option<bool> = "lld",
56 bootstrap_override_lld: Option<BootstrapOverrideLld> = "bootstrap-override-lld",
57 llvm_tools: Option<bool> = "llvm-tools",
58 deny_warnings: Option<bool> = "deny-warnings",
59 backtrace_on_ice: Option<bool> = "backtrace-on-ice",
60 verify_llvm_ir: Option<bool> = "verify-llvm-ir",
61 thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
62 remap_debuginfo: Option<bool> = "remap-debuginfo",
63 jemalloc: Option<bool> = "jemalloc",
65 test_compare_mode: Option<bool> = "test-compare-mode",
66 llvm_libunwind: Option<String> = "llvm-libunwind",
67 control_flow_guard: Option<bool> = "control-flow-guard",
68 ehcont_guard: Option<bool> = "ehcont-guard",
69 new_symbol_mangling: Option<bool> = "new-symbol-mangling",
70 annotate_moves_size_limit: Option<u64> = "annotate-moves-size-limit",
71 profile_generate: Option<PathBuf> = "profile-generate",
73 profile_use: Option<PathBuf> = "profile-use",
75 download_rustc: Option<StringOrBool> = "download-rustc",
77 lto: Option<String> = "lto",
78 validate_mir_opts: Option<u32> = "validate-mir-opts",
79 std_features: Option<BTreeSet<String>> = "std-features",
80 break_on_ice: Option<bool> = "break-on-ice",
81 parallel_frontend_threads: Option<u32> = "parallel-frontend-threads",
82 stdlib_semver_baseline: Option<String> = "stdlib-semver-baseline",
83 wasm_proc_macros: Option<bool> = "wasm-proc-macros",
84 }
85}
86
87#[derive(Copy, Clone, Default, Debug, PartialEq)]
110pub enum BootstrapOverrideLld {
111 #[default]
113 None,
114 SelfContained,
116 External,
120}
121
122impl BootstrapOverrideLld {
123 pub fn is_used(&self) -> bool {
124 match self {
125 BootstrapOverrideLld::SelfContained | BootstrapOverrideLld::External => true,
126 BootstrapOverrideLld::None => false,
127 }
128 }
129}
130
131impl<'de> Deserialize<'de> for BootstrapOverrideLld {
132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133 where
134 D: Deserializer<'de>,
135 {
136 struct LldModeVisitor;
137
138 impl serde::de::Visitor<'_> for LldModeVisitor {
139 type Value = BootstrapOverrideLld;
140
141 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 formatter.write_str("one of true, 'self-contained' or 'external'")
143 }
144
145 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
146 where
147 E: serde::de::Error,
148 {
149 Ok(if v { BootstrapOverrideLld::External } else { BootstrapOverrideLld::None })
150 }
151
152 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
153 where
154 E: serde::de::Error,
155 {
156 match v {
157 "external" => Ok(BootstrapOverrideLld::External),
158 "self-contained" => Ok(BootstrapOverrideLld::SelfContained),
159 _ => Err(E::custom(format!("unknown mode {v}"))),
160 }
161 }
162 }
163
164 deserializer.deserialize_any(LldModeVisitor)
165 }
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub enum RustOptimize {
170 String(String),
171 Int(u8),
172 Bool(bool),
173}
174
175impl Default for RustOptimize {
176 fn default() -> RustOptimize {
177 RustOptimize::Bool(false)
178 }
179}
180
181impl<'de> Deserialize<'de> for RustOptimize {
182 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183 where
184 D: Deserializer<'de>,
185 {
186 deserializer.deserialize_any(OptimizeVisitor)
187 }
188}
189
190struct OptimizeVisitor;
191
192impl serde::de::Visitor<'_> for OptimizeVisitor {
193 type Value = RustOptimize;
194
195 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 formatter.write_str(r#"one of: 0, 1, 2, 3, "s", "z", true, false"#)
197 }
198
199 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
200 where
201 E: serde::de::Error,
202 {
203 if matches!(value, "s" | "z") {
204 Ok(RustOptimize::String(value.to_string()))
205 } else {
206 Err(serde::de::Error::custom(format_optimize_error_msg(value)))
207 }
208 }
209
210 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
211 where
212 E: serde::de::Error,
213 {
214 if matches!(value, 0..=3) {
215 Ok(RustOptimize::Int(value as u8))
216 } else {
217 Err(serde::de::Error::custom(format_optimize_error_msg(value)))
218 }
219 }
220
221 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
222 where
223 E: serde::de::Error,
224 {
225 Ok(RustOptimize::Bool(value))
226 }
227}
228
229fn format_optimize_error_msg(v: impl std::fmt::Display) -> String {
230 format!(
231 r#"unrecognized option for rust optimize: "{v}", expected one of 0, 1, 2, 3, "s", "z", true, false"#
232 )
233}
234
235impl RustOptimize {
236 pub(crate) fn is_release(&self) -> bool {
237 match &self {
238 RustOptimize::Bool(true) | RustOptimize::String(_) => true,
239 RustOptimize::Int(i) => *i > 0,
240 RustOptimize::Bool(false) => false,
241 }
242 }
243
244 pub(crate) fn get_opt_level(&self) -> Option<String> {
245 match &self {
246 RustOptimize::String(s) => Some(s.clone()),
247 RustOptimize::Int(i) => Some(i.to_string()),
248 RustOptimize::Bool(_) => None,
249 }
250 }
251}
252
253pub fn check_incompatible_options_for_ci_rustc(
256 host: TargetSelection,
257 current_config_toml: TomlConfig,
258 ci_config_toml: TomlConfig,
259) -> Result<(), String> {
260 macro_rules! err {
261 ($current:expr, $expected:expr, $config_section:expr) => {
262 if let Some(current) = &$current {
263 if Some(current) != $expected.as_ref() {
264 return Err(format!(
265 "ERROR: Setting `{}` is incompatible with `rust.download-rustc`. \
266 Current value: {:?}, Expected value(s): {}{:?}",
267 format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
268 $current,
269 if $expected.is_some() { "None/" } else { "" },
270 $expected,
271 ));
272 };
273 };
274 };
275 }
276
277 macro_rules! warn {
278 ($current:expr, $expected:expr, $config_section:expr) => {
279 if let Some(current) = &$current {
280 if Some(current) != $expected.as_ref() {
281 println!(
282 "WARNING: `{}` has no effect with `rust.download-rustc`. \
283 Current value: {:?}, Expected value(s): {}{:?}",
284 format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
285 $current,
286 if $expected.is_some() { "None/" } else { "" },
287 $expected,
288 );
289 };
290 };
291 };
292 }
293
294 let current_profiler = current_config_toml.build.as_ref().and_then(|b| b.profiler);
295 let profiler = ci_config_toml.build.as_ref().and_then(|b| b.profiler);
296 err!(current_profiler, profiler, "build");
297
298 let current_optimized_compiler_builtins =
299 current_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
300 let optimized_compiler_builtins =
301 ci_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
302 err!(current_optimized_compiler_builtins, optimized_compiler_builtins, "build");
303
304 let current_allocator = current_config_toml.build.as_ref().and_then(|b| b.allocator);
305 let allocator = ci_config_toml.build.as_ref().and_then(|b| b.allocator);
306 err!(current_allocator, allocator, "build");
307
308 let host_str = host.to_string();
311 if let Some(current_cfg) = current_config_toml.target.as_ref().and_then(|c| c.get(&host_str))
312 && current_cfg.profiler.is_some()
313 {
314 let ci_target_toml = ci_config_toml.target.as_ref().and_then(|c| c.get(&host_str));
315 let ci_cfg = ci_target_toml.ok_or(format!(
316 "Target specific config for '{host_str}' is not present for CI-rustc"
317 ))?;
318
319 let profiler = &ci_cfg.profiler;
320 err!(current_cfg.profiler, profiler, format!("target.{host_str}"));
321
322 let optimized_compiler_builtins = &ci_cfg.optimized_compiler_builtins;
323 err!(
324 current_cfg.optimized_compiler_builtins,
325 optimized_compiler_builtins,
326 format!("target.{host_str}")
327 );
328
329 err!(current_cfg.allocator, &ci_cfg.allocator, format!("target.{host_str}"));
330 err!(current_cfg.jemalloc, &ci_cfg.jemalloc, format!("target.{host_str}"));
331 }
332
333 let (Some(current_rust_config), Some(ci_rust_config)) =
334 (current_config_toml.rust, ci_config_toml.rust)
335 else {
336 return Ok(());
337 };
338
339 let Rust {
340 optimize,
342 randomize_layout,
343 debug_logging,
344 debuginfo_level_rustc,
345 compress_debuginfo,
346 llvm_tools,
347 llvm_bitcode_linker,
348 stack_protector,
349 strip,
350 jemalloc,
351 rpath,
352 channel,
353 default_linker,
354 std_features,
355
356 incremental: _,
358 debug: _,
359 codegen_units: _,
360 codegen_units_std: _,
361 rustc_debug_assertions: _,
362 std_debug_assertions: _,
363 tools_debug_assertions: _,
364 overflow_checks: _,
365 overflow_checks_std: _,
366 debuginfo_level: _,
367 debuginfo_level_std: _,
368 debuginfo_level_tools: _,
369 debuginfo_level_tests: _,
370 backtrace: _,
371 musl_root: _,
372 verbose_tests: _,
373 optimize_tests: _,
374 codegen_tests: _,
375 omit_git_hash: _,
376 dist_src: _,
377 save_toolstates: _,
378 codegen_backends: _,
379 lld: _,
380 lto: _,
381 deny_warnings: _,
382 backtrace_on_ice: _,
383 verify_llvm_ir: _,
384 thin_lto_import_instr_limit: _,
385 remap_debuginfo: _,
386 test_compare_mode: _,
387 llvm_libunwind: _,
388 control_flow_guard: _,
389 ehcont_guard: _,
390 new_symbol_mangling: _,
391 annotate_moves_size_limit: _,
392 profile_generate: _,
393 profile_use: _,
394 download_rustc: _,
395 validate_mir_opts: _,
396 frame_pointers: _,
397 break_on_ice: _,
398 parallel_frontend_threads: _,
399 bootstrap_override_lld: _,
400 rustflags: _,
401 stdlib_semver_baseline: _,
402 wasm_proc_macros: _,
403 } = ci_rust_config;
404
405 err!(current_rust_config.optimize, optimize, "rust");
413 err!(current_rust_config.randomize_layout, randomize_layout, "rust");
414 err!(current_rust_config.compress_debuginfo, compress_debuginfo, "rust");
415 err!(current_rust_config.debug_logging, debug_logging, "rust");
416 err!(current_rust_config.debuginfo_level_rustc, debuginfo_level_rustc, "rust");
417 err!(current_rust_config.rpath, rpath, "rust");
418 err!(current_rust_config.strip, strip, "rust");
419 err!(current_rust_config.llvm_tools, llvm_tools, "rust");
420 err!(current_rust_config.llvm_bitcode_linker, llvm_bitcode_linker, "rust");
421 err!(current_rust_config.jemalloc, jemalloc, "rust");
422 err!(current_rust_config.default_linker, default_linker, "rust");
423 err!(current_rust_config.stack_protector, stack_protector, "rust");
424 err!(current_rust_config.std_features, std_features, "rust");
425
426 warn!(current_rust_config.channel, channel, "rust");
427
428 Ok(())
429}
430
431pub(crate) const BUILTIN_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"];
432
433pub(crate) fn parse_codegen_backends(
434 backends: Vec<String>,
435 section: &str,
436) -> Vec<CodegenBackendKind> {
437 const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
438
439 let mut found_backends = vec![];
440 for backend in &backends {
441 if let Some(stripped) = backend.strip_prefix(CODEGEN_BACKEND_PREFIX) {
442 panic!(
443 "Invalid value '{backend}' for '{section}.codegen-backends'. \
444 Codegen backends are defined without the '{CODEGEN_BACKEND_PREFIX}' prefix. \
445 Please, use '{stripped}' instead."
446 )
447 }
448 let backend = match backend.as_str() {
449 "llvm" => CodegenBackendKind::Llvm,
450 "cranelift" => CodegenBackendKind::Cranelift,
451 "gcc" => CodegenBackendKind::Gcc,
452 backend => CodegenBackendKind::Custom(backend.to_string()),
453 };
454
455 if found_backends.contains(&backend) {
456 panic!(
457 "Duplicate value '{}' for '{section}.codegen-backends'. \
458 Each codegen backend should only be specified once.",
459 backend.name()
460 );
461 }
462
463 if !BUILTIN_CODEGEN_BACKENDS.contains(&backend.name()) {
464 if CiEnv::is_rust_lang_managed_ci_job() {
465 eprintln!("Unknown codegen backend {}", backend.name());
466 helpers::exit_process(1);
467 }
468
469 println!(
470 "HELP: '{}' for '{section}.codegen-backends' might fail. \
471 List of known codegen backends: {BUILTIN_CODEGEN_BACKENDS:?}",
472 backend.name()
473 );
474 }
475 found_backends.push(backend);
476 }
477 if found_backends.is_empty() {
478 eprintln!("ERROR: `{section}.codegen-backends` should not be set to `[]`");
479 helpers::exit_process(1);
480 }
481 found_backends
482}