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