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