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