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