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