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