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