1 use libloading::Library;
2 use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *};
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;
29 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
30 use std::lazy::SyncOnceCell;
32 use std::ops::DerefMut;
33 #[cfg(not(parallel_compiler))]
35 use std::path::{Path, PathBuf};
36 use std::sync::atomic::{AtomicBool, Ordering};
40 /// Function pointer type that constructs a new CodegenBackend.
41 pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
43 /// Adds `target_feature = "..."` cfgs for a variety of platform
44 /// specific features (SSE, NEON etc.).
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,
51 codegen_backend: &dyn CodegenBackend,
53 let tf = sym::target_feature;
55 let target_features = codegen_backend.target_features(sess);
56 sess.target_features.extend(target_features.iter().cloned());
58 cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
60 if sess.crt_static(None) {
61 cfg.insert((tf, Some(sym::crt_dash_static)));
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>,
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)
82 sopts.debugging_opts.codegen_backend.as_ref().map(|name| &name[..]),
86 // target_override is documented to be called before init(), so this is okay
87 let target_override = codegen_backend.target_override(&sopts);
89 let mut sess = session::build_session(
99 codegen_backend.init(&sess);
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;
105 (Lrc::new(sess), Lrc::new(codegen_backend))
108 const STACK_SIZE: usize = 8 * 1024 * 1024;
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)
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
122 match unsafe { cfg.spawn_unchecked(f) }.unwrap().join() {
124 Err(e) => panic::resume_unwind(e),
128 #[cfg(not(parallel_compiler))]
129 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
134 let mut cfg = thread::Builder::new().name("rustc".to_string());
136 if let Some(size) = get_stack_size() {
137 cfg = cfg.stack_size(size);
140 let main_handler = move || rustc_span::create_session_globals_then(edition, f);
142 scoped_thread(cfg, main_handler)
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();
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<'_, '_>);
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(®istry))
168 #[cfg(parallel_compiler)]
169 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
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() });
181 if let Some(size) = get_stack_size() {
182 config = config.stack_size(size);
185 let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
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())
196 config.build_scoped(main_handler, with_pool).unwrap()
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);
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);
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() };
221 /// Get the codegen backend based on the name and specified sysroot.
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();
230 let load = LOAD.get_or_init(|| {
231 #[cfg(feature = "llvm")]
232 const DEFAULT_CODEGEN_BACKEND: &str = "llvm";
234 #[cfg(not(feature = "llvm"))]
235 const DEFAULT_CODEGEN_BACKEND: &str = "cranelift";
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),
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.
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();
257 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
259 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
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") {
269 candidate.exists().then_some(candidate)
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`.
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());
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()),
303 return sysroot_candidates;
306 fn current_dll_path() -> Option<PathBuf> {
307 use std::ffi::{CStr, OsStr};
308 use std::os::unix::prelude::*;
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");
317 if info.dli_fname.is_null() {
318 info!("dladdr returned null pointer");
321 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
322 let os = OsStr::from_bytes(bytes);
323 Some(PathBuf::from(os))
328 fn current_dll_path() -> Option<PathBuf> {
329 use std::ffi::OsString;
331 use std::os::windows::prelude::*;
334 use winapi::um::libloaderapi::{
335 GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
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 _,
346 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
349 let mut space = Vec::with_capacity(1024);
350 let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
352 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
356 if r >= space.capacity() {
357 info!("our buffer was too small? {}", io::Error::last_os_error());
361 let os = OsString::from_wide(&space);
362 Some(PathBuf::from(os))
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
373 static LOADED: AtomicBool = AtomicBool::new(false);
375 !LOADED.fetch_or(true, Ordering::SeqCst),
376 "cannot load the default codegen backend twice"
379 let target = session::config::host_triple();
380 let sysroot_candidates = sysroot_candidates();
382 let sysroot = maybe_sysroot
384 .chain(sysroot_candidates.iter())
386 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
389 info!("codegen backend candidate: {}", f.display());
392 let sysroot = sysroot.unwrap_or_else(|| {
393 let candidates = sysroot_candidates
395 .map(|p| p.display().to_string())
399 "failed to find a `codegen-backends` folder \
400 in the sysroot candidates:\n* {}",
403 early_error(ErrorOutputType::default(), &err);
405 info!("probing {} for a codegen backend", sysroot.display());
407 let d = sysroot.read_dir().unwrap_or_else(|e| {
409 "failed to load default codegen backend, couldn't \
414 early_error(ErrorOutputType::default(), &err);
417 let mut file: Option<PathBuf> = None;
419 let expected_names = &[
420 format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
421 format!("rustc_codegen_{}", backend_name),
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()) {
429 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
432 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
433 if !expected_names.iter().any(|expected| expected == name) {
436 if let Some(ref prev) = file {
438 "duplicate codegen backends found\n\
445 early_error(ErrorOutputType::default(), &err);
447 file = Some(path.clone());
451 Some(ref s) => load_backend_from_dylib(s),
453 let err = format!("unsupported builtin codegen backend `{}`", backend_name);
454 early_error(ErrorOutputType::default(), &err);
459 pub(crate) fn check_attr_crate_type(
461 attrs: &[ast::Attribute],
462 lint_buffer: &mut LintBuffer,
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() {
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<_>>(),
479 if let Some(candidate) = lev_candidate {
480 lint_buffer.buffer_lint_with_diagnostic(
481 lint::builtin::UNKNOWN_CRATE_TYPES,
484 "invalid `crate_type` value",
485 BuiltinLintDiagnostics::UnknownCrateTypes(
487 "did you mean".to_string(),
488 format!("\"{}\"", candidate),
492 lint_buffer.buffer_lint(
493 lint::builtin::UNKNOWN_CRATE_TYPES,
496 "invalid `crate_type` value",
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
508 validate_attr::emit_fatal_malformed_builtin_attribute(
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),
528 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
529 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
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
537 if a.has_name(sym::crate_type) {
538 match a.value_str() {
539 Some(s) => categorize_crate_type(s),
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];
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();
559 base.extend(attr_types);
561 base.push(output::default_output_for_target(session));
568 base.retain(|crate_type| {
569 let res = !output::invalid_output_for_target(session, *crate_type);
572 session.warn(&format!(
573 "dropping unsupported crate type `{}` for target `{}`",
574 *crate_type, session.opts.target_triple
584 pub fn build_output_filenames(
586 odir: &Option<PathBuf>,
587 ofile: &Option<PathBuf>,
588 temps_dir: &Option<PathBuf>,
589 attrs: &[ast::Attribute],
591 ) -> OutputFilenames {
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();
599 // If a crate name is present, we use it as the link name
604 .or_else(|| rustc_attr::find_crate_name(sess, attrs).map(|n| n.to_string()))
605 .unwrap_or_else(|| input.filestem().to_owned());
607 OutputFilenames::new(
612 sess.opts.cg.extra_filename.clone(),
613 sess.opts.output_types.clone(),
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 {
622 "due to multiple output types requested, the explicitly specified \
623 output file name will be adapted for each output type",
627 if !sess.opts.cg.extra_filename.is_empty() {
628 sess.warn("ignoring -C extra-filename flag due to -o flag");
630 Some(out_file.clone())
633 sess.warn("ignoring --out-dir flag due to -o flag");
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(),
641 sess.opts.cg.extra_filename.clone(),
642 sess.opts.output_types.clone(),
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)
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.
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)
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.
670 /// This pass is known as `everybody_loops`. Very punny.
672 /// As of March 2021, `everybody_loops` is only used for the
673 /// `-Z unpretty=everybody_loops` debugging option.
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].
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>,
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 }
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;
704 fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
705 let ast::FnRetTy::Ty(ref ty) = ret_ty else {
708 fn involves_impl_trait(ty: &ast::Ty) -> bool {
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() {
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(_) => {
728 ast::AngleBracketedArg::Constraint(c) => match c.kind {
729 ast::AssocConstraintKind::Bound { .. } => true,
730 ast::AssocConstraintKind::Equality { ref 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,
741 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
742 any_involves_impl_trait(data.inputs.iter())
743 || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
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))
755 involves_impl_trait(ty)
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)
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),
771 self.run(is_const, |s| noop_visit_item_kind(i, s))
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),
780 self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
783 fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
784 self.flat_map_trait_item(i)
787 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
788 self.run(true, |s| noop_visit_anon_const(c, s))
791 fn visit_block(&mut self, b: &mut P<ast::Block>) {
793 rules: ast::BlockCheckMode,
794 s: Option<ast::Stmt>,
795 resolver: &mut Resolver<'_>,
798 stmts: s.into_iter().collect(),
800 id: resolver.next_node_id(),
801 span: rustc_span::DUMMY_SP,
803 could_be_bare_literal: false,
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(),
817 id: resolver.next_node_id(),
818 kind: ast::StmtKind::Expr(expr),
819 span: rustc_span::DUMMY_SP,
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(),
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),
838 if self.within_static_or_const {
839 noop_visit_block(b, self)
841 visit_clobber(b.deref_mut(), |b| {
842 let mut stmts = vec![];
844 let old_blocks = self.nested_blocks.replace(vec![]);
846 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
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)));
854 let mut new_block = ast::Block { stmts, ..b };
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);
862 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
864 //push `loop {}` onto the end of our fresh block and yield that
865 new_block.stmts.push(loop_stmt);
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")
879 /// Returns a version string such as "0.12.0-dev".
880 pub fn release_str() -> Option<&'static str> {
881 option_env!("CFG_RELEASE")
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")
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")