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::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;
30 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};
41 /// Function pointer type that constructs a new CodegenBackend.
42 pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
44 /// Adds `target_feature = "..."` cfgs for a variety of platform
45 /// specific features (SSE, NEON etc.).
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,
52 codegen_backend: &dyn CodegenBackend,
54 let tf = sym::target_feature;
56 let target_features = codegen_backend.target_features(sess);
57 sess.target_features.extend(target_features.iter().cloned());
59 cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
61 if sess.crt_static(None) {
62 cfg.insert((tf, Some(sym::crt_dash_static)));
66 pub fn create_session(
67 sopts: config::Options,
68 cfg: FxHashSet<(String, Option<String>)>,
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>,
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)
84 sopts.debugging_opts.codegen_backend.as_ref().map(|name| &name[..]),
88 // target_override is documented to be called before init(), so this is okay
89 let target_override = codegen_backend.target_override(&sopts);
91 let mut sess = session::build_session(
101 codegen_backend.init(&sess);
103 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
104 add_configuration(&mut cfg, &mut sess, &*codegen_backend);
106 let mut check_cfg = config::to_crate_check_config(check_cfg);
107 check_cfg.fill_well_known();
108 check_cfg.fill_actual(&cfg);
110 sess.parse_sess.config = cfg;
111 sess.parse_sess.check_config = check_cfg;
113 (Lrc::new(sess), Lrc::new(codegen_backend))
116 const STACK_SIZE: usize = 8 * 1024 * 1024;
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)
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
130 match unsafe { cfg.spawn_unchecked(f) }.unwrap().join() {
132 Err(e) => panic::resume_unwind(e),
136 #[cfg(not(parallel_compiler))]
137 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
142 let mut cfg = thread::Builder::new().name("rustc".to_string());
144 if let Some(size) = get_stack_size() {
145 cfg = cfg.stack_size(size);
148 let main_handler = move || rustc_span::create_session_globals_then(edition, f);
150 scoped_thread(cfg, main_handler)
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();
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<'_, '_>);
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(®istry))
176 #[cfg(parallel_compiler)]
177 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
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() });
189 if let Some(size) = get_stack_size() {
190 config = config.stack_size(size);
193 let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
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())
204 config.build_scoped(main_handler, with_pool).unwrap()
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);
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);
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() };
229 /// Get the codegen backend based on the name and specified sysroot.
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();
238 let load = LOAD.get_or_init(|| {
239 let default_codegen_backend = option_env!("CFG_DEFAULT_CODEGEN_BACKEND").unwrap_or("llvm");
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),
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.
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();
261 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
263 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
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") {
273 candidate.exists().then_some(candidate)
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`.
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());
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()),
307 return sysroot_candidates;
310 fn current_dll_path() -> Option<PathBuf> {
311 use std::ffi::{CStr, OsStr};
312 use std::os::unix::prelude::*;
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");
321 if info.dli_fname.is_null() {
322 info!("dladdr returned null pointer");
325 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
326 let os = OsStr::from_bytes(bytes);
327 Some(PathBuf::from(os))
332 fn current_dll_path() -> Option<PathBuf> {
333 use std::ffi::OsString;
335 use std::os::windows::prelude::*;
338 use winapi::um::libloaderapi::{
339 GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
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 _,
350 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
353 let mut space = Vec::with_capacity(1024);
354 let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
356 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
360 if r >= space.capacity() {
361 info!("our buffer was too small? {}", io::Error::last_os_error());
365 let os = OsString::from_wide(&space);
366 Some(PathBuf::from(os))
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
377 static LOADED: AtomicBool = AtomicBool::new(false);
379 !LOADED.fetch_or(true, Ordering::SeqCst),
380 "cannot load the default codegen backend twice"
383 let target = session::config::host_triple();
384 let sysroot_candidates = sysroot_candidates();
386 let sysroot = maybe_sysroot
388 .chain(sysroot_candidates.iter())
390 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
393 info!("codegen backend candidate: {}", f.display());
396 let sysroot = sysroot.unwrap_or_else(|| {
397 let candidates = sysroot_candidates
399 .map(|p| p.display().to_string())
403 "failed to find a `codegen-backends` folder \
404 in the sysroot candidates:\n* {}",
407 early_error(ErrorOutputType::default(), &err);
409 info!("probing {} for a codegen backend", sysroot.display());
411 let d = sysroot.read_dir().unwrap_or_else(|e| {
413 "failed to load default codegen backend, couldn't \
418 early_error(ErrorOutputType::default(), &err);
421 let mut file: Option<PathBuf> = None;
423 let expected_names = &[
424 format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
425 format!("rustc_codegen_{}", backend_name),
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)) {
433 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
434 if !expected_names.iter().any(|expected| expected == name) {
437 if let Some(ref prev) = file {
439 "duplicate codegen backends found\n\
446 early_error(ErrorOutputType::default(), &err);
448 file = Some(path.clone());
452 Some(ref s) => load_backend_from_dylib(s),
454 let err = format!("unsupported builtin codegen backend `{}`", backend_name);
455 early_error(ErrorOutputType::default(), &err);
460 pub(crate) fn check_attr_crate_type(
462 attrs: &[ast::Attribute],
463 lint_buffer: &mut LintBuffer,
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() {
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<_>>(),
480 if let Some(candidate) = lev_candidate {
481 lint_buffer.buffer_lint_with_diagnostic(
482 lint::builtin::UNKNOWN_CRATE_TYPES,
485 "invalid `crate_type` value",
486 BuiltinLintDiagnostics::UnknownCrateTypes(
488 "did you mean".to_string(),
489 format!("\"{}\"", candidate),
493 lint_buffer.buffer_lint(
494 lint::builtin::UNKNOWN_CRATE_TYPES,
497 "invalid `crate_type` value",
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
509 validate_attr::emit_fatal_malformed_builtin_attribute(
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),
529 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
530 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
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
538 if a.has_name(sym::crate_type) {
539 match a.value_str() {
540 Some(s) => categorize_crate_type(s),
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];
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();
560 base.extend(attr_types);
562 base.push(output::default_output_for_target(session));
569 base.retain(|crate_type| {
570 let res = !output::invalid_output_for_target(session, *crate_type);
573 session.warn(&format!(
574 "dropping unsupported crate type `{}` for target `{}`",
575 *crate_type, session.opts.target_triple
585 pub fn build_output_filenames(
587 odir: &Option<PathBuf>,
588 ofile: &Option<PathBuf>,
589 temps_dir: &Option<PathBuf>,
590 attrs: &[ast::Attribute],
592 ) -> OutputFilenames {
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();
600 // If a crate name is present, we use it as the link name
605 .or_else(|| rustc_attr::find_crate_name(sess, attrs).map(|n| n.to_string()))
606 .unwrap_or_else(|| input.filestem().to_owned());
608 OutputFilenames::new(
613 sess.opts.cg.extra_filename.clone(),
614 sess.opts.output_types.clone(),
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 {
623 "due to multiple output types requested, the explicitly specified \
624 output file name will be adapted for each output type",
628 if !sess.opts.cg.extra_filename.is_empty() {
629 sess.warn("ignoring -C extra-filename flag due to -o flag");
631 Some(out_file.clone())
634 sess.warn("ignoring --out-dir flag due to -o flag");
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(),
642 sess.opts.cg.extra_filename.clone(),
643 sess.opts.output_types.clone(),
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)
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.
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)
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.
671 /// This pass is known as `everybody_loops`. Very punny.
673 /// As of March 2021, `everybody_loops` is only used for the
674 /// `-Z unpretty=everybody_loops` debugging option.
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].
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>,
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 }
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;
705 fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
706 let ast::FnRetTy::Ty(ref ty) = ret_ty else {
709 fn involves_impl_trait(ty: &ast::Ty) -> bool {
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() {
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(_) => {
729 ast::AngleBracketedArg::Constraint(c) => match c.kind {
730 ast::AssocConstraintKind::Bound { .. } => true,
731 ast::AssocConstraintKind::Equality { ref 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,
742 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
743 any_involves_impl_trait(data.inputs.iter())
744 || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
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))
756 involves_impl_trait(ty)
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)
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),
772 self.run(is_const, |s| noop_visit_item_kind(i, s))
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),
781 self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
784 fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
785 self.flat_map_trait_item(i)
788 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
789 self.run(true, |s| noop_visit_anon_const(c, s))
792 fn visit_block(&mut self, b: &mut P<ast::Block>) {
794 rules: ast::BlockCheckMode,
795 s: Option<ast::Stmt>,
796 resolver: &mut Resolver<'_>,
799 stmts: s.into_iter().collect(),
801 id: resolver.next_node_id(),
802 span: rustc_span::DUMMY_SP,
804 could_be_bare_literal: false,
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(),
818 id: resolver.next_node_id(),
819 kind: ast::StmtKind::Expr(expr),
820 span: rustc_span::DUMMY_SP,
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(),
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),
839 if self.within_static_or_const {
840 noop_visit_block(b, self)
842 visit_clobber(b.deref_mut(), |b| {
843 let mut stmts = vec![];
845 let old_blocks = self.nested_blocks.replace(vec![]);
847 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
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)));
855 let mut new_block = ast::Block { stmts, ..b };
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);
863 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
865 //push `loop {}` onto the end of our fresh block and yield that
866 new_block.stmts.push(loop_stmt);
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")
880 /// Returns a version string such as "0.12.0-dev".
881 pub fn release_str() -> Option<&'static str> {
882 option_env!("CFG_RELEASE")
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")
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")