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