1 use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *};
3 use rustc_ast::{self as ast, AttrVec, BlockCheckMode};
4 use rustc_codegen_ssa::traits::CodegenBackend;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 #[cfg(parallel_compiler)]
8 use rustc_data_structures::jobserver;
9 use rustc_data_structures::stable_hasher::StableHasher;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_errors::registry::Registry;
12 use rustc_metadata::dynamic_lib::DynamicLibrary;
13 #[cfg(parallel_compiler)]
14 use rustc_middle::ty::tls;
15 use rustc_resolve::{self, Resolver};
16 use rustc_session as session;
17 use rustc_session::config::{self, CrateType};
18 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
19 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
20 use rustc_session::parse::CrateConfig;
21 use rustc_session::CrateDisambiguator;
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;
29 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
31 use std::lazy::SyncOnceCell;
33 use std::ops::DerefMut;
34 #[cfg(not(parallel_compiler))]
36 use std::path::{Path, PathBuf};
37 use std::sync::atomic::{AtomicBool, Ordering};
38 use std::sync::{Arc, Mutex, Once};
42 /// Adds `target_feature = "..."` cfgs for a variety of platform
43 /// specific features (SSE, NEON etc.).
45 /// This is performed by checking whether a set of permitted features
46 /// is available on the target machine, by querying LLVM.
47 pub fn add_configuration(
48 cfg: &mut CrateConfig,
50 codegen_backend: &dyn CodegenBackend,
52 let tf = sym::target_feature;
54 let target_features = codegen_backend.target_features(sess);
55 sess.target_features.extend(target_features.iter().cloned());
57 cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
59 if sess.crt_static(None) {
60 cfg.insert((tf, Some(sym::crt_dash_static)));
64 pub fn create_session(
65 sopts: config::Options,
66 cfg: FxHashSet<(String, Option<String>)>,
67 diagnostic_output: DiagnosticOutput,
68 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
69 input_path: Option<PathBuf>,
70 lint_caps: FxHashMap<lint::LintId, lint::Level>,
71 make_codegen_backend: Option<
72 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
74 descriptions: Registry,
75 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
76 let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
77 make_codegen_backend(&sopts)
79 get_codegen_backend(&sopts)
82 // target_override is documented to be called before init(), so this is okay
83 let target_override = codegen_backend.target_override(&sopts);
85 let mut sess = session::build_session(
95 codegen_backend.init(&sess);
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;
101 (Lrc::new(sess), Lrc::new(codegen_backend))
104 const STACK_SIZE: usize = 8 * 1024 * 1024;
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)
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 {
117 unsafe impl Send for Ptr {}
118 unsafe impl Sync for Ptr {}
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 ());
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());
131 match thread.unwrap().join() {
132 Ok(()) => result.unwrap(),
133 Err(p) => panic::resume_unwind(p),
137 #[cfg(not(parallel_compiler))]
138 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
141 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
144 let mut cfg = thread::Builder::new().name("rustc".to_string());
146 if let Some(size) = get_stack_size() {
147 cfg = cfg.stack_size(size);
150 crate::callbacks::setup_callbacks();
152 let main_handler = move || {
153 rustc_span::with_session_globals(edition, || {
154 io::set_output_capture(stderr.clone());
159 scoped_thread(cfg, main_handler)
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();
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<'_, '_>);
174 let session_globals = rustc_span::SESSION_GLOBALS.with(|sg| sg as *const _);
175 let session_globals = &*session_globals;
176 thread::spawn(move || {
177 tls::enter_context(icx, |_| {
178 rustc_span::SESSION_GLOBALS
179 .set(session_globals, || tls::with(|tcx| tcx.queries.deadlock(tcx, ®istry)))
184 #[cfg(parallel_compiler)]
185 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
188 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
191 crate::callbacks::setup_callbacks();
193 let mut config = rayon::ThreadPoolBuilder::new()
194 .thread_name(|_| "rustc".to_string())
195 .acquire_thread_handler(jobserver::acquire_thread)
196 .release_thread_handler(jobserver::release_thread)
197 .num_threads(threads)
198 .deadlock_handler(|| unsafe { handle_deadlock() });
200 if let Some(size) = get_stack_size() {
201 config = config.stack_size(size);
204 let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
206 rustc_span::with_session_globals(edition, || {
207 rustc_span::SESSION_GLOBALS.with(|session_globals| {
208 // The main handler runs for each Rayon worker thread and sets up
209 // the thread local rustc uses. `session_globals` is captured and set
210 // on the new threads.
211 let main_handler = move |thread: rayon::ThreadBuilder| {
212 rustc_span::SESSION_GLOBALS.set(session_globals, || {
213 io::set_output_capture(stderr.clone());
218 config.build_scoped(main_handler, with_pool).unwrap()
223 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
224 let lib = DynamicLibrary::open(path).unwrap_or_else(|err| {
225 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
226 early_error(ErrorOutputType::default(), &err);
229 match lib.symbol("__rustc_codegen_backend") {
232 mem::transmute::<*mut u8, _>(f)
236 "couldn't load codegen backend as it \
237 doesn't export the `__rustc_codegen_backend` \
241 early_error(ErrorOutputType::default(), &err);
247 pub fn get_codegen_backend(sopts: &config::Options) -> Box<dyn CodegenBackend> {
248 static INIT: Once = Once::new();
250 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
253 #[cfg(feature = "llvm")]
254 const DEFAULT_CODEGEN_BACKEND: &str = "llvm";
256 #[cfg(not(feature = "llvm"))]
257 const DEFAULT_CODEGEN_BACKEND: &str = "cranelift";
259 let codegen_name = sopts
263 .map(|name| &name[..])
264 .unwrap_or(DEFAULT_CODEGEN_BACKEND);
266 let backend = match codegen_name {
267 filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
268 codegen_name => get_builtin_codegen_backend(&sopts.maybe_sysroot, codegen_name),
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();
284 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
286 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
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") {
296 candidate.exists().then_some(candidate)
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`.
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());
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()),
330 return sysroot_candidates;
333 fn current_dll_path() -> Option<PathBuf> {
334 use std::ffi::{CStr, OsStr};
335 use std::os::unix::prelude::*;
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");
344 if info.dli_fname.is_null() {
345 info!("dladdr returned null pointer");
348 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
349 let os = OsStr::from_bytes(bytes);
350 Some(PathBuf::from(os))
355 fn current_dll_path() -> Option<PathBuf> {
356 use std::ffi::OsString;
357 use std::os::windows::prelude::*;
360 use winapi::um::libloaderapi::{
361 GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
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 _,
372 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
375 let mut space = Vec::with_capacity(1024);
376 let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
378 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
382 if r >= space.capacity() {
383 info!("our buffer was too small? {}", io::Error::last_os_error());
387 let os = OsString::from_wide(&space);
388 Some(PathBuf::from(os))
393 pub fn get_builtin_codegen_backend(
394 maybe_sysroot: &Option<PathBuf>,
396 ) -> fn() -> Box<dyn CodegenBackend> {
398 #[cfg(feature = "llvm")]
399 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
400 _ => get_codegen_sysroot(maybe_sysroot, backend_name),
404 pub fn get_codegen_sysroot(
405 maybe_sysroot: &Option<PathBuf>,
407 ) -> fn() -> Box<dyn CodegenBackend> {
408 // For now we only allow this function to be called once as it'll dlopen a
409 // few things, which seems to work best if we only do that once. In
410 // general this assertion never trips due to the once guard in `get_codegen_backend`,
411 // but there's a few manual calls to this function in this file we protect
413 static LOADED: AtomicBool = AtomicBool::new(false);
415 !LOADED.fetch_or(true, Ordering::SeqCst),
416 "cannot load the default codegen backend twice"
419 let target = session::config::host_triple();
420 let sysroot_candidates = sysroot_candidates();
422 let sysroot = maybe_sysroot
424 .chain(sysroot_candidates.iter())
426 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
427 sysroot.join(libdir).with_file_name("codegen-backends")
430 info!("codegen backend candidate: {}", f.display());
433 let sysroot = sysroot.unwrap_or_else(|| {
434 let candidates = sysroot_candidates
436 .map(|p| p.display().to_string())
440 "failed to find a `codegen-backends` folder \
441 in the sysroot candidates:\n* {}",
444 early_error(ErrorOutputType::default(), &err);
446 info!("probing {} for a codegen backend", sysroot.display());
448 let d = sysroot.read_dir().unwrap_or_else(|e| {
450 "failed to load default codegen backend, couldn't \
455 early_error(ErrorOutputType::default(), &err);
458 let mut file: Option<PathBuf> = None;
460 let expected_names = &[
461 format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
462 format!("rustc_codegen_{}", backend_name),
464 for entry in d.filter_map(|e| e.ok()) {
465 let path = entry.path();
466 let filename = match path.file_name().and_then(|s| s.to_str()) {
470 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
473 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
474 if !expected_names.iter().any(|expected| expected == name) {
477 if let Some(ref prev) = file {
479 "duplicate codegen backends found\n\
486 early_error(ErrorOutputType::default(), &err);
488 file = Some(path.clone());
492 Some(ref s) => load_backend_from_dylib(s),
494 let err = format!("unsupported builtin codegen backend `{}`", backend_name);
495 early_error(ErrorOutputType::default(), &err);
500 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
501 use std::hash::Hasher;
503 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
504 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
505 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
506 // should still be safe enough to avoid collisions in practice.
507 let mut hasher = StableHasher::new();
509 let mut metadata = session.opts.cg.metadata.clone();
510 // We don't want the crate_disambiguator to dependent on the order
511 // -C metadata arguments, so sort them:
513 // Every distinct -C metadata value is only incorporated once:
516 hasher.write(b"metadata");
518 // Also incorporate the length of a metadata string, so that we generate
519 // different values for `-Cmetadata=ab -Cmetadata=c` and
520 // `-Cmetadata=a -Cmetadata=bc`
521 hasher.write_usize(s.len());
522 hasher.write(s.as_bytes());
525 // Also incorporate crate type, so that we don't get symbol conflicts when
526 // linking against a library of the same name, if this is an executable.
527 let is_exe = session.crate_types().contains(&CrateType::Executable);
528 hasher.write(if is_exe { b"exe" } else { b"lib" });
530 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
533 pub(crate) fn check_attr_crate_type(
535 attrs: &[ast::Attribute],
536 lint_buffer: &mut LintBuffer,
538 // Unconditionally collect crate types from attributes to make them used
539 for a in attrs.iter() {
540 if sess.check_name(a, sym::crate_type) {
541 if let Some(n) = a.value_str() {
542 if categorize_crate_type(n).is_some() {
546 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
547 let span = spanned.span;
548 let lev_candidate = find_best_match_for_name(
549 &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
553 if let Some(candidate) = lev_candidate {
554 lint_buffer.buffer_lint_with_diagnostic(
555 lint::builtin::UNKNOWN_CRATE_TYPES,
558 "invalid `crate_type` value",
559 BuiltinLintDiagnostics::UnknownCrateTypes(
561 "did you mean".to_string(),
562 format!("\"{}\"", candidate),
566 lint_buffer.buffer_lint(
567 lint::builtin::UNKNOWN_CRATE_TYPES,
570 "invalid `crate_type` value",
579 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
580 (sym::rlib, CrateType::Rlib),
581 (sym::dylib, CrateType::Dylib),
582 (sym::cdylib, CrateType::Cdylib),
583 (sym::lib, config::default_lib_output()),
584 (sym::staticlib, CrateType::Staticlib),
585 (sym::proc_dash_macro, CrateType::ProcMacro),
586 (sym::bin, CrateType::Executable),
589 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
590 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
593 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
594 // Unconditionally collect crate types from attributes to make them used
595 let attr_types: Vec<CrateType> = attrs
598 if session.check_name(a, sym::crate_type) {
599 match a.value_str() {
600 Some(s) => categorize_crate_type(s),
609 // If we're generating a test executable, then ignore all other output
610 // styles at all other locations
611 if session.opts.test {
612 return vec![CrateType::Executable];
615 // Only check command line flags if present. If no types are specified by
616 // command line, then reuse the empty `base` Vec to hold the types that
617 // will be found in crate attributes.
618 let mut base = session.opts.crate_types.clone();
620 base.extend(attr_types);
622 base.push(output::default_output_for_target(session));
629 base.retain(|crate_type| {
630 let res = !output::invalid_output_for_target(session, *crate_type);
633 session.warn(&format!(
634 "dropping unsupported crate type `{}` for target `{}`",
635 *crate_type, session.opts.target_triple
645 pub fn build_output_filenames(
647 odir: &Option<PathBuf>,
648 ofile: &Option<PathBuf>,
649 attrs: &[ast::Attribute],
651 ) -> OutputFilenames {
654 // "-" as input file will cause the parser to read from stdin so we
655 // have to make up a name
656 // We want to toss everything after the final '.'
657 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
659 // If a crate name is present, we use it as the link name
664 .or_else(|| rustc_attr::find_crate_name(&sess, attrs).map(|n| n.to_string()))
665 .unwrap_or_else(|| input.filestem().to_owned());
667 OutputFilenames::new(
671 sess.opts.cg.extra_filename.clone(),
672 sess.opts.output_types.clone(),
676 Some(ref out_file) => {
677 let unnamed_output_types =
678 sess.opts.output_types.values().filter(|a| a.is_none()).count();
679 let ofile = if unnamed_output_types > 1 {
681 "due to multiple output types requested, the explicitly specified \
682 output file name will be adapted for each output type",
686 if !sess.opts.cg.extra_filename.is_empty() {
687 sess.warn("ignoring -C extra-filename flag due to -o flag");
689 Some(out_file.clone())
692 sess.warn("ignoring --out-dir flag due to -o flag");
695 OutputFilenames::new(
696 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
697 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
699 sess.opts.cg.extra_filename.clone(),
700 sess.opts.output_types.clone(),
706 #[cfg(not(target_os = "linux"))]
707 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
708 std::fs::rename(src, dst)
711 /// This function attempts to bypass the auto_da_alloc heuristic implemented by some filesystems
712 /// such as btrfs and ext4. When renaming over a file that already exists then they will "helpfully"
713 /// write back the source file before committing the rename in case a developer forgot some of
714 /// the fsyncs in the open/write/fsync(file)/rename/fsync(dir) dance for atomic file updates.
716 /// To avoid triggering this heuristic we delete the destination first, if it exists.
717 /// The cost of an extra syscall is much lower than getting descheduled for the sync IO.
718 #[cfg(target_os = "linux")]
719 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
720 let _ = std::fs::remove_file(dst);
721 std::fs::rename(src, dst)
724 /// Replaces function bodies with `loop {}` (an infinite loop). This gets rid of
725 /// all semantic errors in the body while still satisfying the return type,
726 /// except in certain cases, see below for more.
728 /// This pass is known as `everybody_loops`. Very punny.
730 /// As of March 2021, `everybody_loops` is only used for the
731 /// `-Z unpretty=everybody_loops` debugging option.
733 /// FIXME: Currently the `everybody_loops` transformation is not applied to:
734 /// * `const fn`; support could be added, but hasn't. Originally `const fn`
735 /// was skipped due to issue #43636 that `loop` was not supported for
736 /// const evaluation.
737 /// * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
738 /// Solving this may require `!` to implement every trait, which relies on the an even more
739 /// ambitious form of the closed RFC #1637. See also [#34511].
741 /// [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
742 pub struct ReplaceBodyWithLoop<'a, 'b> {
743 within_static_or_const: bool,
744 nested_blocks: Option<Vec<ast::Block>>,
745 resolver: &'a mut Resolver<'b>,
748 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
749 pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
750 ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver }
753 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
754 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
755 let old_blocks = self.nested_blocks.take();
756 let ret = action(self);
757 self.within_static_or_const = old_const;
758 self.nested_blocks = old_blocks;
762 fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
763 if let ast::FnRetTy::Ty(ref ty) = ret_ty {
764 fn involves_impl_trait(ty: &ast::Ty) -> bool {
766 ast::TyKind::ImplTrait(..) => true,
767 ast::TyKind::Slice(ref subty)
768 | ast::TyKind::Array(ref subty, _)
769 | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. })
770 | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. })
771 | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
772 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
773 ast::TyKind::Path(_, ref path) => {
774 path.segments.iter().any(|seg| match seg.args.as_deref() {
776 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
777 data.args.iter().any(|arg| match arg {
778 ast::AngleBracketedArg::Arg(arg) => match arg {
779 ast::GenericArg::Type(ty) => involves_impl_trait(ty),
780 ast::GenericArg::Lifetime(_)
781 | ast::GenericArg::Const(_) => false,
783 ast::AngleBracketedArg::Constraint(c) => match c.kind {
784 ast::AssocTyConstraintKind::Bound { .. } => true,
785 ast::AssocTyConstraintKind::Equality { ref ty } => {
786 involves_impl_trait(ty)
791 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
792 any_involves_impl_trait(data.inputs.iter())
793 || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
801 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
802 it.any(|subty| involves_impl_trait(subty))
805 involves_impl_trait(ty)
811 fn is_sig_const(sig: &ast::FnSig) -> bool {
812 matches!(sig.header.constness, ast::Const::Yes(_))
813 || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output)
817 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
818 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
819 let is_const = match i {
820 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
821 ast::ItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
824 self.run(is_const, |s| noop_visit_item_kind(i, s))
827 fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
828 let is_const = match i.kind {
829 ast::AssocItemKind::Const(..) => true,
830 ast::AssocItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
833 self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
836 fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
837 self.flat_map_trait_item(i)
840 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
841 self.run(true, |s| noop_visit_anon_const(c, s))
844 fn visit_block(&mut self, b: &mut P<ast::Block>) {
846 rules: ast::BlockCheckMode,
847 s: Option<ast::Stmt>,
848 resolver: &mut Resolver<'_>,
851 stmts: s.into_iter().collect(),
853 id: resolver.next_node_id(),
854 span: rustc_span::DUMMY_SP,
859 fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
860 let expr = P(ast::Expr {
861 id: resolver.next_node_id(),
862 kind: ast::ExprKind::Block(P(b), None),
863 span: rustc_span::DUMMY_SP,
864 attrs: AttrVec::new(),
869 id: resolver.next_node_id(),
870 kind: ast::StmtKind::Expr(expr),
871 span: rustc_span::DUMMY_SP,
875 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
876 let loop_expr = P(ast::Expr {
877 kind: ast::ExprKind::Loop(P(empty_block), None),
878 id: self.resolver.next_node_id(),
879 span: rustc_span::DUMMY_SP,
880 attrs: AttrVec::new(),
884 let loop_stmt = ast::Stmt {
885 id: self.resolver.next_node_id(),
886 span: rustc_span::DUMMY_SP,
887 kind: ast::StmtKind::Expr(loop_expr),
890 if self.within_static_or_const {
891 noop_visit_block(b, self)
893 visit_clobber(b.deref_mut(), |b| {
894 let mut stmts = vec![];
896 let old_blocks = self.nested_blocks.replace(vec![]);
898 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
900 // we put a Some in there earlier with that replace(), so this is valid
901 let new_blocks = self.nested_blocks.take().unwrap();
902 self.nested_blocks = old_blocks;
903 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
906 let mut new_block = ast::Block { stmts, ..b };
908 if let Some(old_blocks) = self.nested_blocks.as_mut() {
909 //push our fresh block onto the cache and yield an empty block with `loop {}`
910 if !new_block.stmts.is_empty() {
911 old_blocks.push(new_block);
914 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
916 //push `loop {}` onto the end of our fresh block and yield that
917 new_block.stmts.push(loop_stmt);
926 /// Returns a version string such as "rustc 1.46.0 (04488afe3 2020-08-24)"
927 pub fn version_str() -> Option<&'static str> {
928 option_env!("CFG_VERSION")
931 /// Returns a version string such as "0.12.0-dev".
932 pub fn release_str() -> Option<&'static str> {
933 option_env!("CFG_RELEASE")
936 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
937 pub fn commit_hash_str() -> Option<&'static str> {
938 option_env!("CFG_VER_HASH")
941 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
942 pub fn commit_date_str() -> Option<&'static str> {
943 option_env!("CFG_VER_DATE")