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