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::fx::{FxHashMap, FxHashSet};
6 #[cfg(parallel_compiler)]
7 use rustc_data_structures::jobserver;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::registry::Registry;
10 use rustc_metadata::dynamic_lib::DynamicLibrary;
11 #[cfg(parallel_compiler)]
12 use rustc_middle::ty::tls;
13 use rustc_resolve::{self, Resolver};
14 use rustc_session as session;
15 use rustc_session::config::{self, CrateType};
16 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
17 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
18 use rustc_session::parse::CrateConfig;
19 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
20 use rustc_span::edition::Edition;
21 use rustc_span::lev_distance::find_best_match_for_name;
22 use rustc_span::source_map::FileLoader;
23 use rustc_span::symbol::{sym, Symbol};
24 use smallvec::SmallVec;
26 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
28 use std::lazy::SyncOnceCell;
30 use std::ops::DerefMut;
31 #[cfg(not(parallel_compiler))]
33 use std::path::{Path, PathBuf};
34 use std::sync::atomic::{AtomicBool, Ordering};
35 use std::sync::{Arc, Mutex};
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
42 /// This is performed by checking whether a set of permitted features
43 /// is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45 cfg: &mut CrateConfig,
47 codegen_backend: &dyn CodegenBackend,
49 let tf = sym::target_feature;
51 let target_features = codegen_backend.target_features(sess);
52 sess.target_features.extend(target_features.iter().cloned());
54 cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
56 if sess.crt_static(None) {
57 cfg.insert((tf, Some(sym::crt_dash_static)));
61 pub fn create_session(
62 sopts: config::Options,
63 cfg: FxHashSet<(String, Option<String>)>,
64 diagnostic_output: DiagnosticOutput,
65 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
66 input_path: Option<PathBuf>,
67 lint_caps: FxHashMap<lint::LintId, lint::Level>,
68 make_codegen_backend: Option<
69 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
71 descriptions: Registry,
72 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
73 let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
74 make_codegen_backend(&sopts)
78 sopts.debugging_opts.codegen_backend.as_ref().map(|name| &name[..]),
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::create_session_globals_then(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::with_session_globals(|sg| sg as *const _);
175 let session_globals = &*session_globals;
176 thread::spawn(move || {
177 tls::enter_context(icx, |_| {
178 rustc_span::set_session_globals_then(session_globals, || {
179 tls::with(|tcx| tcx.queries.deadlock(tcx, ®istry))
185 #[cfg(parallel_compiler)]
186 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
189 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
192 crate::callbacks::setup_callbacks();
194 let mut config = rayon::ThreadPoolBuilder::new()
195 .thread_name(|_| "rustc".to_string())
196 .acquire_thread_handler(jobserver::acquire_thread)
197 .release_thread_handler(jobserver::release_thread)
198 .num_threads(threads)
199 .deadlock_handler(|| unsafe { handle_deadlock() });
201 if let Some(size) = get_stack_size() {
202 config = config.stack_size(size);
205 let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
207 rustc_span::create_session_globals_then(edition, || {
208 rustc_span::with_session_globals(|session_globals| {
209 // The main handler runs for each Rayon worker thread and sets up
210 // the thread local rustc uses. `session_globals` is captured and set
211 // on the new threads.
212 let main_handler = move |thread: rayon::ThreadBuilder| {
213 rustc_span::set_session_globals_then(session_globals, || {
214 io::set_output_capture(stderr.clone());
219 config.build_scoped(main_handler, with_pool).unwrap()
224 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
225 let lib = DynamicLibrary::open(path).unwrap_or_else(|err| {
226 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
227 early_error(ErrorOutputType::default(), &err);
230 match lib.symbol("__rustc_codegen_backend") {
233 mem::transmute::<*mut u8, _>(f)
237 "couldn't load codegen backend as it \
238 doesn't export the `__rustc_codegen_backend` \
242 early_error(ErrorOutputType::default(), &err);
248 /// Get the codegen backend based on the name and specified sysroot.
250 /// A name of `None` indicates that the default backend should be used.
251 pub fn get_codegen_backend(
252 maybe_sysroot: &Option<PathBuf>,
253 backend_name: Option<&str>,
254 ) -> Box<dyn CodegenBackend> {
255 static LOAD: SyncOnceCell<unsafe fn() -> Box<dyn CodegenBackend>> = SyncOnceCell::new();
257 let load = LOAD.get_or_init(|| {
258 #[cfg(feature = "llvm")]
259 const DEFAULT_CODEGEN_BACKEND: &str = "llvm";
261 #[cfg(not(feature = "llvm"))]
262 const DEFAULT_CODEGEN_BACKEND: &str = "cranelift";
264 match backend_name.unwrap_or(DEFAULT_CODEGEN_BACKEND) {
265 filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
266 #[cfg(feature = "llvm")]
267 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
268 backend_name => get_codegen_sysroot(maybe_sysroot, backend_name),
272 // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
273 // backend we hope that the backend links against the same rustc_driver version. If this is not
274 // the case, we get UB.
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_codegen_sysroot(
394 maybe_sysroot: &Option<PathBuf>,
396 ) -> fn() -> Box<dyn CodegenBackend> {
397 // For now we only allow this function to be called once as it'll dlopen a
398 // few things, which seems to work best if we only do that once. In
399 // general this assertion never trips due to the once guard in `get_codegen_backend`,
400 // but there's a few manual calls to this function in this file we protect
402 static LOADED: AtomicBool = AtomicBool::new(false);
404 !LOADED.fetch_or(true, Ordering::SeqCst),
405 "cannot load the default codegen backend twice"
408 let target = session::config::host_triple();
409 let sysroot_candidates = sysroot_candidates();
411 let sysroot = maybe_sysroot
413 .chain(sysroot_candidates.iter())
415 filesearch::make_target_lib_path(&sysroot, &target).with_file_name("codegen-backends")
418 info!("codegen backend candidate: {}", f.display());
421 let sysroot = sysroot.unwrap_or_else(|| {
422 let candidates = sysroot_candidates
424 .map(|p| p.display().to_string())
428 "failed to find a `codegen-backends` folder \
429 in the sysroot candidates:\n* {}",
432 early_error(ErrorOutputType::default(), &err);
434 info!("probing {} for a codegen backend", sysroot.display());
436 let d = sysroot.read_dir().unwrap_or_else(|e| {
438 "failed to load default codegen backend, couldn't \
443 early_error(ErrorOutputType::default(), &err);
446 let mut file: Option<PathBuf> = None;
448 let expected_names = &[
449 format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
450 format!("rustc_codegen_{}", backend_name),
452 for entry in d.filter_map(|e| e.ok()) {
453 let path = entry.path();
454 let filename = match path.file_name().and_then(|s| s.to_str()) {
458 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
461 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
462 if !expected_names.iter().any(|expected| expected == name) {
465 if let Some(ref prev) = file {
467 "duplicate codegen backends found\n\
474 early_error(ErrorOutputType::default(), &err);
476 file = Some(path.clone());
480 Some(ref s) => load_backend_from_dylib(s),
482 let err = format!("unsupported builtin codegen backend `{}`", backend_name);
483 early_error(ErrorOutputType::default(), &err);
488 pub(crate) fn check_attr_crate_type(
490 attrs: &[ast::Attribute],
491 lint_buffer: &mut LintBuffer,
493 // Unconditionally collect crate types from attributes to make them used
494 for a in attrs.iter() {
495 if sess.check_name(a, sym::crate_type) {
496 if let Some(n) = a.value_str() {
497 if categorize_crate_type(n).is_some() {
501 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
502 let span = spanned.span;
503 let lev_candidate = find_best_match_for_name(
504 &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
508 if let Some(candidate) = lev_candidate {
509 lint_buffer.buffer_lint_with_diagnostic(
510 lint::builtin::UNKNOWN_CRATE_TYPES,
513 "invalid `crate_type` value",
514 BuiltinLintDiagnostics::UnknownCrateTypes(
516 "did you mean".to_string(),
517 format!("\"{}\"", candidate),
521 lint_buffer.buffer_lint(
522 lint::builtin::UNKNOWN_CRATE_TYPES,
525 "invalid `crate_type` value",
534 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
535 (sym::rlib, CrateType::Rlib),
536 (sym::dylib, CrateType::Dylib),
537 (sym::cdylib, CrateType::Cdylib),
538 (sym::lib, config::default_lib_output()),
539 (sym::staticlib, CrateType::Staticlib),
540 (sym::proc_dash_macro, CrateType::ProcMacro),
541 (sym::bin, CrateType::Executable),
544 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
545 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
548 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
549 // Unconditionally collect crate types from attributes to make them used
550 let attr_types: Vec<CrateType> = attrs
553 if session.check_name(a, sym::crate_type) {
554 match a.value_str() {
555 Some(s) => categorize_crate_type(s),
564 // If we're generating a test executable, then ignore all other output
565 // styles at all other locations
566 if session.opts.test {
567 return vec![CrateType::Executable];
570 // Only check command line flags if present. If no types are specified by
571 // command line, then reuse the empty `base` Vec to hold the types that
572 // will be found in crate attributes.
573 let mut base = session.opts.crate_types.clone();
575 base.extend(attr_types);
577 base.push(output::default_output_for_target(session));
584 base.retain(|crate_type| {
585 let res = !output::invalid_output_for_target(session, *crate_type);
588 session.warn(&format!(
589 "dropping unsupported crate type `{}` for target `{}`",
590 *crate_type, session.opts.target_triple
600 pub fn build_output_filenames(
602 odir: &Option<PathBuf>,
603 ofile: &Option<PathBuf>,
604 attrs: &[ast::Attribute],
606 ) -> OutputFilenames {
609 // "-" as input file will cause the parser to read from stdin so we
610 // have to make up a name
611 // We want to toss everything after the final '.'
612 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
614 // If a crate name is present, we use it as the link name
619 .or_else(|| rustc_attr::find_crate_name(&sess, attrs).map(|n| n.to_string()))
620 .unwrap_or_else(|| input.filestem().to_owned());
622 OutputFilenames::new(
626 sess.opts.cg.extra_filename.clone(),
627 sess.opts.output_types.clone(),
631 Some(ref out_file) => {
632 let unnamed_output_types =
633 sess.opts.output_types.values().filter(|a| a.is_none()).count();
634 let ofile = if unnamed_output_types > 1 {
636 "due to multiple output types requested, the explicitly specified \
637 output file name will be adapted for each output type",
641 if !sess.opts.cg.extra_filename.is_empty() {
642 sess.warn("ignoring -C extra-filename flag due to -o flag");
644 Some(out_file.clone())
647 sess.warn("ignoring --out-dir flag due to -o flag");
650 OutputFilenames::new(
651 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
652 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
654 sess.opts.cg.extra_filename.clone(),
655 sess.opts.output_types.clone(),
661 #[cfg(not(target_os = "linux"))]
662 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
663 std::fs::rename(src, dst)
666 /// This function attempts to bypass the auto_da_alloc heuristic implemented by some filesystems
667 /// such as btrfs and ext4. When renaming over a file that already exists then they will "helpfully"
668 /// write back the source file before committing the rename in case a developer forgot some of
669 /// the fsyncs in the open/write/fsync(file)/rename/fsync(dir) dance for atomic file updates.
671 /// To avoid triggering this heuristic we delete the destination first, if it exists.
672 /// The cost of an extra syscall is much lower than getting descheduled for the sync IO.
673 #[cfg(target_os = "linux")]
674 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
675 let _ = std::fs::remove_file(dst);
676 std::fs::rename(src, dst)
679 /// Replaces function bodies with `loop {}` (an infinite loop). This gets rid of
680 /// all semantic errors in the body while still satisfying the return type,
681 /// except in certain cases, see below for more.
683 /// This pass is known as `everybody_loops`. Very punny.
685 /// As of March 2021, `everybody_loops` is only used for the
686 /// `-Z unpretty=everybody_loops` debugging option.
688 /// FIXME: Currently the `everybody_loops` transformation is not applied to:
689 /// * `const fn`; support could be added, but hasn't. Originally `const fn`
690 /// was skipped due to issue #43636 that `loop` was not supported for
691 /// const evaluation.
692 /// * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
693 /// Solving this may require `!` to implement every trait, which relies on the an even more
694 /// ambitious form of the closed RFC #1637. See also [#34511].
696 /// [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
697 pub struct ReplaceBodyWithLoop<'a, 'b> {
698 within_static_or_const: bool,
699 nested_blocks: Option<Vec<ast::Block>>,
700 resolver: &'a mut Resolver<'b>,
703 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
704 pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
705 ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver }
708 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
709 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
710 let old_blocks = self.nested_blocks.take();
711 let ret = action(self);
712 self.within_static_or_const = old_const;
713 self.nested_blocks = old_blocks;
717 fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
718 if let ast::FnRetTy::Ty(ref ty) = ret_ty {
719 fn involves_impl_trait(ty: &ast::Ty) -> bool {
721 ast::TyKind::ImplTrait(..) => true,
722 ast::TyKind::Slice(ref subty)
723 | ast::TyKind::Array(ref subty, _)
724 | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. })
725 | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. })
726 | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
727 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
728 ast::TyKind::Path(_, ref path) => {
729 path.segments.iter().any(|seg| match seg.args.as_deref() {
731 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
732 data.args.iter().any(|arg| match arg {
733 ast::AngleBracketedArg::Arg(arg) => match arg {
734 ast::GenericArg::Type(ty) => involves_impl_trait(ty),
735 ast::GenericArg::Lifetime(_)
736 | ast::GenericArg::Const(_) => false,
738 ast::AngleBracketedArg::Constraint(c) => match c.kind {
739 ast::AssocTyConstraintKind::Bound { .. } => true,
740 ast::AssocTyConstraintKind::Equality { ref ty } => {
741 involves_impl_trait(ty)
746 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
747 any_involves_impl_trait(data.inputs.iter())
748 || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
756 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
757 it.any(|subty| involves_impl_trait(subty))
760 involves_impl_trait(ty)
766 fn is_sig_const(sig: &ast::FnSig) -> bool {
767 matches!(sig.header.constness, ast::Const::Yes(_))
768 || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output)
772 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
773 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
774 let is_const = match i {
775 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
776 ast::ItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
779 self.run(is_const, |s| noop_visit_item_kind(i, s))
782 fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
783 let is_const = match i.kind {
784 ast::AssocItemKind::Const(..) => true,
785 ast::AssocItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
788 self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
791 fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
792 self.flat_map_trait_item(i)
795 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
796 self.run(true, |s| noop_visit_anon_const(c, s))
799 fn visit_block(&mut self, b: &mut P<ast::Block>) {
801 rules: ast::BlockCheckMode,
802 s: Option<ast::Stmt>,
803 resolver: &mut Resolver<'_>,
806 stmts: s.into_iter().collect(),
808 id: resolver.next_node_id(),
809 span: rustc_span::DUMMY_SP,
814 fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
815 let expr = P(ast::Expr {
816 id: resolver.next_node_id(),
817 kind: ast::ExprKind::Block(P(b), None),
818 span: rustc_span::DUMMY_SP,
819 attrs: AttrVec::new(),
824 id: resolver.next_node_id(),
825 kind: ast::StmtKind::Expr(expr),
826 span: rustc_span::DUMMY_SP,
830 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
831 let loop_expr = P(ast::Expr {
832 kind: ast::ExprKind::Loop(P(empty_block), None),
833 id: self.resolver.next_node_id(),
834 span: rustc_span::DUMMY_SP,
835 attrs: AttrVec::new(),
839 let loop_stmt = ast::Stmt {
840 id: self.resolver.next_node_id(),
841 span: rustc_span::DUMMY_SP,
842 kind: ast::StmtKind::Expr(loop_expr),
845 if self.within_static_or_const {
846 noop_visit_block(b, self)
848 visit_clobber(b.deref_mut(), |b| {
849 let mut stmts = vec![];
851 let old_blocks = self.nested_blocks.replace(vec![]);
853 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
855 // we put a Some in there earlier with that replace(), so this is valid
856 let new_blocks = self.nested_blocks.take().unwrap();
857 self.nested_blocks = old_blocks;
858 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
861 let mut new_block = ast::Block { stmts, ..b };
863 if let Some(old_blocks) = self.nested_blocks.as_mut() {
864 //push our fresh block onto the cache and yield an empty block with `loop {}`
865 if !new_block.stmts.is_empty() {
866 old_blocks.push(new_block);
869 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
871 //push `loop {}` onto the end of our fresh block and yield that
872 new_block.stmts.push(loop_stmt);
881 /// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)"
882 pub fn version_str() -> Option<&'static str> {
883 option_env!("CFG_VERSION")
886 /// Returns a version string such as "0.12.0-dev".
887 pub fn release_str() -> Option<&'static str> {
888 option_env!("CFG_RELEASE")
891 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
892 pub fn commit_hash_str() -> Option<&'static str> {
893 option_env!("CFG_VER_HASH")
896 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
897 pub fn commit_date_str() -> Option<&'static str> {
898 option_env!("CFG_VER_DATE")