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