2 use rustc::session::config::{Input, OutputFilenames, ErrorOutputType};
3 use rustc::session::{self, config, early_error, filesearch, Session, DiagnosticOutput};
4 use rustc::session::CrateDisambiguator;
7 use rustc_codegen_utils::codegen_backend::CodegenBackend;
8 #[cfg(parallel_compiler)]
9 use rustc_data_structures::jobserver;
10 use rustc_data_structures::sync::{Lock, Lrc};
11 use rustc_data_structures::stable_hasher::StableHasher;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc_data_structures::thin_vec::ThinVec;
14 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
15 use rustc_errors::registry::Registry;
16 use rustc_metadata::dynamic_lib::DynamicLibrary;
21 use rustc_resolve::{self, Resolver};
24 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
25 use std::io::{self, Write};
27 use std::path::{Path, PathBuf};
28 use std::sync::atomic::{AtomicBool, Ordering};
29 use std::sync::{Arc, Mutex, Once};
30 use std::ops::DerefMut;
31 use smallvec::SmallVec;
33 use syntax::mut_visit::{*, MutVisitor, visit_clobber};
34 use syntax::ast::BlockCheckMode;
35 use syntax::util::lev_distance::find_best_match_for_name;
36 use syntax::source_map::{FileLoader, RealFileLoader, SourceMap};
37 use syntax::symbol::{Symbol, sym};
38 use syntax::{self, ast, attr};
39 use syntax_expand::config::process_configure_mod;
40 use syntax_pos::edition::Edition;
41 #[cfg(not(parallel_compiler))]
42 use std::{thread, panic};
44 pub fn diagnostics_registry() -> Registry {
45 let mut all_errors = Vec::new();
46 all_errors.extend_from_slice(&rustc::error_codes::DIAGNOSTICS);
47 all_errors.extend_from_slice(&rustc_typeck::error_codes::DIAGNOSTICS);
48 all_errors.extend_from_slice(&rustc_resolve::error_codes::DIAGNOSTICS);
49 all_errors.extend_from_slice(&rustc_privacy::error_codes::DIAGNOSTICS);
50 // FIXME: need to figure out a way to get these back in here
51 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
52 all_errors.extend_from_slice(&rustc_metadata::error_codes::DIAGNOSTICS);
53 all_errors.extend_from_slice(&rustc_parse::error_codes::DIAGNOSTICS);
54 all_errors.extend_from_slice(&rustc_passes::error_codes::DIAGNOSTICS);
55 all_errors.extend_from_slice(&rustc_plugin::error_codes::DIAGNOSTICS);
56 all_errors.extend_from_slice(&rustc_mir::error_codes::DIAGNOSTICS);
57 all_errors.extend_from_slice(&syntax::error_codes::DIAGNOSTICS);
59 Registry::new(&all_errors)
62 /// Adds `target_feature = "..."` cfgs for a variety of platform
63 /// specific features (SSE, NEON etc.).
65 /// This is performed by checking whether a whitelisted set of
66 /// features is available on the target machine, by querying LLVM.
67 pub fn add_configuration(
68 cfg: &mut ast::CrateConfig,
70 codegen_backend: &dyn CodegenBackend,
72 let tf = sym::target_feature;
76 .target_features(sess)
78 .map(|feat| (tf, Some(feat))),
81 if sess.crt_static_feature() {
82 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
86 pub fn create_session(
87 sopts: config::Options,
88 cfg: FxHashSet<(String, Option<String>)>,
89 diagnostic_output: DiagnosticOutput,
90 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
91 input_path: Option<PathBuf>,
92 lint_caps: FxHashMap<lint::LintId, lint::Level>,
93 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) {
94 let descriptions = diagnostics_registry();
96 let loader = file_loader.unwrap_or(box RealFileLoader);
97 let source_map = Lrc::new(SourceMap::with_file_loader(
99 sopts.file_path_mapping(),
101 let mut sess = session::build_session_with_source_map(
108 process_configure_mod,
111 let codegen_backend = get_codegen_backend(&sess);
113 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
114 add_configuration(&mut cfg, &sess, &*codegen_backend);
115 sess.parse_sess.config = cfg;
117 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
120 // Temporarily have stack size set to 32MB to deal with various crates with long method
121 // chains or deep syntax trees, except when on Haiku.
122 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
123 #[cfg(not(target_os = "haiku"))]
124 const STACK_SIZE: usize = 32 * 1024 * 1024;
126 #[cfg(target_os = "haiku")]
127 const STACK_SIZE: usize = 16 * 1024 * 1024;
129 fn get_stack_size() -> Option<usize> {
130 // FIXME: Hacks on hacks. If the env is trying to override the stack size
131 // then *don't* set it explicitly.
132 if env::var_os("RUST_MIN_STACK").is_none() {
139 struct Sink(Arc<Mutex<Vec<u8>>>);
140 impl Write for Sink {
141 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
142 Write::write(&mut *self.0.lock().unwrap(), data)
144 fn flush(&mut self) -> io::Result<()> { Ok(()) }
147 #[cfg(not(parallel_compiler))]
148 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
150 unsafe impl Send for Ptr {}
151 unsafe impl Sync for Ptr {}
154 let run = Ptr(&mut f as *mut _ as *mut ());
155 let mut result = None;
156 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
158 let thread = cfg.spawn(move || {
159 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
160 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
161 *result = Some(run());
164 match thread.unwrap().join() {
165 Ok(()) => result.unwrap(),
166 Err(p) => panic::resume_unwind(p),
170 #[cfg(not(parallel_compiler))]
171 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
174 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
177 let mut cfg = thread::Builder::new().name("rustc".to_string());
179 if let Some(size) = get_stack_size() {
180 cfg = cfg.stack_size(size);
183 scoped_thread(cfg, || {
184 syntax::with_globals(edition, || {
185 ty::tls::GCX_PTR.set(&Lock::new(0), || {
186 if let Some(stderr) = stderr {
187 io::set_panic(Some(box Sink(stderr.clone())));
189 ty::tls::with_thread_locals(|| f())
195 #[cfg(parallel_compiler)]
196 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
199 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
202 use rayon::{ThreadBuilder, ThreadPool, ThreadPoolBuilder};
204 let gcx_ptr = &Lock::new(0);
206 let mut config = ThreadPoolBuilder::new()
207 .thread_name(|_| "rustc".to_string())
208 .acquire_thread_handler(jobserver::acquire_thread)
209 .release_thread_handler(jobserver::release_thread)
210 .num_threads(threads)
211 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
213 if let Some(size) = get_stack_size() {
214 config = config.stack_size(size);
217 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
219 syntax::with_globals(edition, || {
220 syntax::GLOBALS.with(|syntax_globals| {
221 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
222 // The main handler runs for each Rayon worker thread and sets up
223 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
224 // captured and set on the new threads. ty::tls::with_thread_locals sets up
225 // thread local callbacks from libsyntax
226 let main_handler = move |thread: ThreadBuilder| {
227 syntax::GLOBALS.set(syntax_globals, || {
228 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
229 if let Some(stderr) = stderr {
230 io::set_panic(Some(box Sink(stderr.clone())));
232 ty::tls::with_thread_locals(|| {
233 ty::tls::GCX_PTR.set(gcx_ptr, || thread.run())
239 config.build_scoped(main_handler, with_pool).unwrap()
245 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
246 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
247 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
248 early_error(ErrorOutputType::default(), &err);
251 match lib.symbol("__rustc_codegen_backend") {
254 mem::transmute::<*mut u8, _>(f)
257 let err = format!("couldn't load codegen backend as it \
258 doesn't export the `__rustc_codegen_backend` \
260 early_error(ErrorOutputType::default(), &err);
266 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
267 static INIT: Once = Once::new();
269 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
272 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
273 .unwrap_or(&sess.target.target.options.codegen_backend);
274 let backend = match &codegen_name[..] {
275 filename if filename.contains(".") => {
276 load_backend_from_dylib(filename.as_ref())
278 codegen_name => get_codegen_sysroot(codegen_name),
285 let backend = unsafe { LOAD() };
290 // This is used for rustdoc, but it uses similar machinery to codegen backend
291 // loading, so we leave the code here. It is potentially useful for other tools
292 // that want to invoke the rustc binary while linking to rustc as well.
293 pub fn rustc_path<'a>() -> Option<&'a Path> {
294 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
295 once_cell::sync::OnceCell::new();
297 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
299 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
302 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
303 sysroot_candidates().iter()
304 .filter_map(|sysroot| {
305 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
310 if candidate.exists() {
319 fn sysroot_candidates() -> Vec<PathBuf> {
320 let target = session::config::host_triple();
321 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
322 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
323 if let Some(dll) = path {
324 // use `parent` twice to chop off the file name and then also the
325 // directory containing the dll which should be either `lib` or `bin`.
326 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
327 // The original `path` pointed at the `rustc_driver` crate's dll.
328 // Now that dll should only be in one of two locations. The first is
329 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
330 // other is the target's libdir, for example
331 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
333 // We don't know which, so let's assume that if our `path` above
334 // ends in `$target` we *could* be in the target libdir, and always
335 // assume that we may be in the main libdir.
336 sysroot_candidates.push(path.to_owned());
338 if path.ends_with(target) {
339 sysroot_candidates.extend(path.parent() // chop off `$target`
340 .and_then(|p| p.parent()) // chop off `rustlib`
341 .and_then(|p| p.parent()) // chop off `lib`
342 .map(|s| s.to_owned()));
347 return sysroot_candidates;
350 fn current_dll_path() -> Option<PathBuf> {
351 use std::ffi::{OsStr, CStr};
352 use std::os::unix::prelude::*;
355 let addr = current_dll_path as usize as *mut _;
356 let mut info = mem::zeroed();
357 if libc::dladdr(addr, &mut info) == 0 {
358 info!("dladdr failed");
361 if info.dli_fname.is_null() {
362 info!("dladdr returned null pointer");
365 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
366 let os = OsStr::from_bytes(bytes);
367 Some(PathBuf::from(os))
372 fn current_dll_path() -> Option<PathBuf> {
373 use std::ffi::OsString;
374 use std::os::windows::prelude::*;
377 fn GetModuleHandleExW(dwFlags: u32,
379 phModule: *mut usize) -> i32;
380 fn GetModuleFileNameW(hModule: usize,
381 lpFilename: *mut u16,
385 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
389 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
390 current_dll_path as usize,
393 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
396 let mut space = Vec::with_capacity(1024);
397 let r = GetModuleFileNameW(module,
399 space.capacity() as u32);
401 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
405 if r >= space.capacity() {
406 info!("our buffer was too small? {}",
407 io::Error::last_os_error());
411 let os = OsString::from_wide(&space);
412 Some(PathBuf::from(os))
417 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
418 // For now we only allow this function to be called once as it'll dlopen a
419 // few things, which seems to work best if we only do that once. In
420 // general this assertion never trips due to the once guard in `get_codegen_backend`,
421 // but there's a few manual calls to this function in this file we protect
423 static LOADED: AtomicBool = AtomicBool::new(false);
424 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
425 "cannot load the default codegen backend twice");
427 let target = session::config::host_triple();
428 let sysroot_candidates = sysroot_candidates();
430 let sysroot = sysroot_candidates.iter()
432 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
433 sysroot.join(libdir).with_file_name(
434 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
437 info!("codegen backend candidate: {}", f.display());
441 let sysroot = sysroot.unwrap_or_else(|| {
442 let candidates = sysroot_candidates.iter()
443 .map(|p| p.display().to_string())
446 let err = format!("failed to find a `codegen-backends` folder \
447 in the sysroot candidates:\n* {}", candidates);
448 early_error(ErrorOutputType::default(), &err);
450 info!("probing {} for a codegen backend", sysroot.display());
452 let d = sysroot.read_dir().unwrap_or_else(|e| {
453 let err = format!("failed to load default codegen backend, couldn't \
454 read `{}`: {}", sysroot.display(), e);
455 early_error(ErrorOutputType::default(), &err);
458 let mut file: Option<PathBuf> = None;
460 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
461 for entry in d.filter_map(|e| e.ok()) {
462 let path = entry.path();
463 let filename = match path.file_name().and_then(|s| s.to_str()) {
467 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
470 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
471 if name != expected_name {
474 if let Some(ref prev) = file {
475 let err = format!("duplicate codegen backends found\n\
478 ", prev.display(), path.display());
479 early_error(ErrorOutputType::default(), &err);
481 file = Some(path.clone());
485 Some(ref s) => return load_backend_from_dylib(s),
487 let err = format!("failed to load default codegen backend for `{}`, \
488 no appropriate codegen dylib found in `{}`",
489 backend_name, sysroot.display());
490 early_error(ErrorOutputType::default(), &err);
496 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
497 use std::hash::Hasher;
499 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
500 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
501 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
502 // should still be safe enough to avoid collisions in practice.
503 let mut hasher = StableHasher::new();
505 let mut metadata = session.opts.cg.metadata.clone();
506 // We don't want the crate_disambiguator to dependent on the order
507 // -C metadata arguments, so sort them:
509 // Every distinct -C metadata value is only incorporated once:
512 hasher.write(b"metadata");
514 // Also incorporate the length of a metadata string, so that we generate
515 // different values for `-Cmetadata=ab -Cmetadata=c` and
516 // `-Cmetadata=a -Cmetadata=bc`
517 hasher.write_usize(s.len());
518 hasher.write(s.as_bytes());
521 // Also incorporate crate type, so that we don't get symbol conflicts when
522 // linking against a library of the same name, if this is an executable.
526 .contains(&config::CrateType::Executable);
527 hasher.write(if is_exe { b"exe" } else { b"lib" });
529 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
532 pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut lint::LintBuffer) {
533 // Unconditionally collect crate types from attributes to make them used
534 for a in attrs.iter() {
535 if a.check_name(sym::crate_type) {
536 if let Some(n) = a.value_str() {
537 if let Some(_) = categorize_crate_type(n) {
541 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
542 let span = spanned.span;
543 let lev_candidate = find_best_match_for_name(
544 CRATE_TYPES.iter().map(|(k, _)| k),
548 if let Some(candidate) = lev_candidate {
549 lint_buffer.buffer_lint_with_diagnostic(
550 lint::builtin::UNKNOWN_CRATE_TYPES,
553 "invalid `crate_type` value",
554 lint::builtin::BuiltinLintDiagnostics::
557 "did you mean".to_string(),
558 format!("\"{}\"", candidate)
562 lint_buffer.buffer_lint(
563 lint::builtin::UNKNOWN_CRATE_TYPES,
566 "invalid `crate_type` value"
575 const CRATE_TYPES: &[(Symbol, config::CrateType)] = &[
576 (sym::rlib, config::CrateType::Rlib),
577 (sym::dylib, config::CrateType::Dylib),
578 (sym::cdylib, config::CrateType::Cdylib),
579 (sym::lib, config::default_lib_output()),
580 (sym::staticlib, config::CrateType::Staticlib),
581 (sym::proc_dash_macro, config::CrateType::ProcMacro),
582 (sym::bin, config::CrateType::Executable),
585 fn categorize_crate_type(s: Symbol) -> Option<config::CrateType> {
586 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
589 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
590 // Unconditionally collect crate types from attributes to make them used
591 let attr_types: Vec<config::CrateType> = attrs
594 if a.check_name(sym::crate_type) {
595 match a.value_str() {
596 Some(s) => categorize_crate_type(s),
605 // If we're generating a test executable, then ignore all other output
606 // styles at all other locations
607 if session.opts.test {
608 return vec![config::CrateType::Executable];
611 // Only check command line flags if present. If no types are specified by
612 // command line, then reuse the empty `base` Vec to hold the types that
613 // will be found in crate attributes.
614 let mut base = session.opts.crate_types.clone();
616 base.extend(attr_types);
618 base.push(::rustc_codegen_utils::link::default_output_for_target(
627 base.retain(|crate_type| {
628 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
631 session.warn(&format!(
632 "dropping unsupported crate type `{}` for target `{}`",
633 *crate_type, session.opts.target_triple
643 pub fn build_output_filenames(
645 odir: &Option<PathBuf>,
646 ofile: &Option<PathBuf>,
647 attrs: &[ast::Attribute],
649 ) -> OutputFilenames {
652 // "-" as input file will cause the parser to read from stdin so we
653 // have to make up a name
654 // We want to toss everything after the final '.'
655 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
657 // If a crate name is present, we use it as the link name
661 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
662 .unwrap_or_else(|| input.filestem().to_owned());
665 out_directory: dirpath,
667 single_output_file: None,
668 extra: sess.opts.cg.extra_filename.clone(),
669 outputs: sess.opts.output_types.clone(),
673 Some(ref out_file) => {
674 let unnamed_output_types = sess.opts
677 .filter(|a| a.is_none())
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");
696 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
697 out_filestem: out_file
703 single_output_file: ofile,
704 extra: sess.opts.cg.extra_filename.clone(),
705 outputs: sess.opts.output_types.clone(),
711 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
713 // FIXME: Currently the `everybody_loops` transformation is not applied to:
714 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
715 // waiting for miri to fix that.
716 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
717 // Solving this may require `!` to implement every trait, which relies on the an even more
718 // ambitious form of the closed RFC #1637. See also [#34511].
720 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
721 pub struct ReplaceBodyWithLoop<'a, 'b> {
722 within_static_or_const: bool,
723 nested_blocks: Option<Vec<ast::Block>>,
724 resolver: &'a mut Resolver<'b>,
727 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
728 pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
729 ReplaceBodyWithLoop {
730 within_static_or_const: false,
736 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
737 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
738 let old_blocks = self.nested_blocks.take();
739 let ret = action(self);
740 self.within_static_or_const = old_const;
741 self.nested_blocks = old_blocks;
745 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
746 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
747 fn involves_impl_trait(ty: &ast::Ty) -> bool {
749 ast::TyKind::ImplTrait(..) => true,
750 ast::TyKind::Slice(ref subty) |
751 ast::TyKind::Array(ref subty, _) |
752 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
753 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
754 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
755 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
756 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
757 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
759 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
760 let types = data.args.iter().filter_map(|arg| match arg {
761 ast::GenericArg::Type(ty) => Some(ty),
764 any_involves_impl_trait(types.into_iter()) ||
765 data.constraints.iter().any(|c| {
767 ast::AssocTyConstraintKind::Bound { .. } => true,
768 ast::AssocTyConstraintKind::Equality { ref ty } =>
769 involves_impl_trait(ty),
773 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
774 any_involves_impl_trait(data.inputs.iter()) ||
775 any_involves_impl_trait(data.output.iter())
783 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
784 it.any(|subty| involves_impl_trait(subty))
787 involves_impl_trait(ty)
793 fn is_sig_const(sig: &ast::FnSig) -> bool {
794 sig.header.constness.node == ast::Constness::Const ||
795 ReplaceBodyWithLoop::should_ignore_fn(&sig.decl)
799 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
800 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
801 let is_const = match i {
802 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
803 ast::ItemKind::Fn(ref sig, _, _) => Self::is_sig_const(sig),
806 self.run(is_const, |s| noop_visit_item_kind(i, s))
809 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
810 let is_const = match i.kind {
811 ast::TraitItemKind::Const(..) => true,
812 ast::TraitItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
815 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
818 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
819 let is_const = match i.kind {
820 ast::ImplItemKind::Const(..) => true,
821 ast::ImplItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
824 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
827 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
828 self.run(true, |s| noop_visit_anon_const(c, s))
831 fn visit_block(&mut self, b: &mut P<ast::Block>) {
832 fn stmt_to_block(rules: ast::BlockCheckMode,
833 s: Option<ast::Stmt>,
834 resolver: &mut Resolver<'_>) -> ast::Block {
836 stmts: s.into_iter().collect(),
838 id: resolver.next_node_id(),
839 span: syntax_pos::DUMMY_SP,
843 fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
844 let expr = P(ast::Expr {
845 id: resolver.next_node_id(),
846 kind: ast::ExprKind::Block(P(b), None),
847 span: syntax_pos::DUMMY_SP,
848 attrs: ThinVec::new(),
852 id: resolver.next_node_id(),
853 kind: ast::StmtKind::Expr(expr),
854 span: syntax_pos::DUMMY_SP,
858 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
859 let loop_expr = P(ast::Expr {
860 kind: ast::ExprKind::Loop(P(empty_block), None),
861 id: self.resolver.next_node_id(),
862 span: syntax_pos::DUMMY_SP,
863 attrs: ThinVec::new(),
866 let loop_stmt = ast::Stmt {
867 id: self.resolver.next_node_id(),
868 span: syntax_pos::DUMMY_SP,
869 kind: ast::StmtKind::Expr(loop_expr),
872 if self.within_static_or_const {
873 noop_visit_block(b, self)
875 visit_clobber(b.deref_mut(), |b| {
876 let mut stmts = vec![];
878 let old_blocks = self.nested_blocks.replace(vec![]);
880 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
882 // we put a Some in there earlier with that replace(), so this is valid
883 let new_blocks = self.nested_blocks.take().unwrap();
884 self.nested_blocks = old_blocks;
885 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
888 let mut new_block = ast::Block {
893 if let Some(old_blocks) = self.nested_blocks.as_mut() {
894 //push our fresh block onto the cache and yield an empty block with `loop {}`
895 if !new_block.stmts.is_empty() {
896 old_blocks.push(new_block);
899 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
901 //push `loop {}` onto the end of our fresh block and yield that
902 new_block.stmts.push(loop_stmt);
910 // in general the pretty printer processes unexpanded code, so
911 // we override the default `visit_mac` method which panics.
912 fn visit_mac(&mut self, mac: &mut ast::Mac) {
913 noop_visit_mac(mac, self)