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