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