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