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