]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/util.rs
Remove io::LocalOutput and use Arc<Mutex<dyn>> for local streams.
[rust.git] / compiler / rustc_interface / src / util.rs
1 use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *};
2 use rustc_ast::ptr::P;
3 use rustc_ast::util::lev_distance::find_best_match_for_name;
4 use rustc_ast::{self as ast, AttrVec, BlockCheckMode};
5 use rustc_codegen_ssa::traits::CodegenBackend;
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 #[cfg(parallel_compiler)]
9 use rustc_data_structures::jobserver;
10 use rustc_data_structures::stable_hasher::StableHasher;
11 use rustc_data_structures::sync::Lrc;
12 use rustc_errors::registry::Registry;
13 use rustc_metadata::dynamic_lib::DynamicLibrary;
14 use rustc_resolve::{self, Resolver};
15 use rustc_session as session;
16 use rustc_session::config::{self, CrateType};
17 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
18 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
19 use rustc_session::parse::CrateConfig;
20 use rustc_session::CrateDisambiguator;
21 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
22 use rustc_span::edition::Edition;
23 use rustc_span::source_map::FileLoader;
24 use rustc_span::symbol::{sym, Symbol};
25 use smallvec::SmallVec;
26 use std::env;
27 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
28 use std::io;
29 use std::lazy::SyncOnceCell;
30 use std::mem;
31 use std::ops::DerefMut;
32 use std::path::{Path, PathBuf};
33 use std::sync::atomic::{AtomicBool, Ordering};
34 use std::sync::{Arc, Mutex, Once};
35 #[cfg(not(parallel_compiler))]
36 use std::{panic, thread};
37 use tracing::info;
38
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
41 ///
42 /// This is performed by checking whether a set of permitted features
43 /// is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45     cfg: &mut CrateConfig,
46     sess: &mut Session,
47     codegen_backend: &dyn CodegenBackend,
48 ) {
49     let tf = sym::target_feature;
50
51     let target_features = codegen_backend.target_features(sess);
52     sess.target_features.extend(target_features.iter().cloned());
53
54     cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
55
56     if sess.crt_static(None) {
57         cfg.insert((tf, Some(sym::crt_dash_static)));
58     }
59 }
60
61 pub fn create_session(
62     sopts: config::Options,
63     cfg: FxHashSet<(String, Option<String>)>,
64     diagnostic_output: DiagnosticOutput,
65     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
66     input_path: Option<PathBuf>,
67     lint_caps: FxHashMap<lint::LintId, lint::Level>,
68     make_codegen_backend: Option<
69         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
70     >,
71     descriptions: Registry,
72 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
73     let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
74         make_codegen_backend(&sopts)
75     } else {
76         get_codegen_backend(&sopts)
77     };
78
79     // target_override is documented to be called before init(), so this is okay
80     let target_override = codegen_backend.target_override(&sopts);
81
82     let mut sess = session::build_session(
83         sopts,
84         input_path,
85         descriptions,
86         diagnostic_output,
87         lint_caps,
88         file_loader,
89         target_override,
90     );
91
92     codegen_backend.init(&sess);
93
94     let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
95     add_configuration(&mut cfg, &mut sess, &*codegen_backend);
96     sess.parse_sess.config = cfg;
97
98     (Lrc::new(sess), Lrc::new(codegen_backend))
99 }
100
101 const STACK_SIZE: usize = 8 * 1024 * 1024;
102
103 fn get_stack_size() -> Option<usize> {
104     // FIXME: Hacks on hacks. If the env is trying to override the stack size
105     // then *don't* set it explicitly.
106     env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
107 }
108
109 /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need
110 /// for `'static` bounds.
111 #[cfg(not(parallel_compiler))]
112 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
113     struct Ptr(*mut ());
114     unsafe impl Send for Ptr {}
115     unsafe impl Sync for Ptr {}
116
117     let mut f = Some(f);
118     let run = Ptr(&mut f as *mut _ as *mut ());
119     let mut result = None;
120     let result_ptr = Ptr(&mut result as *mut _ as *mut ());
121
122     let thread = cfg.spawn(move || {
123         let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
124         let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
125         *result = Some(run());
126     });
127
128     match thread.unwrap().join() {
129         Ok(()) => result.unwrap(),
130         Err(p) => panic::resume_unwind(p),
131     }
132 }
133
134 #[cfg(not(parallel_compiler))]
135 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
136     edition: Edition,
137     _threads: usize,
138     stderr: &Option<Arc<Mutex<Vec<u8>>>>,
139     f: F,
140 ) -> R {
141     let mut cfg = thread::Builder::new().name("rustc".to_string());
142
143     if let Some(size) = get_stack_size() {
144         cfg = cfg.stack_size(size);
145     }
146
147     crate::callbacks::setup_callbacks();
148
149     let main_handler = move || {
150         rustc_span::with_session_globals(edition, || {
151             if let Some(stderr) = stderr {
152                 io::set_panic(Some(stderr.clone()));
153             }
154             f()
155         })
156     };
157
158     scoped_thread(cfg, main_handler)
159 }
160
161 #[cfg(parallel_compiler)]
162 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
163     edition: Edition,
164     threads: usize,
165     stderr: &Option<Arc<Mutex<Vec<u8>>>>,
166     f: F,
167 ) -> R {
168     use rustc_middle::ty;
169     crate::callbacks::setup_callbacks();
170
171     let mut config = rayon::ThreadPoolBuilder::new()
172         .thread_name(|_| "rustc".to_string())
173         .acquire_thread_handler(jobserver::acquire_thread)
174         .release_thread_handler(jobserver::release_thread)
175         .num_threads(threads)
176         .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
177
178     if let Some(size) = get_stack_size() {
179         config = config.stack_size(size);
180     }
181
182     let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
183
184     rustc_span::with_session_globals(edition, || {
185         rustc_span::SESSION_GLOBALS.with(|session_globals| {
186             // The main handler runs for each Rayon worker thread and sets up
187             // the thread local rustc uses. `session_globals` is captured and set
188             // on the new threads.
189             let main_handler = move |thread: rayon::ThreadBuilder| {
190                 rustc_span::SESSION_GLOBALS.set(session_globals, || {
191                     if let Some(stderr) = stderr {
192                         io::set_panic(Some(stderr.clone()));
193                     }
194                     thread.run()
195                 })
196             };
197
198             config.build_scoped(main_handler, with_pool).unwrap()
199         })
200     })
201 }
202
203 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
204     let lib = DynamicLibrary::open(path).unwrap_or_else(|err| {
205         let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
206         early_error(ErrorOutputType::default(), &err);
207     });
208     unsafe {
209         match lib.symbol("__rustc_codegen_backend") {
210             Ok(f) => {
211                 mem::forget(lib);
212                 mem::transmute::<*mut u8, _>(f)
213             }
214             Err(e) => {
215                 let err = format!(
216                     "couldn't load codegen backend as it \
217                                    doesn't export the `__rustc_codegen_backend` \
218                                    symbol: {:?}",
219                     e
220                 );
221                 early_error(ErrorOutputType::default(), &err);
222             }
223         }
224     }
225 }
226
227 pub fn get_codegen_backend(sopts: &config::Options) -> Box<dyn CodegenBackend> {
228     static INIT: Once = Once::new();
229
230     static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
231
232     INIT.call_once(|| {
233         #[cfg(feature = "llvm")]
234         const DEFAULT_CODEGEN_BACKEND: &str = "llvm";
235
236         #[cfg(not(feature = "llvm"))]
237         const DEFAULT_CODEGEN_BACKEND: &str = "cranelift";
238
239         let codegen_name = sopts
240             .debugging_opts
241             .codegen_backend
242             .as_ref()
243             .map(|name| &name[..])
244             .unwrap_or(DEFAULT_CODEGEN_BACKEND);
245
246         let backend = match codegen_name {
247             filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
248             codegen_name => get_builtin_codegen_backend(codegen_name),
249         };
250
251         unsafe {
252             LOAD = backend;
253         }
254     });
255     unsafe { LOAD() }
256 }
257
258 // This is used for rustdoc, but it uses similar machinery to codegen backend
259 // loading, so we leave the code here. It is potentially useful for other tools
260 // that want to invoke the rustc binary while linking to rustc as well.
261 pub fn rustc_path<'a>() -> Option<&'a Path> {
262     static RUSTC_PATH: SyncOnceCell<Option<PathBuf>> = SyncOnceCell::new();
263
264     const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
265
266     RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
267 }
268
269 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
270     sysroot_candidates().iter().find_map(|sysroot| {
271         let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
272             "rustc.exe"
273         } else {
274             "rustc"
275         });
276         candidate.exists().then_some(candidate)
277     })
278 }
279
280 fn sysroot_candidates() -> Vec<PathBuf> {
281     let target = session::config::host_triple();
282     let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
283     let path = current_dll_path().and_then(|s| s.canonicalize().ok());
284     if let Some(dll) = path {
285         // use `parent` twice to chop off the file name and then also the
286         // directory containing the dll which should be either `lib` or `bin`.
287         if let Some(path) = dll.parent().and_then(|p| p.parent()) {
288             // The original `path` pointed at the `rustc_driver` crate's dll.
289             // Now that dll should only be in one of two locations. The first is
290             // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
291             // other is the target's libdir, for example
292             // `$sysroot/lib/rustlib/$target/lib/*.dll`.
293             //
294             // We don't know which, so let's assume that if our `path` above
295             // ends in `$target` we *could* be in the target libdir, and always
296             // assume that we may be in the main libdir.
297             sysroot_candidates.push(path.to_owned());
298
299             if path.ends_with(target) {
300                 sysroot_candidates.extend(
301                     path.parent() // chop off `$target`
302                         .and_then(|p| p.parent()) // chop off `rustlib`
303                         .and_then(|p| p.parent()) // chop off `lib`
304                         .map(|s| s.to_owned()),
305                 );
306             }
307         }
308     }
309
310     return sysroot_candidates;
311
312     #[cfg(unix)]
313     fn current_dll_path() -> Option<PathBuf> {
314         use std::ffi::{CStr, OsStr};
315         use std::os::unix::prelude::*;
316
317         unsafe {
318             let addr = current_dll_path as usize as *mut _;
319             let mut info = mem::zeroed();
320             if libc::dladdr(addr, &mut info) == 0 {
321                 info!("dladdr failed");
322                 return None;
323             }
324             if info.dli_fname.is_null() {
325                 info!("dladdr returned null pointer");
326                 return None;
327             }
328             let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
329             let os = OsStr::from_bytes(bytes);
330             Some(PathBuf::from(os))
331         }
332     }
333
334     #[cfg(windows)]
335     fn current_dll_path() -> Option<PathBuf> {
336         use std::ffi::OsString;
337         use std::os::windows::prelude::*;
338         use std::ptr;
339
340         use winapi::um::libloaderapi::{
341             GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
342         };
343
344         unsafe {
345             let mut module = ptr::null_mut();
346             let r = GetModuleHandleExW(
347                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
348                 current_dll_path as usize as *mut _,
349                 &mut module,
350             );
351             if r == 0 {
352                 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
353                 return None;
354             }
355             let mut space = Vec::with_capacity(1024);
356             let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
357             if r == 0 {
358                 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
359                 return None;
360             }
361             let r = r as usize;
362             if r >= space.capacity() {
363                 info!("our buffer was too small? {}", io::Error::last_os_error());
364                 return None;
365             }
366             space.set_len(r);
367             let os = OsString::from_wide(&space);
368             Some(PathBuf::from(os))
369         }
370     }
371 }
372
373 pub fn get_builtin_codegen_backend(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
374     match backend_name {
375         #[cfg(feature = "llvm")]
376         "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
377         _ => get_codegen_sysroot(backend_name),
378     }
379 }
380
381 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
382     // For now we only allow this function to be called once as it'll dlopen a
383     // few things, which seems to work best if we only do that once. In
384     // general this assertion never trips due to the once guard in `get_codegen_backend`,
385     // but there's a few manual calls to this function in this file we protect
386     // against.
387     static LOADED: AtomicBool = AtomicBool::new(false);
388     assert!(
389         !LOADED.fetch_or(true, Ordering::SeqCst),
390         "cannot load the default codegen backend twice"
391     );
392
393     let target = session::config::host_triple();
394     let sysroot_candidates = sysroot_candidates();
395
396     let sysroot = sysroot_candidates
397         .iter()
398         .map(|sysroot| {
399             let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
400             sysroot.join(libdir).with_file_name("codegen-backends")
401         })
402         .find(|f| {
403             info!("codegen backend candidate: {}", f.display());
404             f.exists()
405         });
406     let sysroot = sysroot.unwrap_or_else(|| {
407         let candidates = sysroot_candidates
408             .iter()
409             .map(|p| p.display().to_string())
410             .collect::<Vec<_>>()
411             .join("\n* ");
412         let err = format!(
413             "failed to find a `codegen-backends` folder \
414                            in the sysroot candidates:\n* {}",
415             candidates
416         );
417         early_error(ErrorOutputType::default(), &err);
418     });
419     info!("probing {} for a codegen backend", sysroot.display());
420
421     let d = sysroot.read_dir().unwrap_or_else(|e| {
422         let err = format!(
423             "failed to load default codegen backend, couldn't \
424                            read `{}`: {}",
425             sysroot.display(),
426             e
427         );
428         early_error(ErrorOutputType::default(), &err);
429     });
430
431     let mut file: Option<PathBuf> = None;
432
433     let expected_name =
434         format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE"));
435     for entry in d.filter_map(|e| e.ok()) {
436         let path = entry.path();
437         let filename = match path.file_name().and_then(|s| s.to_str()) {
438             Some(s) => s,
439             None => continue,
440         };
441         if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
442             continue;
443         }
444         let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
445         if name != expected_name {
446             continue;
447         }
448         if let Some(ref prev) = file {
449             let err = format!(
450                 "duplicate codegen backends found\n\
451                                first:  {}\n\
452                                second: {}\n\
453             ",
454                 prev.display(),
455                 path.display()
456             );
457             early_error(ErrorOutputType::default(), &err);
458         }
459         file = Some(path.clone());
460     }
461
462     match file {
463         Some(ref s) => load_backend_from_dylib(s),
464         None => {
465             let err = format!("unsupported builtin codegen backend `{}`", backend_name);
466             early_error(ErrorOutputType::default(), &err);
467         }
468     }
469 }
470
471 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
472     use std::hash::Hasher;
473
474     // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
475     // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
476     // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
477     // should still be safe enough to avoid collisions in practice.
478     let mut hasher = StableHasher::new();
479
480     let mut metadata = session.opts.cg.metadata.clone();
481     // We don't want the crate_disambiguator to dependent on the order
482     // -C metadata arguments, so sort them:
483     metadata.sort();
484     // Every distinct -C metadata value is only incorporated once:
485     metadata.dedup();
486
487     hasher.write(b"metadata");
488     for s in &metadata {
489         // Also incorporate the length of a metadata string, so that we generate
490         // different values for `-Cmetadata=ab -Cmetadata=c` and
491         // `-Cmetadata=a -Cmetadata=bc`
492         hasher.write_usize(s.len());
493         hasher.write(s.as_bytes());
494     }
495
496     // Also incorporate crate type, so that we don't get symbol conflicts when
497     // linking against a library of the same name, if this is an executable.
498     let is_exe = session.crate_types().contains(&CrateType::Executable);
499     hasher.write(if is_exe { b"exe" } else { b"lib" });
500
501     CrateDisambiguator::from(hasher.finish::<Fingerprint>())
502 }
503
504 pub(crate) fn check_attr_crate_type(
505     sess: &Session,
506     attrs: &[ast::Attribute],
507     lint_buffer: &mut LintBuffer,
508 ) {
509     // Unconditionally collect crate types from attributes to make them used
510     for a in attrs.iter() {
511         if sess.check_name(a, sym::crate_type) {
512             if let Some(n) = a.value_str() {
513                 if categorize_crate_type(n).is_some() {
514                     return;
515                 }
516
517                 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
518                     let span = spanned.span;
519                     let lev_candidate =
520                         find_best_match_for_name(CRATE_TYPES.iter().map(|(k, _)| k), n, None);
521                     if let Some(candidate) = lev_candidate {
522                         lint_buffer.buffer_lint_with_diagnostic(
523                             lint::builtin::UNKNOWN_CRATE_TYPES,
524                             ast::CRATE_NODE_ID,
525                             span,
526                             "invalid `crate_type` value",
527                             BuiltinLintDiagnostics::UnknownCrateTypes(
528                                 span,
529                                 "did you mean".to_string(),
530                                 format!("\"{}\"", candidate),
531                             ),
532                         );
533                     } else {
534                         lint_buffer.buffer_lint(
535                             lint::builtin::UNKNOWN_CRATE_TYPES,
536                             ast::CRATE_NODE_ID,
537                             span,
538                             "invalid `crate_type` value",
539                         );
540                     }
541                 }
542             }
543         }
544     }
545 }
546
547 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
548     (sym::rlib, CrateType::Rlib),
549     (sym::dylib, CrateType::Dylib),
550     (sym::cdylib, CrateType::Cdylib),
551     (sym::lib, config::default_lib_output()),
552     (sym::staticlib, CrateType::Staticlib),
553     (sym::proc_dash_macro, CrateType::ProcMacro),
554     (sym::bin, CrateType::Executable),
555 ];
556
557 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
558     Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
559 }
560
561 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
562     // Unconditionally collect crate types from attributes to make them used
563     let attr_types: Vec<CrateType> = attrs
564         .iter()
565         .filter_map(|a| {
566             if session.check_name(a, sym::crate_type) {
567                 match a.value_str() {
568                     Some(s) => categorize_crate_type(s),
569                     _ => None,
570                 }
571             } else {
572                 None
573             }
574         })
575         .collect();
576
577     // If we're generating a test executable, then ignore all other output
578     // styles at all other locations
579     if session.opts.test {
580         return vec![CrateType::Executable];
581     }
582
583     // Only check command line flags if present. If no types are specified by
584     // command line, then reuse the empty `base` Vec to hold the types that
585     // will be found in crate attributes.
586     let mut base = session.opts.crate_types.clone();
587     if base.is_empty() {
588         base.extend(attr_types);
589         if base.is_empty() {
590             base.push(output::default_output_for_target(session));
591         } else {
592             base.sort();
593             base.dedup();
594         }
595     }
596
597     base.retain(|crate_type| {
598         let res = !output::invalid_output_for_target(session, *crate_type);
599
600         if !res {
601             session.warn(&format!(
602                 "dropping unsupported crate type `{}` for target `{}`",
603                 *crate_type, session.opts.target_triple
604             ));
605         }
606
607         res
608     });
609
610     base
611 }
612
613 pub fn build_output_filenames(
614     input: &Input,
615     odir: &Option<PathBuf>,
616     ofile: &Option<PathBuf>,
617     attrs: &[ast::Attribute],
618     sess: &Session,
619 ) -> OutputFilenames {
620     match *ofile {
621         None => {
622             // "-" as input file will cause the parser to read from stdin so we
623             // have to make up a name
624             // We want to toss everything after the final '.'
625             let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
626
627             // If a crate name is present, we use it as the link name
628             let stem = sess
629                 .opts
630                 .crate_name
631                 .clone()
632                 .or_else(|| rustc_attr::find_crate_name(&sess, attrs).map(|n| n.to_string()))
633                 .unwrap_or_else(|| input.filestem().to_owned());
634
635             OutputFilenames::new(
636                 dirpath,
637                 stem,
638                 None,
639                 sess.opts.cg.extra_filename.clone(),
640                 sess.opts.output_types.clone(),
641             )
642         }
643
644         Some(ref out_file) => {
645             let unnamed_output_types =
646                 sess.opts.output_types.values().filter(|a| a.is_none()).count();
647             let ofile = if unnamed_output_types > 1 {
648                 sess.warn(
649                     "due to multiple output types requested, the explicitly specified \
650                      output file name will be adapted for each output type",
651                 );
652                 None
653             } else {
654                 if !sess.opts.cg.extra_filename.is_empty() {
655                     sess.warn("ignoring -C extra-filename flag due to -o flag");
656                 }
657                 Some(out_file.clone())
658             };
659             if *odir != None {
660                 sess.warn("ignoring --out-dir flag due to -o flag");
661             }
662
663             OutputFilenames::new(
664                 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
665                 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
666                 ofile,
667                 sess.opts.cg.extra_filename.clone(),
668                 sess.opts.output_types.clone(),
669             )
670         }
671     }
672 }
673
674 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
675 //
676 // FIXME: Currently the `everybody_loops` transformation is not applied to:
677 //  * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
678 //    waiting for miri to fix that.
679 //  * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
680 //    Solving this may require `!` to implement every trait, which relies on the an even more
681 //    ambitious form of the closed RFC #1637. See also [#34511].
682 //
683 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
684 pub struct ReplaceBodyWithLoop<'a, 'b> {
685     within_static_or_const: bool,
686     nested_blocks: Option<Vec<ast::Block>>,
687     resolver: &'a mut Resolver<'b>,
688 }
689
690 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
691     pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
692         ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver }
693     }
694
695     fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
696         let old_const = mem::replace(&mut self.within_static_or_const, is_const);
697         let old_blocks = self.nested_blocks.take();
698         let ret = action(self);
699         self.within_static_or_const = old_const;
700         self.nested_blocks = old_blocks;
701         ret
702     }
703
704     fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
705         if let ast::FnRetTy::Ty(ref ty) = ret_ty {
706             fn involves_impl_trait(ty: &ast::Ty) -> bool {
707                 match ty.kind {
708                     ast::TyKind::ImplTrait(..) => true,
709                     ast::TyKind::Slice(ref subty)
710                     | ast::TyKind::Array(ref subty, _)
711                     | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. })
712                     | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. })
713                     | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
714                     ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
715                     ast::TyKind::Path(_, ref path) => {
716                         path.segments.iter().any(|seg| match seg.args.as_deref() {
717                             None => false,
718                             Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
719                                 data.args.iter().any(|arg| match arg {
720                                     ast::AngleBracketedArg::Arg(arg) => match arg {
721                                         ast::GenericArg::Type(ty) => involves_impl_trait(ty),
722                                         ast::GenericArg::Lifetime(_)
723                                         | ast::GenericArg::Const(_) => false,
724                                     },
725                                     ast::AngleBracketedArg::Constraint(c) => match c.kind {
726                                         ast::AssocTyConstraintKind::Bound { .. } => true,
727                                         ast::AssocTyConstraintKind::Equality { ref ty } => {
728                                             involves_impl_trait(ty)
729                                         }
730                                     },
731                                 })
732                             }
733                             Some(&ast::GenericArgs::Parenthesized(ref data)) => {
734                                 any_involves_impl_trait(data.inputs.iter())
735                                     || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
736                             }
737                         })
738                     }
739                     _ => false,
740                 }
741             }
742
743             fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
744                 it.any(|subty| involves_impl_trait(subty))
745             }
746
747             involves_impl_trait(ty)
748         } else {
749             false
750         }
751     }
752
753     fn is_sig_const(sig: &ast::FnSig) -> bool {
754         matches!(sig.header.constness, ast::Const::Yes(_))
755             || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output)
756     }
757 }
758
759 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
760     fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
761         let is_const = match i {
762             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
763             ast::ItemKind::Fn(_, ref sig, _, _) => Self::is_sig_const(sig),
764             _ => false,
765         };
766         self.run(is_const, |s| noop_visit_item_kind(i, s))
767     }
768
769     fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
770         let is_const = match i.kind {
771             ast::AssocItemKind::Const(..) => true,
772             ast::AssocItemKind::Fn(_, ref sig, _, _) => Self::is_sig_const(sig),
773             _ => false,
774         };
775         self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
776     }
777
778     fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
779         self.flat_map_trait_item(i)
780     }
781
782     fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
783         self.run(true, |s| noop_visit_anon_const(c, s))
784     }
785
786     fn visit_block(&mut self, b: &mut P<ast::Block>) {
787         fn stmt_to_block(
788             rules: ast::BlockCheckMode,
789             s: Option<ast::Stmt>,
790             resolver: &mut Resolver<'_>,
791         ) -> ast::Block {
792             ast::Block {
793                 stmts: s.into_iter().collect(),
794                 rules,
795                 id: resolver.next_node_id(),
796                 span: rustc_span::DUMMY_SP,
797                 tokens: None,
798             }
799         }
800
801         fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
802             let expr = P(ast::Expr {
803                 id: resolver.next_node_id(),
804                 kind: ast::ExprKind::Block(P(b), None),
805                 span: rustc_span::DUMMY_SP,
806                 attrs: AttrVec::new(),
807                 tokens: None,
808             });
809
810             ast::Stmt {
811                 id: resolver.next_node_id(),
812                 kind: ast::StmtKind::Expr(expr),
813                 span: rustc_span::DUMMY_SP,
814                 tokens: None,
815             }
816         }
817
818         let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
819         let loop_expr = P(ast::Expr {
820             kind: ast::ExprKind::Loop(P(empty_block), None),
821             id: self.resolver.next_node_id(),
822             span: rustc_span::DUMMY_SP,
823             attrs: AttrVec::new(),
824             tokens: None,
825         });
826
827         let loop_stmt = ast::Stmt {
828             id: self.resolver.next_node_id(),
829             span: rustc_span::DUMMY_SP,
830             kind: ast::StmtKind::Expr(loop_expr),
831             tokens: None,
832         };
833
834         if self.within_static_or_const {
835             noop_visit_block(b, self)
836         } else {
837             visit_clobber(b.deref_mut(), |b| {
838                 let mut stmts = vec![];
839                 for s in b.stmts {
840                     let old_blocks = self.nested_blocks.replace(vec![]);
841
842                     stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
843
844                     // we put a Some in there earlier with that replace(), so this is valid
845                     let new_blocks = self.nested_blocks.take().unwrap();
846                     self.nested_blocks = old_blocks;
847                     stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
848                 }
849
850                 let mut new_block = ast::Block { stmts, ..b };
851
852                 if let Some(old_blocks) = self.nested_blocks.as_mut() {
853                     //push our fresh block onto the cache and yield an empty block with `loop {}`
854                     if !new_block.stmts.is_empty() {
855                         old_blocks.push(new_block);
856                     }
857
858                     stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
859                 } else {
860                     //push `loop {}` onto the end of our fresh block and yield that
861                     new_block.stmts.push(loop_stmt);
862
863                     new_block
864                 }
865             })
866         }
867     }
868 }
869
870 /// Returns a version string such as "rustc 1.46.0 (04488afe3 2020-08-24)"
871 pub fn version_str() -> Option<&'static str> {
872     option_env!("CFG_VERSION")
873 }
874
875 /// Returns a version string such as "0.12.0-dev".
876 pub fn release_str() -> Option<&'static str> {
877     option_env!("CFG_RELEASE")
878 }
879
880 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
881 pub fn commit_hash_str() -> Option<&'static str> {
882     option_env!("CFG_VER_HASH")
883 }
884
885 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
886 pub fn commit_date_str() -> Option<&'static str> {
887     option_env!("CFG_VER_DATE")
888 }