1use std::any::Any;
2use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
3use std::num::NonZero;
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, OnceLock};
7use std::{env, thread};
8
9use rand::{RngCore, rng};
10use rustc_ast as ast;
11use rustc_attr_parsing::ShouldEmit;
12use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
13use rustc_codegen_ssa::back::link::link_binary;
14use rustc_codegen_ssa::target_features::internal_target_features;
15use rustc_codegen_ssa::traits::CodegenBackend;
16use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
17use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
18use rustc_data_structures::jobserver::Proxy;
19use rustc_data_structures::sync;
20use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
21use rustc_middle::dep_graph::WorkProductMap;
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24use rustc_session::config::{
25 Cfg, CrateType, Jobs, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
26};
27use rustc_session::{EarlyDiagCtxt, IncrCompSession, Session, filesearch};
28use rustc_span::edition::Edition;
29use rustc_span::source_map::SourceMapInputs;
30use rustc_span::{SessionGlobals, Symbol, sym};
31use rustc_target::spec::Target;
32use tracing::info;
33
34use crate::diagnostics;
35use crate::passes::parse_crate_name;
36
37type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
39
40pub(crate) fn add_configuration(
46 cfg: &mut Cfg,
47 sess: &mut Session,
48 codegen_backend: &dyn CodegenBackend,
49) {
50 let tf = sym::target_feature;
51 let tf_cfg = codegen_backend.target_config(sess);
52
53 cfg.extend(
55 sess.target
56 .rust_target_features()
57 .iter()
58 .filter_map(|(feature, gate, _)| {
59 if gate.in_cfg()
60 && (sess.is_nightly_build()
61 || gate.requires_nightly(true).is_none())
62 {
63 Some(Symbol::intern(feature))
64 } else {
65 None
66 }
67 })
68 .filter(|feature| tf_cfg.internal_target_features.contains(&feature))
69 .map(|feature| (sym::target_feature, Some(feature))),
70 );
71
72 sess.internal_target_features.extend(tf_cfg.internal_target_features.into_sorted_stable_ord());
74
75 if tf_cfg.has_reliable_f16 {
76 cfg.insert((sym::target_has_reliable_f16, None));
77 }
78 if tf_cfg.has_reliable_f16_math {
79 cfg.insert((sym::target_has_reliable_f16_math, None));
80 }
81 if tf_cfg.has_reliable_f128 {
82 cfg.insert((sym::target_has_reliable_f128, None));
83 }
84 if tf_cfg.has_reliable_f128_math {
85 cfg.insert((sym::target_has_reliable_f128_math, None));
86 }
87
88 if sess.crt_static(None) {
89 cfg.insert((tf, Some(sym::crt_dash_static)));
90 }
91}
92
93pub(crate) fn check_abi_required_features(sess: &Session) {
96 let abi_feature_constraints = sess.target.abi_required_features();
97 for feature in
101 abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
102 {
103 if !sess.target.rust_target_features().iter().any(|(name, ..)|
feature == name) {
{
::core::panicking::panic_fmt(format_args!("target feature {0} is required/incompatible for the current ABI but not a recognized feature for this target",
feature));
}
};assert!(
104 sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
105 "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
106 );
107 }
108
109 for feature in abi_feature_constraints.required {
110 if !sess.internal_target_features.contains(&Symbol::intern(feature)) {
111 sess.dcx()
112 .emit_warn(diagnostics::AbiRequiredTargetFeature { feature, enabled: "enabled" });
113 }
114 }
115 for feature in abi_feature_constraints.incompatible {
116 if sess.internal_target_features.contains(&Symbol::intern(feature)) {
117 sess.dcx()
118 .emit_warn(diagnostics::AbiRequiredTargetFeature { feature, enabled: "disabled" });
119 }
120 }
121}
122
123pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
124pub const DEFAULT_STACK_SIZE: usize = 16 * 1024 * 1024;
125
126fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
127 *STACK_SIZE.get_or_init(|| {
129 env::var_os("RUST_MIN_STACK")
130 .as_ref()
131 .map(|os_str| os_str.to_string_lossy())
132 .filter(|s| !s.trim().is_empty())
136 .map(|s| {
140 let s = s.trim();
141 s.parse::<usize>().unwrap_or_else(|_| {
142 let mut err = early_dcx.early_struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`RUST_MIN_STACK` should be a number of bytes, but was \"{0}\"",
s))
})format!(
143 r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
144 ));
145 err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
146 err.emit()
147 })
148 })
149 .unwrap_or(DEFAULT_STACK_SIZE)
151 })
152}
153
154fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
155 thread_stack_size: usize,
156 edition: Edition,
157 sm_inputs: SourceMapInputs,
158 extra_symbols: &[&'static str],
159 f: F,
160) -> R {
161 let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
168
169 thread::scope(|s| {
172 let r = builder
175 .spawn_scoped(s, move || {
176 rustc_span::create_session_globals_then(
177 edition,
178 extra_symbols,
179 Some(sm_inputs),
180 || f(CurrentGcx::new()),
181 )
182 })
183 .unwrap()
184 .join();
185
186 match r {
187 Ok(v) => v,
188 Err(e) => std::panic::resume_unwind(e),
189 }
190 })
191}
192
193pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
194 thread_builder_diag: &EarlyDiagCtxt,
195 edition: Edition,
196 jobs: Jobs,
197 extra_symbols: &[&'static str],
198 sm_inputs: SourceMapInputs,
199 f: F,
200) -> R {
201 use std::process;
202
203 use rustc_data_structures::defer;
204 use rustc_middle::ty::tls;
205 use rustc_query_impl::break_query_cycle;
206
207 let thread_stack_size = init_stack_size(thread_builder_diag);
208
209 let jobs_frontend = jobs.frontend.or(NonZero::new(1)).unwrap();
210 let registry = sync::Registry::new(jobs_frontend);
211
212 let Some(proof) = sync::check_dyn_thread_safe() else {
213 {
match (&jobs_frontend.get(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(jobs_frontend.get(), 1);
214 return run_in_thread_with_globals(
215 thread_stack_size,
216 edition,
217 sm_inputs,
218 extra_symbols,
219 |current_gcx| {
220 registry.register();
222
223 f(current_gcx)
224 },
225 );
226 };
227
228 let current_gcx = proof.derive(CurrentGcx::new());
229 let current_gcx2 = current_gcx.clone();
230
231 let proxy = Proxy::new();
232 let proxy_ = Arc::clone(&proxy);
233
234 let builder = rustc_thread_pool::ThreadPoolBuilder::new()
235 .thread_name(|_| "rustc".to_string())
236 .acquire_thread_handler(move || proxy.acquire_thread())
237 .release_thread_handler(move || proxy_.release_thread())
238 .num_threads(jobs_frontend.get())
239 .deadlock_handler(move || {
240 let current_gcx2 = current_gcx2.clone();
244 let registry = rustc_thread_pool::Registry::current();
245 let session_globals = rustc_span::with_session_globals(|session_globals| {
246 session_globals as *const SessionGlobals as usize
247 });
248 thread::Builder::new()
249 .name("rustc query cycle handler".to_string())
250 .spawn(move || {
251 let on_panic = defer(|| {
252 const MESSAGE: &str = "\
256internal compiler error: query cycle handler thread panicked, aborting process";
257 { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
258 process::abort();
261 });
262
263 current_gcx2.access(|gcx| {
266 tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
267 tls::with(|tcx| {
268 let job_map = rustc_span::set_session_globals_then(
271 unsafe { &*(session_globals as *const SessionGlobals) },
272 || {
273 collect_active_query_jobs(
277 tcx,
278 CollectActiveJobsKind::FullNoContention,
279 )
280 },
281 );
282 break_query_cycle(job_map, ®istry);
283 })
284 })
285 });
286
287 on_panic.disable();
288 })
289 .unwrap();
290 })
291 .stack_size(thread_stack_size);
292
293 rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
298 rustc_span::with_session_globals(|session_globals| {
299 let session_globals = proof.derive(session_globals);
300 builder
301 .build_scoped(
302 move |thread: rustc_thread_pool::ThreadBuilder| {
304 registry.register();
306
307 rustc_span::set_session_globals_then(session_globals.into_inner(), || {
308 thread.run()
309 })
310 },
311 move |pool: &rustc_thread_pool::ThreadPool| {
313 pool.install(|| f(current_gcx.into_inner()))
314 },
315 )
316 .unwrap_or_else(|err| {
317 let mut diag = thread_builder_diag.early_struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to spawn compiler thread pool: could not create {0} threads ({1})",
jobs_frontend, err))
})format!(
318 "failed to spawn compiler thread pool: could not create {jobs_frontend} threads ({err})",
319 ));
320 diag.help(
321 "try lowering `-Z threads` or checking the operating system's resource limits",
322 );
323 diag.emit()
324 })
325 })
326 })
327}
328
329fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
330 match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
331 Ok(backend_sym) => backend_sym,
332 Err(DylibError::DlOpen(path, err)) => {
333 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("couldn\'t load codegen backend {0}{1}",
path, err))
})format!("couldn't load codegen backend {path}{err}");
334 early_dcx.early_fatal(err);
335 }
336 Err(DylibError::DlSym(_path, err)) => {
337 let e = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
err))
})format!(
338 "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
339 );
340 early_dcx.early_fatal(e);
341 }
342 }
343}
344
345pub fn get_codegen_backend(
349 early_dcx: &EarlyDiagCtxt,
350 sysroot: &Sysroot,
351 backend_name: Option<&str>,
352 target: &Target,
353) -> Box<dyn CodegenBackend> {
354 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
355
356 let load = LOAD.get_or_init(|| {
357 let backend = backend_name
358 .or(target.default_codegen_backend.as_deref())
359 .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
360 .unwrap_or("dummy");
361
362 match backend {
363 filename if filename.contains('.') => {
364 load_backend_from_dylib(early_dcx, filename.as_ref())
365 }
366 "dummy" => || Box::new(DummyCodegenBackend { target_config_override: None }),
367 #[cfg(feature = "llvm")]
368 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
369 backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
370 }
371 });
372
373 unsafe { load() }
377}
378
379pub struct DummyCodegenBackend {
380 pub target_config_override: Option<Box<dyn Fn(&Session) -> TargetConfig>>,
381}
382
383impl CodegenBackend for DummyCodegenBackend {
384 fn name(&self) -> &'static str {
385 "dummy"
386 }
387
388 fn target_config(&self, sess: &Session) -> TargetConfig {
389 if let Some(target_config_override) = &self.target_config_override {
390 return target_config_override(sess);
391 }
392
393 let abi_required_features = sess.target.abi_required_features();
394 let internal_target_features = internal_target_features::<0>(
395 sess,
396 |_feature| Default::default(),
397 |feature| {
398 abi_required_features.required.contains(&feature)
403 },
404 );
405
406 TargetConfig {
407 internal_target_features,
408 has_reliable_f16: true,
409 has_reliable_f16_math: true,
410 has_reliable_f128: true,
411 has_reliable_f128_math: true,
412 }
413 }
414
415 fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
416 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[CrateType::Rlib, CrateType::Executable]))vec![CrateType::Rlib, CrateType::Executable]
421 }
422
423 fn target_cpu(&self, _sess: &Session) -> String {
424 String::new()
425 }
426
427 fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
428 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
429 }
430
431 fn join_codegen(
432 &self,
433 ongoing_codegen: Box<dyn Any>,
434 _sess: &Session,
435 _incr_comp_session: Option<&IncrCompSession>,
436 _outputs: &OutputFilenames,
437 _crate_info: &CrateInfo,
438 ) -> (CompiledModules, WorkProductMap) {
439 (*ongoing_codegen.downcast().unwrap(), WorkProductMap::default())
440 }
441
442 fn link(
443 &self,
444 sess: &Session,
445 compiled_modules: CompiledModules,
446 crate_info: CrateInfo,
447 metadata: EncodedMetadata,
448 outputs: &OutputFilenames,
449 ) {
450 #[allow(rustc::bad_opt_access)]
452 if let Some(&crate_type) =
453 crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
454 && outputs.outputs.should_link()
455 {
456 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate type {0} not supported by the dummy codegen backend",
crate_type))
})format!(
457 "crate type {crate_type} not supported by the dummy codegen backend"
458 ));
459 }
460
461 link_binary(
462 sess,
463 &DummyArchiveBuilderBuilder,
464 compiled_modules,
465 crate_info,
466 metadata,
467 outputs,
468 self.name(),
469 );
470 }
471}
472
473struct DummyArchiveBuilderBuilder;
474
475impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
476 fn new_archive_builder<'a>(
477 &self,
478 sess: &'a Session,
479 ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
480 ArArchiveBuilderBuilder.new_archive_builder(sess)
481 }
482
483 fn create_dll_import_lib(
484 &self,
485 sess: &Session,
486 _lib_name: &str,
487 _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
488 output_path: &Path,
489 ) {
490 ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
492 }
493}
494
495pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
499 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
500
501 RUSTC_PATH
502 .get_or_init(|| {
503 let candidate = sysroot
504 .default
505 .join("bin"env!("RUSTC_INSTALL_BINDIR"))
506 .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
507 candidate.exists().then_some(candidate)
508 })
509 .as_deref()
510}
511
512fn get_codegen_sysroot(
513 early_dcx: &EarlyDiagCtxt,
514 sysroot: &Sysroot,
515 backend_name: &str,
516) -> MakeBackendFn {
517 static LOADED: AtomicBool = AtomicBool::new(false);
523 if !!LOADED.fetch_or(true, Ordering::SeqCst) {
{
::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
}
};assert!(
524 !LOADED.fetch_or(true, Ordering::SeqCst),
525 "cannot load the default codegen backend twice"
526 );
527
528 let target = host_tuple();
529
530 let sysroot = sysroot
531 .all_paths()
532 .map(|sysroot| {
533 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
534 })
535 .find(|f| {
536 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:536",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(536u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
f.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("codegen backend candidate: {}", f.display());
537 f.exists()
538 })
539 .unwrap_or_else(|| {
540 let candidates = sysroot
541 .all_paths()
542 .map(|p| p.display().to_string())
543 .collect::<Vec<_>>()
544 .join("\n* ");
545 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to find a `codegen-backends` folder in the sysroot candidates:\n* {0}",
candidates))
})format!(
546 "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
547 * {candidates}"
548 );
549 early_dcx.early_fatal(err);
550 });
551
552 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/util.rs:552",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(552u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
sysroot.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
553
554 let d = sysroot.read_dir().unwrap_or_else(|e| {
555 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to load default codegen backend, couldn\'t read `{0}`: {1}",
sysroot.display(), e))
})format!(
556 "failed to load default codegen backend, couldn't read `{}`: {e}",
557 sysroot.display(),
558 );
559 early_dcx.early_fatal(err);
560 });
561
562 let mut file: Option<PathBuf> = None;
563
564 let expected_names = &[
565 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
backend_name, "1.99.0-nightly"))
})format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
566 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
})format!("rustc_codegen_{backend_name}"),
567 ];
568 for entry in d.filter_map(|e| e.ok()) {
569 let path = entry.path();
570 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
571 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
572 continue;
573 }
574 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
575 if !expected_names.iter().any(|expected| expected == name) {
576 continue;
577 }
578 if let Some(ref prev) = file {
579 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("duplicate codegen backends found\nfirst: {0}\nsecond: {1}\n",
prev.display(), path.display()))
})format!(
580 "duplicate codegen backends found\n\
581 first: {}\n\
582 second: {}\n\
583 ",
584 prev.display(),
585 path.display()
586 );
587 early_dcx.early_fatal(err);
588 }
589 file = Some(path.clone());
590 }
591
592 match file {
593 Some(ref s) => load_backend_from_dylib(early_dcx, s),
594 None => {
595 let err = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsupported builtin codegen backend `{0}`",
backend_name))
})format!("unsupported builtin codegen backend `{backend_name}`");
596 early_dcx.early_fatal(err);
597 }
598 }
599}
600
601fn multiple_output_types_to_stdout(
602 output_types: &OutputTypes,
603 single_output_file_is_stdout: bool,
604) -> bool {
605 use std::io::IsTerminal;
606 if std::io::stdout().is_terminal() {
607 let named_text_types = output_types
610 .iter()
611 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
612 .count();
613 let unnamed_text_types =
614 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
615 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
616 } else {
617 let named_types =
619 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
620 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
621 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
622 }
623}
624
625pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
626 if multiple_output_types_to_stdout(
627 &sess.opts.output_types,
628 sess.io.output_file == Some(OutFileName::Stdout),
629 ) {
630 sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
631 }
632
633 let crate_name =
634 sess.opts.crate_name.clone().or_else(|| {
635 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
636 });
637
638 let invocation_temp = sess
639 .opts
640 .incremental
641 .as_ref()
642 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
643
644 match sess.io.output_file {
645 None => {
646 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
650
651 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
653
654 OutputFilenames::new(
655 dirpath,
656 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
657 stem,
658 None,
659 sess.io.temps_dir.clone(),
660 invocation_temp,
661 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
662 sess.opts.cg.extra_filename.clone(),
663 sess.opts.output_types.clone(),
664 )
665 }
666
667 Some(ref out_file) => {
668 let unnamed_output_types =
669 sess.opts.output_types.values().filter(|a| a.is_none()).count();
670 let ofile = if unnamed_output_types > 1 {
671 sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
672 None
673 } else {
674 if !sess.opts.cg.extra_filename.is_empty() {
675 sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
676 }
677 Some(out_file.clone())
678 };
679 if sess.io.output_dir.is_some() {
680 sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
681 }
682
683 let out_filestem =
684 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
685 OutputFilenames::new(
686 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
687 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
688 out_filestem,
689 ofile,
690 sess.io.temps_dir.clone(),
691 invocation_temp,
692 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
693 sess.opts.cg.extra_filename.clone(),
694 sess.opts.output_types.clone(),
695 )
696 }
697 }
698}
699
700pub macro version_str() {
702 option_env!("CFG_VERSION")
703}
704
705pub fn rustc_version_str() -> Option<&'static str> {
707 ::core::option::Option::Some("1.99.0-nightly (c81c8c15f 2026-09-09) (Ferrocene nightly by Ferrous Systems)")version_str!()
708}