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