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