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),
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
381impl CodegenBackend for DummyCodegenBackend {
382 fn name(&self) -> &'static str {
383 "dummy"
384 }
385
386 fn target_config(&self, sess: &Session) -> TargetConfig {
387 let abi_required_features = sess.target.abi_required_features();
388 let internal_target_features = internal_target_features::<0>(
389 sess,
390 |_feature| Default::default(),
391 |feature| {
392 abi_required_features.required.contains(&feature)
397 },
398 );
399
400 TargetConfig {
401 internal_target_features,
402 has_reliable_f16: true,
403 has_reliable_f16_math: true,
404 has_reliable_f128: true,
405 has_reliable_f128_math: true,
406 }
407 }
408
409 fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
410 ::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]
415 }
416
417 fn target_cpu(&self, _sess: &Session) -> String {
418 String::new()
419 }
420
421 fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
422 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
423 }
424
425 fn join_codegen(
426 &self,
427 ongoing_codegen: Box<dyn Any>,
428 _sess: &Session,
429 _incr_comp_session: Option<&IncrCompSession>,
430 _outputs: &OutputFilenames,
431 _crate_info: &CrateInfo,
432 ) -> (CompiledModules, WorkProductMap) {
433 (*ongoing_codegen.downcast().unwrap(), WorkProductMap::default())
434 }
435
436 fn link(
437 &self,
438 sess: &Session,
439 compiled_modules: CompiledModules,
440 crate_info: CrateInfo,
441 metadata: EncodedMetadata,
442 outputs: &OutputFilenames,
443 ) {
444 #[allow(rustc::bad_opt_access)]
446 if let Some(&crate_type) =
447 crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
448 && outputs.outputs.should_link()
449 {
450 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!(
451 "crate type {crate_type} not supported by the dummy codegen backend"
452 ));
453 }
454
455 link_binary(
456 sess,
457 &DummyArchiveBuilderBuilder,
458 compiled_modules,
459 crate_info,
460 metadata,
461 outputs,
462 self.name(),
463 );
464 }
465}
466
467struct DummyArchiveBuilderBuilder;
468
469impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
470 fn new_archive_builder<'a>(
471 &self,
472 sess: &'a Session,
473 ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
474 ArArchiveBuilderBuilder.new_archive_builder(sess)
475 }
476
477 fn create_dll_import_lib(
478 &self,
479 sess: &Session,
480 _lib_name: &str,
481 _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
482 output_path: &Path,
483 ) {
484 ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
486 }
487}
488
489pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
493 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
494
495 RUSTC_PATH
496 .get_or_init(|| {
497 let candidate = sysroot
498 .default
499 .join("bin"env!("RUSTC_INSTALL_BINDIR"))
500 .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
501 candidate.exists().then_some(candidate)
502 })
503 .as_deref()
504}
505
506fn get_codegen_sysroot(
507 early_dcx: &EarlyDiagCtxt,
508 sysroot: &Sysroot,
509 backend_name: &str,
510) -> MakeBackendFn {
511 static LOADED: AtomicBool = AtomicBool::new(false);
517 if !!LOADED.fetch_or(true, Ordering::SeqCst) {
{
::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
}
};assert!(
518 !LOADED.fetch_or(true, Ordering::SeqCst),
519 "cannot load the default codegen backend twice"
520 );
521
522 let target = host_tuple();
523
524 let sysroot = sysroot
525 .all_paths()
526 .map(|sysroot| {
527 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
528 })
529 .find(|f| {
530 {
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:530",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(530u32),
::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());
531 f.exists()
532 })
533 .unwrap_or_else(|| {
534 let candidates = sysroot
535 .all_paths()
536 .map(|p| p.display().to_string())
537 .collect::<Vec<_>>()
538 .join("\n* ");
539 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!(
540 "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
541 * {candidates}"
542 );
543 early_dcx.early_fatal(err);
544 });
545
546 {
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:546",
"rustc_interface::util", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/util.rs"),
::tracing_core::__macro_support::Option::Some(546u32),
::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());
547
548 let d = sysroot.read_dir().unwrap_or_else(|e| {
549 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!(
550 "failed to load default codegen backend, couldn't read `{}`: {e}",
551 sysroot.display(),
552 );
553 early_dcx.early_fatal(err);
554 });
555
556 let mut file: Option<PathBuf> = None;
557
558 let expected_names = &[
559 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
backend_name, "1.100.0-nightly"))
})format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
560 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
})format!("rustc_codegen_{backend_name}"),
561 ];
562 for entry in d.filter_map(|e| e.ok()) {
563 let path = entry.path();
564 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
565 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
566 continue;
567 }
568 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
569 if !expected_names.iter().any(|expected| expected == name) {
570 continue;
571 }
572 if let Some(ref prev) = file {
573 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!(
574 "duplicate codegen backends found\n\
575 first: {}\n\
576 second: {}\n\
577 ",
578 prev.display(),
579 path.display()
580 );
581 early_dcx.early_fatal(err);
582 }
583 file = Some(path.clone());
584 }
585
586 match file {
587 Some(ref s) => load_backend_from_dylib(early_dcx, s),
588 None => {
589 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}`");
590 early_dcx.early_fatal(err);
591 }
592 }
593}
594
595fn multiple_output_types_to_stdout(
596 output_types: &OutputTypes,
597 single_output_file_is_stdout: bool,
598) -> bool {
599 use std::io::IsTerminal;
600 if std::io::stdout().is_terminal() {
601 let named_text_types = output_types
604 .iter()
605 .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
606 .count();
607 let unnamed_text_types =
608 output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
609 named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
610 } else {
611 let named_types =
613 output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
614 let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
615 named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
616 }
617}
618
619pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
620 if multiple_output_types_to_stdout(
621 &sess.opts.output_types,
622 sess.io.output_file == Some(OutFileName::Stdout),
623 ) {
624 sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
625 }
626
627 let crate_name =
628 sess.opts.crate_name.clone().or_else(|| {
629 parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
630 });
631
632 let invocation_temp = sess
633 .opts
634 .incremental
635 .as_ref()
636 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
637
638 match sess.io.output_file {
639 None => {
640 let dirpath = sess.io.output_dir.clone().unwrap_or_default();
644
645 let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
647
648 OutputFilenames::new(
649 dirpath,
650 crate_name.unwrap_or_else(|| stem.replace('-', "_")),
651 stem,
652 None,
653 sess.io.temps_dir.clone(),
654 invocation_temp,
655 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
656 sess.opts.cg.extra_filename.clone(),
657 sess.opts.output_types.clone(),
658 )
659 }
660
661 Some(ref out_file) => {
662 let unnamed_output_types =
663 sess.opts.output_types.values().filter(|a| a.is_none()).count();
664 let ofile = if unnamed_output_types > 1 {
665 sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
666 None
667 } else {
668 if !sess.opts.cg.extra_filename.is_empty() {
669 sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
670 }
671 Some(out_file.clone())
672 };
673 if sess.io.output_dir.is_some() {
674 sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
675 }
676
677 let out_filestem =
678 out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
679 OutputFilenames::new(
680 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
681 crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
682 out_filestem,
683 ofile,
684 sess.io.temps_dir.clone(),
685 invocation_temp,
686 sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
687 sess.opts.cg.extra_filename.clone(),
688 sess.opts.output_types.clone(),
689 )
690 }
691 }
692}
693
694pub macro version_str() {
696 option_env!("CFG_VERSION")
697}
698
699pub fn rustc_version_str() -> Option<&'static str> {
701 ::core::option::Option::Some("1.100.0-nightly (e71c0f1e3 2026-08-18)")version_str!()
702}