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