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