rustc_interface/
util.rs

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, validate_attr};
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::{CodegenResults, CrateInfo, TargetConfig};
15use rustc_data_structures::fx::FxIndexMap;
16use rustc_data_structures::jobserver::Proxy;
17use rustc_data_structures::sync;
18use rustc_errors::LintBuffer;
19use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
20use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
21use rustc_middle::ty::{CurrentGcx, TyCtxt};
22use rustc_session::config::{
23    Cfg, CrateType, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
24};
25use rustc_session::output::{CRATE_TYPES, categorize_crate_type};
26use rustc_session::{EarlyDiagCtxt, Session, filesearch, lint};
27use rustc_span::edit_distance::find_best_match_for_name;
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::errors;
35use crate::passes::parse_crate_name;
36
37/// Function pointer type that constructs a new CodegenBackend.
38type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
39
40/// Adds `target_feature = "..."` cfgs for a variety of platform
41/// specific features (SSE, NEON etc.).
42///
43/// This is performed by checking whether a set of permitted features
44/// is available on the target machine, by querying the codegen backend.
45pub(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    sess.unstable_target_features.extend(tf_cfg.unstable_target_features.iter().copied());
54    sess.target_features.extend(tf_cfg.target_features.iter().copied());
55
56    cfg.extend(tf_cfg.target_features.into_iter().map(|feat| (tf, Some(feat))));
57
58    if tf_cfg.has_reliable_f16 {
59        cfg.insert((sym::target_has_reliable_f16, None));
60    }
61    if tf_cfg.has_reliable_f16_math {
62        cfg.insert((sym::target_has_reliable_f16_math, None));
63    }
64    if tf_cfg.has_reliable_f128 {
65        cfg.insert((sym::target_has_reliable_f128, None));
66    }
67    if tf_cfg.has_reliable_f128_math {
68        cfg.insert((sym::target_has_reliable_f128_math, None));
69    }
70
71    if sess.crt_static(None) {
72        cfg.insert((tf, Some(sym::crt_dash_static)));
73    }
74}
75
76/// Ensures that all target features required by the ABI are present.
77/// Must be called after `unstable_target_features` has been populated!
78pub(crate) fn check_abi_required_features(sess: &Session) {
79    let abi_feature_constraints = sess.target.abi_required_features();
80    // We check this against `unstable_target_features` as that is conveniently already
81    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
82    // Just double-check that the features we care about are actually on our list.
83    for feature in
84        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
85    {
86        assert!(
87            sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
88            "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
89        );
90    }
91
92    for feature in abi_feature_constraints.required {
93        if !sess.unstable_target_features.contains(&Symbol::intern(feature)) {
94            sess.dcx().emit_warn(errors::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().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" });
100        }
101    }
102}
103
104pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
105pub const DEFAULT_STACK_SIZE: usize = 8 * 1024 * 1024;
106
107fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
108    // Obey the environment setting or default
109    *STACK_SIZE.get_or_init(|| {
110        env::var_os("RUST_MIN_STACK")
111            .as_ref()
112            .map(|os_str| os_str.to_string_lossy())
113            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
114            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
115            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
116            .filter(|s| !s.trim().is_empty())
117            // rustc is a batch program, so error early on inputs which are unlikely to be intended
118            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
119            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
120            .map(|s| {
121                let s = s.trim();
122                // FIXME(workingjubilee): add proper diagnostics when we factor out "pre-run" setup
123                #[allow(rustc::untranslatable_diagnostic, rustc::diagnostic_outside_of_impl)]
124                s.parse::<usize>().unwrap_or_else(|_| {
125                    let mut err = early_dcx.early_struct_fatal(format!(
126                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
127                    ));
128                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
129                    err.emit()
130                })
131            })
132            // otherwise pick a consistent default
133            .unwrap_or(DEFAULT_STACK_SIZE)
134    })
135}
136
137fn run_in_thread_with_globals<F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send, R: Send>(
138    thread_stack_size: usize,
139    edition: Edition,
140    sm_inputs: SourceMapInputs,
141    extra_symbols: &[&'static str],
142    f: F,
143) -> R {
144    // The "thread pool" is a single spawned thread in the non-parallel
145    // compiler. We run on a spawned thread instead of the main thread (a) to
146    // provide control over the stack size, and (b) to increase similarity with
147    // the parallel compiler, in particular to ensure there is no accidental
148    // sharing of data between the main thread and the compilation thread
149    // (which might cause problems for the parallel compiler).
150    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
151
152    // We build the session globals and run `f` on the spawned thread, because
153    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
154    thread::scope(|s| {
155        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
156        // name contains null bytes.
157        let r = builder
158            .spawn_scoped(s, move || {
159                rustc_span::create_session_globals_then(
160                    edition,
161                    extra_symbols,
162                    Some(sm_inputs),
163                    || f(CurrentGcx::new(), Proxy::new()),
164                )
165            })
166            .unwrap()
167            .join();
168
169        match r {
170            Ok(v) => v,
171            Err(e) => std::panic::resume_unwind(e),
172        }
173    })
174}
175
176pub(crate) fn run_in_thread_pool_with_globals<
177    F: FnOnce(CurrentGcx, Arc<Proxy>) -> R + Send,
178    R: Send,
179>(
180    thread_builder_diag: &EarlyDiagCtxt,
181    edition: Edition,
182    threads: usize,
183    extra_symbols: &[&'static str],
184    sm_inputs: SourceMapInputs,
185    f: F,
186) -> R {
187    use std::process;
188
189    use rustc_data_structures::defer;
190    use rustc_data_structures::sync::FromDyn;
191    use rustc_middle::ty::tls;
192    use rustc_query_impl::QueryCtxt;
193    use rustc_query_system::query::{QueryContext, break_query_cycles};
194
195    let thread_stack_size = init_stack_size(thread_builder_diag);
196
197    let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
198
199    if !sync::is_dyn_thread_safe() {
200        return run_in_thread_with_globals(
201            thread_stack_size,
202            edition,
203            sm_inputs,
204            extra_symbols,
205            |current_gcx, jobserver_proxy| {
206                // Register the thread for use with the `WorkerLocal` type.
207                registry.register();
208
209                f(current_gcx, jobserver_proxy)
210            },
211        );
212    }
213
214    let current_gcx = FromDyn::from(CurrentGcx::new());
215    let current_gcx2 = current_gcx.clone();
216
217    let proxy = Proxy::new();
218
219    let proxy_ = Arc::clone(&proxy);
220    let proxy__ = Arc::clone(&proxy);
221    let builder = rustc_thread_pool::ThreadPoolBuilder::new()
222        .thread_name(|_| "rustc".to_string())
223        .acquire_thread_handler(move || proxy_.acquire_thread())
224        .release_thread_handler(move || proxy__.release_thread())
225        .num_threads(threads)
226        .deadlock_handler(move || {
227            // On deadlock, creates a new thread and forwards information in thread
228            // locals to it. The new thread runs the deadlock handler.
229
230            let current_gcx2 = current_gcx2.clone();
231            let registry = rustc_thread_pool::Registry::current();
232            let session_globals = rustc_span::with_session_globals(|session_globals| {
233                session_globals as *const SessionGlobals as usize
234            });
235            thread::Builder::new()
236                .name("rustc query cycle handler".to_string())
237                .spawn(move || {
238                    let on_panic = defer(|| {
239                        eprintln!("internal compiler error: query cycle handler thread panicked, aborting process");
240                        // We need to abort here as we failed to resolve the deadlock,
241                        // otherwise the compiler could just hang,
242                        process::abort();
243                    });
244
245                    // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
246                    // `TyCtxt` TLS reference here.
247                    current_gcx2.access(|gcx| {
248                        tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
249                            tls::with(|tcx| {
250                                // Accessing session globals is sound as they outlive `GlobalCtxt`.
251                                // They are needed to hash query keys containing spans or symbols.
252                                let query_map = rustc_span::set_session_globals_then(unsafe { &*(session_globals as *const SessionGlobals) }, || {
253                                    // Ensure there was no errors collecting all active jobs.
254                                    // We need the complete map to ensure we find a cycle to break.
255                                    QueryCtxt::new(tcx).collect_active_jobs().expect("failed to collect active queries in deadlock handler")
256                                });
257                                break_query_cycles(query_map, &registry);
258                            })
259                        })
260                    });
261
262                    on_panic.disable();
263                })
264                .unwrap();
265        })
266        .stack_size(thread_stack_size);
267
268    // We create the session globals on the main thread, then create the thread
269    // pool. Upon creation, each worker thread created gets a copy of the
270    // session globals in TLS. This is possible because `SessionGlobals` impls
271    // `Send` in the parallel compiler.
272    rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
273        rustc_span::with_session_globals(|session_globals| {
274            let session_globals = FromDyn::from(session_globals);
275            builder
276                .build_scoped(
277                    // Initialize each new worker thread when created.
278                    move |thread: rustc_thread_pool::ThreadBuilder| {
279                        // Register the thread for use with the `WorkerLocal` type.
280                        registry.register();
281
282                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
283                            thread.run()
284                        })
285                    },
286                    // Run `f` on the first thread in the thread pool.
287                    move |pool: &rustc_thread_pool::ThreadPool| {
288                        pool.install(|| f(current_gcx.into_inner(), proxy))
289                    },
290                )
291                .unwrap_or_else(|err| {
292                    let mut diag = thread_builder_diag.early_struct_fatal(format!(
293                        "failed to spawn compiler thread pool: could not create {threads} threads ({err})",
294                    ));
295                    diag.help(
296                        "try lowering `-Z threads` or checking the operating system's resource limits",
297                    );
298                    diag.emit();
299                })
300        })
301    })
302}
303
304#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
305fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
306    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
307        Ok(backend_sym) => backend_sym,
308        Err(DylibError::DlOpen(path, err)) => {
309            let err = format!("couldn't load codegen backend {path}{err}");
310            early_dcx.early_fatal(err);
311        }
312        Err(DylibError::DlSym(_path, err)) => {
313            let e = format!(
314                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
315            );
316            early_dcx.early_fatal(e);
317        }
318    }
319}
320
321/// Get the codegen backend based on the name and specified sysroot.
322///
323/// A name of `None` indicates that the default backend should be used.
324pub fn get_codegen_backend(
325    early_dcx: &EarlyDiagCtxt,
326    sysroot: &Sysroot,
327    backend_name: Option<&str>,
328    target: &Target,
329) -> Box<dyn CodegenBackend> {
330    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
331
332    let load = LOAD.get_or_init(|| {
333        let backend = backend_name
334            .or(target.default_codegen_backend.as_deref())
335            .or(option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
336            .unwrap_or("dummy");
337
338        match backend {
339            filename if filename.contains('.') => {
340                load_backend_from_dylib(early_dcx, filename.as_ref())
341            }
342            "dummy" => || Box::new(DummyCodegenBackend),
343            #[cfg(feature = "llvm")]
344            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
345            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
346        }
347    });
348
349    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
350    // backend we hope that the backend links against the same rustc_driver version. If this is not
351    // the case, we get UB.
352    unsafe { load() }
353}
354
355struct DummyCodegenBackend;
356
357impl CodegenBackend for DummyCodegenBackend {
358    fn locale_resource(&self) -> &'static str {
359        ""
360    }
361
362    fn name(&self) -> &'static str {
363        "dummy"
364    }
365
366    fn target_config(&self, sess: &Session) -> TargetConfig {
367        let (target_features, unstable_target_features) = cfg_target_feature::<0>(
368            sess,
369            |_feature| Default::default(),
370            |feature| {
371                // This is a standin for the list of features a backend is expected to enable.
372                // It would be better to parse target.features instead and handle implied features,
373                // but target.features is a list of LLVM target features, not Rust target features.
374                // The dummy backend doesn't know the mapping between LLVM and Rust target features.
375                sess.target.abi_required_features().required.contains(&feature)
376            },
377        );
378
379        TargetConfig {
380            target_features,
381            unstable_target_features,
382            has_reliable_f16: true,
383            has_reliable_f16_math: true,
384            has_reliable_f128: true,
385            has_reliable_f128_math: true,
386        }
387    }
388
389    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
390        // This includes bin despite failing on the link step to ensure that you
391        // can still get the frontend handling for binaries. For all library
392        // like crate types cargo will fallback to rlib unless you specifically
393        // say that only a different crate type must be used.
394        vec![CrateType::Rlib, CrateType::Executable]
395    }
396
397    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
398        Box::new(CodegenResults {
399            modules: vec![],
400            allocator_module: None,
401            crate_info: CrateInfo::new(tcx, String::new()),
402        })
403    }
404
405    fn join_codegen(
406        &self,
407        ongoing_codegen: Box<dyn Any>,
408        _sess: &Session,
409        _outputs: &OutputFilenames,
410    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
411        (*ongoing_codegen.downcast().unwrap(), FxIndexMap::default())
412    }
413
414    fn link(
415        &self,
416        sess: &Session,
417        codegen_results: CodegenResults,
418        metadata: EncodedMetadata,
419        outputs: &OutputFilenames,
420    ) {
421        // JUSTIFICATION: TyCtxt no longer available here
422        #[allow(rustc::bad_opt_access)]
423        if let Some(&crate_type) = codegen_results
424            .crate_info
425            .crate_types
426            .iter()
427            .find(|&&crate_type| crate_type != CrateType::Rlib)
428            && outputs.outputs.should_link()
429        {
430            #[allow(rustc::untranslatable_diagnostic)]
431            #[allow(rustc::diagnostic_outside_of_impl)]
432            sess.dcx().fatal(format!(
433                "crate type {crate_type} not supported by the dummy codegen backend"
434            ));
435        }
436
437        link_binary(
438            sess,
439            &DummyArchiveBuilderBuilder,
440            codegen_results,
441            metadata,
442            outputs,
443            self.name(),
444        );
445    }
446}
447
448struct DummyArchiveBuilderBuilder;
449
450impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
451    fn new_archive_builder<'a>(
452        &self,
453        sess: &'a Session,
454    ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
455        ArArchiveBuilderBuilder.new_archive_builder(sess)
456    }
457
458    fn create_dll_import_lib(
459        &self,
460        sess: &Session,
461        _lib_name: &str,
462        _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
463        output_path: &Path,
464    ) {
465        // Build an empty static library to avoid calling an external dlltool on mingw
466        ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path);
467    }
468}
469
470// This is used for rustdoc, but it uses similar machinery to codegen backend
471// loading, so we leave the code here. It is potentially useful for other tools
472// that want to invoke the rustc binary while linking to rustc as well.
473pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
474    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
475
476    RUSTC_PATH
477        .get_or_init(|| {
478            let candidate = sysroot
479                .default
480                .join(env!("RUSTC_INSTALL_BINDIR"))
481                .join(if cfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
482            candidate.exists().then_some(candidate)
483        })
484        .as_deref()
485}
486
487#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
488fn get_codegen_sysroot(
489    early_dcx: &EarlyDiagCtxt,
490    sysroot: &Sysroot,
491    backend_name: &str,
492) -> MakeBackendFn {
493    // For now we only allow this function to be called once as it'll dlopen a
494    // few things, which seems to work best if we only do that once. In
495    // general this assertion never trips due to the once guard in `get_codegen_backend`,
496    // but there's a few manual calls to this function in this file we protect
497    // against.
498    static LOADED: AtomicBool = AtomicBool::new(false);
499    assert!(
500        !LOADED.fetch_or(true, Ordering::SeqCst),
501        "cannot load the default codegen backend twice"
502    );
503
504    let target = host_tuple();
505
506    let sysroot = sysroot
507        .all_paths()
508        .map(|sysroot| {
509            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
510        })
511        .find(|f| {
512            info!("codegen backend candidate: {}", f.display());
513            f.exists()
514        })
515        .unwrap_or_else(|| {
516            let candidates = sysroot
517                .all_paths()
518                .map(|p| p.display().to_string())
519                .collect::<Vec<_>>()
520                .join("\n* ");
521            let err = format!(
522                "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
523                 * {candidates}"
524            );
525            early_dcx.early_fatal(err);
526        });
527
528    info!("probing {} for a codegen backend", sysroot.display());
529
530    let d = sysroot.read_dir().unwrap_or_else(|e| {
531        let err = format!(
532            "failed to load default codegen backend, couldn't read `{}`: {e}",
533            sysroot.display(),
534        );
535        early_dcx.early_fatal(err);
536    });
537
538    let mut file: Option<PathBuf> = None;
539
540    let expected_names = &[
541        format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
542        format!("rustc_codegen_{backend_name}"),
543    ];
544    for entry in d.filter_map(|e| e.ok()) {
545        let path = entry.path();
546        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
547        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
548            continue;
549        }
550        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
551        if !expected_names.iter().any(|expected| expected == name) {
552            continue;
553        }
554        if let Some(ref prev) = file {
555            let err = format!(
556                "duplicate codegen backends found\n\
557                               first:  {}\n\
558                               second: {}\n\
559            ",
560                prev.display(),
561                path.display()
562            );
563            early_dcx.early_fatal(err);
564        }
565        file = Some(path.clone());
566    }
567
568    match file {
569        Some(ref s) => load_backend_from_dylib(early_dcx, s),
570        None => {
571            let err = format!("unsupported builtin codegen backend `{backend_name}`");
572            early_dcx.early_fatal(err);
573        }
574    }
575}
576
577pub(crate) fn check_attr_crate_type(
578    sess: &Session,
579    attrs: &[ast::Attribute],
580    lint_buffer: &mut LintBuffer,
581) {
582    // Unconditionally collect crate types from attributes to make them used
583    for a in attrs.iter() {
584        if a.has_name(sym::crate_type) {
585            if let Some(n) = a.value_str() {
586                if categorize_crate_type(n).is_some() {
587                    return;
588                }
589
590                if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
591                    let span = spanned.span;
592                    let candidate = find_best_match_for_name(
593                        &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
594                        n,
595                        None,
596                    );
597                    lint_buffer.buffer_lint(
598                        lint::builtin::UNKNOWN_CRATE_TYPES,
599                        ast::CRATE_NODE_ID,
600                        span,
601                        errors::UnknownCrateTypes {
602                            sugg: candidate
603                                .map(|cand| errors::UnknownCrateTypesSub { span, snippet: cand }),
604                        },
605                    );
606                }
607            } else {
608                // This is here mainly to check for using a macro, such as
609                // `#![crate_type = foo!()]`. That is not supported since the
610                // crate type needs to be known very early in compilation long
611                // before expansion. Otherwise, validation would normally be
612                // caught during semantic analysis via `TyCtxt::check_mod_attrs`,
613                // but by the time that runs the macro is expanded, and it doesn't
614                // give an error.
615                validate_attr::emit_fatal_malformed_builtin_attribute(
616                    &sess.psess,
617                    a,
618                    sym::crate_type,
619                );
620            }
621        }
622    }
623}
624
625fn multiple_output_types_to_stdout(
626    output_types: &OutputTypes,
627    single_output_file_is_stdout: bool,
628) -> bool {
629    use std::io::IsTerminal;
630    if std::io::stdout().is_terminal() {
631        // If stdout is a tty, check if multiple text output types are
632        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
633        let named_text_types = output_types
634            .iter()
635            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
636            .count();
637        let unnamed_text_types =
638            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
639        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
640    } else {
641        // Otherwise, all the output types should be checked
642        let named_types =
643            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
644        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
645        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
646    }
647}
648
649pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
650    if multiple_output_types_to_stdout(
651        &sess.opts.output_types,
652        sess.io.output_file == Some(OutFileName::Stdout),
653    ) {
654        sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout);
655    }
656
657    let crate_name =
658        sess.opts.crate_name.clone().or_else(|| {
659            parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
660        });
661
662    match sess.io.output_file {
663        None => {
664            // "-" as input file will cause the parser to read from stdin so we
665            // have to make up a name
666            // We want to toss everything after the final '.'
667            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
668
669            // If a crate name is present, we use it as the link name
670            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
671
672            OutputFilenames::new(
673                dirpath,
674                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
675                stem,
676                None,
677                sess.io.temps_dir.clone(),
678                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
679                sess.opts.cg.extra_filename.clone(),
680                sess.opts.output_types.clone(),
681            )
682        }
683
684        Some(ref out_file) => {
685            let unnamed_output_types =
686                sess.opts.output_types.values().filter(|a| a.is_none()).count();
687            let ofile = if unnamed_output_types > 1 {
688                sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption);
689                None
690            } else {
691                if !sess.opts.cg.extra_filename.is_empty() {
692                    sess.dcx().emit_warn(errors::IgnoringExtraFilename);
693                }
694                Some(out_file.clone())
695            };
696            if sess.io.output_dir.is_some() {
697                sess.dcx().emit_warn(errors::IgnoringOutDir);
698            }
699
700            let out_filestem =
701                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
702            OutputFilenames::new(
703                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
704                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
705                out_filestem,
706                ofile,
707                sess.io.temps_dir.clone(),
708                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
709                sess.opts.cg.extra_filename.clone(),
710                sess.opts.output_types.clone(),
711            )
712        }
713    }
714}
715
716/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
717pub macro version_str() {
718    option_env!("CFG_VERSION")
719}
720
721/// Returns the version string for `rustc` itself (which may be different from a tool version).
722pub fn rustc_version_str() -> Option<&'static str> {
723    version_str!()
724}