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