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