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