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