]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/util.rs
PR feedback
[rust.git] / compiler / rustc_interface / src / util.rs
1 use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *};
2 use rustc_ast::ptr::P;
3 use rustc_ast::util::lev_distance::find_best_match_for_name;
4 use rustc_ast::{self as ast, AttrVec, BlockCheckMode};
5 use rustc_codegen_ssa::traits::CodegenBackend;
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 #[cfg(parallel_compiler)]
9 use rustc_data_structures::jobserver;
10 use rustc_data_structures::stable_hasher::StableHasher;
11 use rustc_data_structures::sync::Lrc;
12 use rustc_errors::registry::Registry;
13 use rustc_metadata::dynamic_lib::DynamicLibrary;
14 use rustc_resolve::{self, Resolver};
15 use rustc_session as session;
16 use rustc_session::config::{self, CrateType};
17 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
18 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
19 use rustc_session::parse::CrateConfig;
20 use rustc_session::CrateDisambiguator;
21 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
22 use rustc_span::edition::Edition;
23 use rustc_span::source_map::FileLoader;
24 use rustc_span::symbol::{sym, Symbol};
25 use smallvec::SmallVec;
26 use std::env;
27 use std::io::{self, Write};
28 use std::lazy::SyncOnceCell;
29 use std::mem;
30 use std::ops::DerefMut;
31 use std::path::{Path, PathBuf};
32 use std::sync::{Arc, Mutex, Once};
33 #[cfg(not(parallel_compiler))]
34 use std::{panic, thread};
35 use tracing::info;
36
37 /// Adds `target_feature = "..."` cfgs for a variety of platform
38 /// specific features (SSE, NEON etc.).
39 ///
40 /// This is performed by checking whether a set of permitted features
41 /// is available on the target machine, by querying LLVM.
42 pub fn add_configuration(
43     cfg: &mut CrateConfig,
44     sess: &mut Session,
45     codegen_backend: &dyn CodegenBackend,
46 ) {
47     let tf = sym::target_feature;
48
49     let target_features = codegen_backend.target_features(sess);
50     sess.target_features.extend(target_features.iter().cloned());
51
52     cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
53
54     if sess.crt_static(None) {
55         cfg.insert((tf, Some(sym::crt_dash_static)));
56     }
57 }
58
59 pub fn create_session(
60     sopts: config::Options,
61     cfg: FxHashSet<(String, Option<String>)>,
62     diagnostic_output: DiagnosticOutput,
63     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
64     input_path: Option<PathBuf>,
65     lint_caps: FxHashMap<lint::LintId, lint::Level>,
66     descriptions: Registry,
67 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
68     let codegen_backend = get_codegen_backend(&sopts);
69     // target_override is documented to be called before init(), so this is okay
70     let target_override = codegen_backend.target_override(&sopts);
71
72     let mut sess = session::build_session(
73         sopts,
74         input_path,
75         descriptions,
76         diagnostic_output,
77         lint_caps,
78         file_loader,
79         target_override,
80     );
81
82     codegen_backend.init(&sess);
83
84     let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
85     add_configuration(&mut cfg, &mut sess, &*codegen_backend);
86     sess.parse_sess.config = cfg;
87
88     (Lrc::new(sess), Lrc::new(codegen_backend))
89 }
90
91 const STACK_SIZE: usize = 8 * 1024 * 1024;
92
93 fn get_stack_size() -> Option<usize> {
94     // FIXME: Hacks on hacks. If the env is trying to override the stack size
95     // then *don't* set it explicitly.
96     env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
97 }
98
99 struct Sink(Arc<Mutex<Vec<u8>>>);
100 impl Write for Sink {
101     fn write(&mut self, data: &[u8]) -> io::Result<usize> {
102         Write::write(&mut *self.0.lock().unwrap(), data)
103     }
104     fn flush(&mut self) -> io::Result<()> {
105         Ok(())
106     }
107 }
108
109 /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need
110 /// for `'static` bounds.
111 #[cfg(not(parallel_compiler))]
112 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
113     struct Ptr(*mut ());
114     unsafe impl Send for Ptr {}
115     unsafe impl Sync for Ptr {}
116
117     let mut f = Some(f);
118     let run = Ptr(&mut f as *mut _ as *mut ());
119     let mut result = None;
120     let result_ptr = Ptr(&mut result as *mut _ as *mut ());
121
122     let thread = cfg.spawn(move || {
123         let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
124         let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
125         *result = Some(run());
126     });
127
128     match thread.unwrap().join() {
129         Ok(()) => result.unwrap(),
130         Err(p) => panic::resume_unwind(p),
131     }
132 }
133
134 #[cfg(not(parallel_compiler))]
135 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
136     edition: Edition,
137     _threads: usize,
138     stderr: &Option<Arc<Mutex<Vec<u8>>>>,
139     f: F,
140 ) -> R {
141     let mut cfg = thread::Builder::new().name("rustc".to_string());
142
143     if let Some(size) = get_stack_size() {
144         cfg = cfg.stack_size(size);
145     }
146
147     crate::callbacks::setup_callbacks();
148
149     let main_handler = move || {
150         rustc_span::with_session_globals(edition, || {
151             if let Some(stderr) = stderr {
152                 io::set_panic(Some(box Sink(stderr.clone())));
153             }
154             f()
155         })
156     };
157
158     scoped_thread(cfg, main_handler)
159 }
160
161 #[cfg(parallel_compiler)]
162 pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
163     edition: Edition,
164     threads: usize,
165     stderr: &Option<Arc<Mutex<Vec<u8>>>>,
166     f: F,
167 ) -> R {
168     use rustc_middle::ty;
169     crate::callbacks::setup_callbacks();
170
171     let mut config = rayon::ThreadPoolBuilder::new()
172         .thread_name(|_| "rustc".to_string())
173         .acquire_thread_handler(jobserver::acquire_thread)
174         .release_thread_handler(jobserver::release_thread)
175         .num_threads(threads)
176         .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
177
178     if let Some(size) = get_stack_size() {
179         config = config.stack_size(size);
180     }
181
182     let with_pool = move |pool: &rayon::ThreadPool| pool.install(move || f());
183
184     rustc_span::with_session_globals(edition, || {
185         rustc_span::SESSION_GLOBALS.with(|session_globals| {
186             // The main handler runs for each Rayon worker thread and sets up
187             // the thread local rustc uses. `session_globals` is captured and set
188             // on the new threads.
189             let main_handler = move |thread: rayon::ThreadBuilder| {
190                 rustc_span::SESSION_GLOBALS.set(session_globals, || {
191                     if let Some(stderr) = stderr {
192                         io::set_panic(Some(box Sink(stderr.clone())));
193                     }
194                     thread.run()
195                 })
196             };
197
198             config.build_scoped(main_handler, with_pool).unwrap()
199         })
200     })
201 }
202
203 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
204     let lib = DynamicLibrary::open(path).unwrap_or_else(|err| {
205         let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
206         early_error(ErrorOutputType::default(), &err);
207     });
208     unsafe {
209         match lib.symbol("__rustc_codegen_backend") {
210             Ok(f) => {
211                 mem::forget(lib);
212                 mem::transmute::<*mut u8, _>(f)
213             }
214             Err(e) => {
215                 let err = format!(
216                     "couldn't load codegen backend as it \
217                                    doesn't export the `__rustc_codegen_backend` \
218                                    symbol: {:?}",
219                     e
220                 );
221                 early_error(ErrorOutputType::default(), &err);
222             }
223         }
224     }
225 }
226
227 pub fn get_codegen_backend(sopts: &config::Options) -> Box<dyn CodegenBackend> {
228     static INIT: Once = Once::new();
229
230     static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
231
232     INIT.call_once(|| {
233         let codegen_name = sopts.debugging_opts.codegen_backend.as_deref().unwrap_or("llvm");
234         let backend = match codegen_name {
235             filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
236             codegen_name => get_builtin_codegen_backend(codegen_name),
237         };
238
239         unsafe {
240             LOAD = backend;
241         }
242     });
243     unsafe { LOAD() }
244 }
245
246 // This is used for rustdoc, but it uses similar machinery to codegen backend
247 // loading, so we leave the code here. It is potentially useful for other tools
248 // that want to invoke the rustc binary while linking to rustc as well.
249 pub fn rustc_path<'a>() -> Option<&'a Path> {
250     static RUSTC_PATH: SyncOnceCell<Option<PathBuf>> = SyncOnceCell::new();
251
252     const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
253
254     RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
255 }
256
257 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
258     sysroot_candidates().iter().find_map(|sysroot| {
259         let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
260             "rustc.exe"
261         } else {
262             "rustc"
263         });
264         candidate.exists().then_some(candidate)
265     })
266 }
267
268 fn sysroot_candidates() -> Vec<PathBuf> {
269     let target = session::config::host_triple();
270     let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
271     let path = current_dll_path().and_then(|s| s.canonicalize().ok());
272     if let Some(dll) = path {
273         // use `parent` twice to chop off the file name and then also the
274         // directory containing the dll which should be either `lib` or `bin`.
275         if let Some(path) = dll.parent().and_then(|p| p.parent()) {
276             // The original `path` pointed at the `rustc_driver` crate's dll.
277             // Now that dll should only be in one of two locations. The first is
278             // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
279             // other is the target's libdir, for example
280             // `$sysroot/lib/rustlib/$target/lib/*.dll`.
281             //
282             // We don't know which, so let's assume that if our `path` above
283             // ends in `$target` we *could* be in the target libdir, and always
284             // assume that we may be in the main libdir.
285             sysroot_candidates.push(path.to_owned());
286
287             if path.ends_with(target) {
288                 sysroot_candidates.extend(
289                     path.parent() // chop off `$target`
290                         .and_then(|p| p.parent()) // chop off `rustlib`
291                         .and_then(|p| p.parent()) // chop off `lib`
292                         .map(|s| s.to_owned()),
293                 );
294             }
295         }
296     }
297
298     return sysroot_candidates;
299
300     #[cfg(unix)]
301     fn current_dll_path() -> Option<PathBuf> {
302         use std::ffi::{CStr, OsStr};
303         use std::os::unix::prelude::*;
304
305         unsafe {
306             let addr = current_dll_path as usize as *mut _;
307             let mut info = mem::zeroed();
308             if libc::dladdr(addr, &mut info) == 0 {
309                 info!("dladdr failed");
310                 return None;
311             }
312             if info.dli_fname.is_null() {
313                 info!("dladdr returned null pointer");
314                 return None;
315             }
316             let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
317             let os = OsStr::from_bytes(bytes);
318             Some(PathBuf::from(os))
319         }
320     }
321
322     #[cfg(windows)]
323     fn current_dll_path() -> Option<PathBuf> {
324         use std::ffi::OsString;
325         use std::os::windows::prelude::*;
326         use std::ptr;
327
328         use winapi::um::libloaderapi::{
329             GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
330         };
331
332         unsafe {
333             let mut module = ptr::null_mut();
334             let r = GetModuleHandleExW(
335                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
336                 current_dll_path as usize as *mut _,
337                 &mut module,
338             );
339             if r == 0 {
340                 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
341                 return None;
342             }
343             let mut space = Vec::with_capacity(1024);
344             let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
345             if r == 0 {
346                 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
347                 return None;
348             }
349             let r = r as usize;
350             if r >= space.capacity() {
351                 info!("our buffer was too small? {}", io::Error::last_os_error());
352                 return None;
353             }
354             space.set_len(r);
355             let os = OsString::from_wide(&space);
356             Some(PathBuf::from(os))
357         }
358     }
359 }
360
361 pub fn get_builtin_codegen_backend(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
362     #[cfg(feature = "llvm")]
363     {
364         if backend_name == "llvm" {
365             return rustc_codegen_llvm::LlvmCodegenBackend::new;
366         }
367     }
368
369     let err = format!("unsupported builtin codegen backend `{}`", backend_name);
370     early_error(ErrorOutputType::default(), &err);
371 }
372
373 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
374     use std::hash::Hasher;
375
376     // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
377     // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
378     // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
379     // should still be safe enough to avoid collisions in practice.
380     let mut hasher = StableHasher::new();
381
382     let mut metadata = session.opts.cg.metadata.clone();
383     // We don't want the crate_disambiguator to dependent on the order
384     // -C metadata arguments, so sort them:
385     metadata.sort();
386     // Every distinct -C metadata value is only incorporated once:
387     metadata.dedup();
388
389     hasher.write(b"metadata");
390     for s in &metadata {
391         // Also incorporate the length of a metadata string, so that we generate
392         // different values for `-Cmetadata=ab -Cmetadata=c` and
393         // `-Cmetadata=a -Cmetadata=bc`
394         hasher.write_usize(s.len());
395         hasher.write(s.as_bytes());
396     }
397
398     // Also incorporate crate type, so that we don't get symbol conflicts when
399     // linking against a library of the same name, if this is an executable.
400     let is_exe = session.crate_types().contains(&CrateType::Executable);
401     hasher.write(if is_exe { b"exe" } else { b"lib" });
402
403     CrateDisambiguator::from(hasher.finish::<Fingerprint>())
404 }
405
406 pub(crate) fn check_attr_crate_type(
407     sess: &Session,
408     attrs: &[ast::Attribute],
409     lint_buffer: &mut LintBuffer,
410 ) {
411     // Unconditionally collect crate types from attributes to make them used
412     for a in attrs.iter() {
413         if sess.check_name(a, sym::crate_type) {
414             if let Some(n) = a.value_str() {
415                 if categorize_crate_type(n).is_some() {
416                     return;
417                 }
418
419                 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
420                     let span = spanned.span;
421                     let lev_candidate =
422                         find_best_match_for_name(CRATE_TYPES.iter().map(|(k, _)| k), n, None);
423                     if let Some(candidate) = lev_candidate {
424                         lint_buffer.buffer_lint_with_diagnostic(
425                             lint::builtin::UNKNOWN_CRATE_TYPES,
426                             ast::CRATE_NODE_ID,
427                             span,
428                             "invalid `crate_type` value",
429                             BuiltinLintDiagnostics::UnknownCrateTypes(
430                                 span,
431                                 "did you mean".to_string(),
432                                 format!("\"{}\"", candidate),
433                             ),
434                         );
435                     } else {
436                         lint_buffer.buffer_lint(
437                             lint::builtin::UNKNOWN_CRATE_TYPES,
438                             ast::CRATE_NODE_ID,
439                             span,
440                             "invalid `crate_type` value",
441                         );
442                     }
443                 }
444             }
445         }
446     }
447 }
448
449 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
450     (sym::rlib, CrateType::Rlib),
451     (sym::dylib, CrateType::Dylib),
452     (sym::cdylib, CrateType::Cdylib),
453     (sym::lib, config::default_lib_output()),
454     (sym::staticlib, CrateType::Staticlib),
455     (sym::proc_dash_macro, CrateType::ProcMacro),
456     (sym::bin, CrateType::Executable),
457 ];
458
459 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
460     Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
461 }
462
463 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
464     // Unconditionally collect crate types from attributes to make them used
465     let attr_types: Vec<CrateType> = attrs
466         .iter()
467         .filter_map(|a| {
468             if session.check_name(a, sym::crate_type) {
469                 match a.value_str() {
470                     Some(s) => categorize_crate_type(s),
471                     _ => None,
472                 }
473             } else {
474                 None
475             }
476         })
477         .collect();
478
479     // If we're generating a test executable, then ignore all other output
480     // styles at all other locations
481     if session.opts.test {
482         return vec![CrateType::Executable];
483     }
484
485     // Only check command line flags if present. If no types are specified by
486     // command line, then reuse the empty `base` Vec to hold the types that
487     // will be found in crate attributes.
488     let mut base = session.opts.crate_types.clone();
489     if base.is_empty() {
490         base.extend(attr_types);
491         if base.is_empty() {
492             base.push(output::default_output_for_target(session));
493         } else {
494             base.sort();
495             base.dedup();
496         }
497     }
498
499     base.retain(|crate_type| {
500         let res = !output::invalid_output_for_target(session, *crate_type);
501
502         if !res {
503             session.warn(&format!(
504                 "dropping unsupported crate type `{}` for target `{}`",
505                 *crate_type, session.opts.target_triple
506             ));
507         }
508
509         res
510     });
511
512     base
513 }
514
515 pub fn build_output_filenames(
516     input: &Input,
517     odir: &Option<PathBuf>,
518     ofile: &Option<PathBuf>,
519     attrs: &[ast::Attribute],
520     sess: &Session,
521 ) -> OutputFilenames {
522     match *ofile {
523         None => {
524             // "-" as input file will cause the parser to read from stdin so we
525             // have to make up a name
526             // We want to toss everything after the final '.'
527             let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
528
529             // If a crate name is present, we use it as the link name
530             let stem = sess
531                 .opts
532                 .crate_name
533                 .clone()
534                 .or_else(|| rustc_attr::find_crate_name(&sess, attrs).map(|n| n.to_string()))
535                 .unwrap_or_else(|| input.filestem().to_owned());
536
537             OutputFilenames::new(
538                 dirpath,
539                 stem,
540                 None,
541                 sess.opts.cg.extra_filename.clone(),
542                 sess.opts.output_types.clone(),
543             )
544         }
545
546         Some(ref out_file) => {
547             let unnamed_output_types =
548                 sess.opts.output_types.values().filter(|a| a.is_none()).count();
549             let ofile = if unnamed_output_types > 1 {
550                 sess.warn(
551                     "due to multiple output types requested, the explicitly specified \
552                      output file name will be adapted for each output type",
553                 );
554                 None
555             } else {
556                 if !sess.opts.cg.extra_filename.is_empty() {
557                     sess.warn("ignoring -C extra-filename flag due to -o flag");
558                 }
559                 Some(out_file.clone())
560             };
561             if *odir != None {
562                 sess.warn("ignoring --out-dir flag due to -o flag");
563             }
564
565             OutputFilenames::new(
566                 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
567                 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
568                 ofile,
569                 sess.opts.cg.extra_filename.clone(),
570                 sess.opts.output_types.clone(),
571             )
572         }
573     }
574 }
575
576 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
577 //
578 // FIXME: Currently the `everybody_loops` transformation is not applied to:
579 //  * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
580 //    waiting for miri to fix that.
581 //  * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
582 //    Solving this may require `!` to implement every trait, which relies on the an even more
583 //    ambitious form of the closed RFC #1637. See also [#34511].
584 //
585 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
586 pub struct ReplaceBodyWithLoop<'a, 'b> {
587     within_static_or_const: bool,
588     nested_blocks: Option<Vec<ast::Block>>,
589     resolver: &'a mut Resolver<'b>,
590 }
591
592 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
593     pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
594         ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver }
595     }
596
597     fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
598         let old_const = mem::replace(&mut self.within_static_or_const, is_const);
599         let old_blocks = self.nested_blocks.take();
600         let ret = action(self);
601         self.within_static_or_const = old_const;
602         self.nested_blocks = old_blocks;
603         ret
604     }
605
606     fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool {
607         if let ast::FnRetTy::Ty(ref ty) = ret_ty {
608             fn involves_impl_trait(ty: &ast::Ty) -> bool {
609                 match ty.kind {
610                     ast::TyKind::ImplTrait(..) => true,
611                     ast::TyKind::Slice(ref subty)
612                     | ast::TyKind::Array(ref subty, _)
613                     | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. })
614                     | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. })
615                     | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
616                     ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
617                     ast::TyKind::Path(_, ref path) => {
618                         path.segments.iter().any(|seg| match seg.args.as_deref() {
619                             None => false,
620                             Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
621                                 data.args.iter().any(|arg| match arg {
622                                     ast::AngleBracketedArg::Arg(arg) => match arg {
623                                         ast::GenericArg::Type(ty) => involves_impl_trait(ty),
624                                         ast::GenericArg::Lifetime(_)
625                                         | ast::GenericArg::Const(_) => false,
626                                     },
627                                     ast::AngleBracketedArg::Constraint(c) => match c.kind {
628                                         ast::AssocTyConstraintKind::Bound { .. } => true,
629                                         ast::AssocTyConstraintKind::Equality { ref ty } => {
630                                             involves_impl_trait(ty)
631                                         }
632                                     },
633                                 })
634                             }
635                             Some(&ast::GenericArgs::Parenthesized(ref data)) => {
636                                 any_involves_impl_trait(data.inputs.iter())
637                                     || ReplaceBodyWithLoop::should_ignore_fn(&data.output)
638                             }
639                         })
640                     }
641                     _ => false,
642                 }
643             }
644
645             fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
646                 it.any(|subty| involves_impl_trait(subty))
647             }
648
649             involves_impl_trait(ty)
650         } else {
651             false
652         }
653     }
654
655     fn is_sig_const(sig: &ast::FnSig) -> bool {
656         matches!(sig.header.constness, ast::Const::Yes(_))
657             || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output)
658     }
659 }
660
661 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
662     fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
663         let is_const = match i {
664             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
665             ast::ItemKind::Fn(_, ref sig, _, _) => Self::is_sig_const(sig),
666             _ => false,
667         };
668         self.run(is_const, |s| noop_visit_item_kind(i, s))
669     }
670
671     fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
672         let is_const = match i.kind {
673             ast::AssocItemKind::Const(..) => true,
674             ast::AssocItemKind::Fn(_, ref sig, _, _) => Self::is_sig_const(sig),
675             _ => false,
676         };
677         self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
678     }
679
680     fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
681         self.flat_map_trait_item(i)
682     }
683
684     fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
685         self.run(true, |s| noop_visit_anon_const(c, s))
686     }
687
688     fn visit_block(&mut self, b: &mut P<ast::Block>) {
689         fn stmt_to_block(
690             rules: ast::BlockCheckMode,
691             s: Option<ast::Stmt>,
692             resolver: &mut Resolver<'_>,
693         ) -> ast::Block {
694             ast::Block {
695                 stmts: s.into_iter().collect(),
696                 rules,
697                 id: resolver.next_node_id(),
698                 span: rustc_span::DUMMY_SP,
699                 tokens: None,
700             }
701         }
702
703         fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
704             let expr = P(ast::Expr {
705                 id: resolver.next_node_id(),
706                 kind: ast::ExprKind::Block(P(b), None),
707                 span: rustc_span::DUMMY_SP,
708                 attrs: AttrVec::new(),
709                 tokens: None,
710             });
711
712             ast::Stmt {
713                 id: resolver.next_node_id(),
714                 kind: ast::StmtKind::Expr(expr),
715                 span: rustc_span::DUMMY_SP,
716                 tokens: None,
717             }
718         }
719
720         let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
721         let loop_expr = P(ast::Expr {
722             kind: ast::ExprKind::Loop(P(empty_block), None),
723             id: self.resolver.next_node_id(),
724             span: rustc_span::DUMMY_SP,
725             attrs: AttrVec::new(),
726             tokens: None,
727         });
728
729         let loop_stmt = ast::Stmt {
730             id: self.resolver.next_node_id(),
731             span: rustc_span::DUMMY_SP,
732             kind: ast::StmtKind::Expr(loop_expr),
733             tokens: None,
734         };
735
736         if self.within_static_or_const {
737             noop_visit_block(b, self)
738         } else {
739             visit_clobber(b.deref_mut(), |b| {
740                 let mut stmts = vec![];
741                 for s in b.stmts {
742                     let old_blocks = self.nested_blocks.replace(vec![]);
743
744                     stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
745
746                     // we put a Some in there earlier with that replace(), so this is valid
747                     let new_blocks = self.nested_blocks.take().unwrap();
748                     self.nested_blocks = old_blocks;
749                     stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
750                 }
751
752                 let mut new_block = ast::Block { stmts, ..b };
753
754                 if let Some(old_blocks) = self.nested_blocks.as_mut() {
755                     //push our fresh block onto the cache and yield an empty block with `loop {}`
756                     if !new_block.stmts.is_empty() {
757                         old_blocks.push(new_block);
758                     }
759
760                     stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
761                 } else {
762                     //push `loop {}` onto the end of our fresh block and yield that
763                     new_block.stmts.push(loop_stmt);
764
765                     new_block
766                 }
767             })
768         }
769     }
770
771     // in general the pretty printer processes unexpanded code, so
772     // we override the default `visit_mac` method which panics.
773     fn visit_mac(&mut self, mac: &mut ast::MacCall) {
774         noop_visit_mac(mac, self)
775     }
776 }