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