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