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