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