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