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