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