]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/passes.rs
Inline the rest of box_region
[rust.git] / compiler / rustc_interface / src / passes.rs
1 use crate::interface::{Compiler, Result};
2 use crate::proc_macro_decls;
3 use crate::util;
4
5 use rustc_ast::mut_visit::MutVisitor;
6 use rustc_ast::{self as ast, visit};
7 use rustc_codegen_ssa::back::link::emit_metadata;
8 use rustc_codegen_ssa::traits::CodegenBackend;
9 use rustc_data_structures::parallel;
10 use rustc_data_structures::steal::Steal;
11 use rustc_data_structures::sync::{par_iter, Lrc, OnceCell, ParallelIterator, WorkerLocal};
12 use rustc_data_structures::temp_dir::MaybeTempDir;
13 use rustc_errors::{ErrorReported, PResult};
14 use rustc_expand::base::ExtCtxt;
15 use rustc_hir::def_id::LOCAL_CRATE;
16 use rustc_hir::Crate;
17 use rustc_lint::LintStore;
18 use rustc_metadata::creader::CStore;
19 use rustc_middle::arena::Arena;
20 use rustc_middle::dep_graph::DepGraph;
21 use rustc_middle::middle;
22 use rustc_middle::middle::cstore::{CrateStore, MetadataLoader, MetadataLoaderDyn};
23 use rustc_middle::ty::query::Providers;
24 use rustc_middle::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
25 use rustc_mir as mir;
26 use rustc_mir_build as mir_build;
27 use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
28 use rustc_passes::{self, hir_stats, layout_test};
29 use rustc_plugin_impl as plugin;
30 use rustc_query_impl::Queries as TcxQueries;
31 use rustc_resolve::{Resolver, ResolverArenas};
32 use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType, PpMode, PpSourceMode};
33 use rustc_session::lint;
34 use rustc_session::output::{filename_for_input, filename_for_metadata};
35 use rustc_session::search_paths::PathKind;
36 use rustc_session::Session;
37 use rustc_span::symbol::{Ident, Symbol};
38 use rustc_trait_selection::traits;
39 use rustc_typeck as typeck;
40 use tracing::{info, warn};
41
42 use rustc_serialize::json;
43 use tempfile::Builder as TempFileBuilder;
44
45 use std::any::Any;
46 use std::cell::RefCell;
47 use std::ffi::OsString;
48 use std::io::{self, BufWriter, Write};
49 use std::lazy::SyncLazy;
50 use std::marker::PhantomData;
51 use std::ops::{Generator, GeneratorState};
52 use std::path::PathBuf;
53 use std::pin::Pin;
54 use std::rc::Rc;
55 use std::{env, fs, iter};
56
57 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
58     let krate = sess.time("parse_crate", || match input {
59         Input::File(file) => parse_crate_from_file(file, &sess.parse_sess),
60         Input::Str { input, name } => {
61             parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
62         }
63     })?;
64
65     if sess.opts.debugging_opts.ast_json_noexpand {
66         println!("{}", json::as_json(&krate));
67     }
68
69     if sess.opts.debugging_opts.input_stats {
70         eprintln!("Lines of code:             {}", sess.source_map().count_lines());
71         eprintln!("Pre-expansion node count:  {}", count_nodes(&krate));
72     }
73
74     if let Some(ref s) = sess.opts.debugging_opts.show_span {
75         rustc_ast_passes::show_span::run(sess.diagnostic(), s, &krate);
76     }
77
78     if sess.opts.debugging_opts.hir_stats {
79         hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
80     }
81
82     Ok(krate)
83 }
84
85 fn count_nodes(krate: &ast::Crate) -> usize {
86     let mut counter = rustc_ast_passes::node_count::NodeCounter::new();
87     visit::walk_crate(&mut counter, krate);
88     counter.count
89 }
90
91 #[derive(Copy, Clone)]
92 pub struct AccessAction(*mut dyn FnMut());
93
94 impl AccessAction {
95     pub fn get(self) -> *mut dyn FnMut() {
96         self.0
97     }
98 }
99
100 #[derive(Copy, Clone)]
101 pub enum Action {
102     Initial,
103     Access(AccessAction),
104     Complete,
105 }
106
107 pub struct PinnedGenerator<I, A, R> {
108     generator: Pin<Box<dyn Generator<Action, Yield = YieldType<I, A>, Return = R>>>,
109 }
110
111 impl<I, A, R> PinnedGenerator<I, A, R> {
112     pub fn new<T: Generator<Action, Yield = YieldType<I, A>, Return = R> + 'static>(
113         generator: T,
114     ) -> (I, Self) {
115         let mut result = PinnedGenerator { generator: Box::pin(generator) };
116
117         // Run it to the first yield to set it up
118         let init = match Pin::new(&mut result.generator).resume(Action::Initial) {
119             GeneratorState::Yielded(YieldType::Initial(y)) => y,
120             _ => panic!(),
121         };
122
123         (init, result)
124     }
125
126     pub unsafe fn access(&mut self, closure: *mut dyn FnMut()) {
127         // Call the generator, which in turn will call the closure
128         if let GeneratorState::Complete(_) =
129             Pin::new(&mut self.generator).resume(Action::Access(AccessAction(closure)))
130         {
131             panic!()
132         }
133     }
134
135     pub fn complete(&mut self) -> R {
136         // Tell the generator we want it to complete, consuming it and yielding a result
137         let result = Pin::new(&mut self.generator).resume(Action::Complete);
138         if let GeneratorState::Complete(r) = result { r } else { panic!() }
139     }
140 }
141
142 #[derive(PartialEq)]
143 pub struct Marker<T>(PhantomData<T>);
144
145 impl<T> Marker<T> {
146     pub unsafe fn new() -> Self {
147         Marker(PhantomData)
148     }
149 }
150
151 pub enum YieldType<I, A> {
152     Initial(I),
153     Accessor(Marker<A>),
154 }
155
156 pub struct BoxedResolver(
157     PinnedGenerator<Result<ast::Crate>, fn(&mut Resolver<'_>), ResolverOutputs>,
158 );
159
160 impl BoxedResolver {
161     fn new<T>(generator: T) -> (Result<ast::Crate>, Self)
162     where
163         T: ::std::ops::Generator<
164                 Action,
165                 Yield = YieldType<Result<ast::Crate>, fn(&mut Resolver<'_>)>,
166                 Return = ResolverOutputs,
167             > + 'static,
168     {
169         let (initial, pinned) = PinnedGenerator::new(generator);
170         (initial, BoxedResolver(pinned))
171     }
172
173     pub fn access<F: FnOnce(&mut Resolver<'_>) -> R, R>(&mut self, f: F) -> R {
174         // Turn the FnOnce closure into *mut dyn FnMut()
175         // so we can pass it in to the generator
176         let mut r = None;
177         let mut f = Some(f);
178         let mut_f: &mut dyn FnMut(&mut Resolver<'_>) = &mut |resolver| {
179             let f = f.take().unwrap();
180             r = Some(f(resolver));
181         };
182         let mut_f = mut_f as *mut dyn FnMut(&mut Resolver<'_>);
183
184         // Get the generator to call our closure
185         unsafe {
186             self.0.access(::std::mem::transmute(mut_f));
187         }
188
189         // Unwrap the result
190         r.unwrap()
191     }
192
193     pub fn complete(mut self) -> ResolverOutputs {
194         self.0.complete()
195     }
196
197     fn initial_yield(
198         value: Result<ast::Crate>,
199     ) -> YieldType<Result<ast::Crate>, fn(&mut Resolver<'_>)> {
200         YieldType::Initial(value)
201     }
202 }
203
204 /// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
205 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
206 /// harness if one is to be provided, injection of a dependency on the
207 /// standard library and prelude, and name resolution.
208 ///
209 /// Returns [`None`] if we're aborting after handling -W help.
210 pub fn configure_and_expand(
211     sess: Lrc<Session>,
212     lint_store: Lrc<LintStore>,
213     metadata_loader: Box<MetadataLoaderDyn>,
214     krate: ast::Crate,
215     crate_name: &str,
216 ) -> Result<(ast::Crate, BoxedResolver)> {
217     tracing::trace!("configure_and_expand");
218     // Currently, we ignore the name resolution data structures for the purposes of dependency
219     // tracking. Instead we will run name resolution and include its output in the hash of each
220     // item, much like we do for macro expansion. In other words, the hash reflects not just
221     // its contents but the results of name resolution on those contents. Hopefully we'll push
222     // this back at some point.
223     let crate_name = crate_name.to_string();
224     let (result, resolver) = BoxedResolver::new(static move |mut action| {
225         let _ = action;
226         let sess = &*sess;
227         let resolver_arenas = Resolver::arenas();
228         let res = configure_and_expand_inner(
229             sess,
230             &lint_store,
231             krate,
232             &crate_name,
233             &resolver_arenas,
234             &*metadata_loader,
235         );
236         let mut resolver = match res {
237             Err(v) => {
238                 yield BoxedResolver::initial_yield(Err(v));
239                 panic!()
240             }
241             Ok((krate, resolver)) => {
242                 action = yield BoxedResolver::initial_yield(Ok(krate));
243                 resolver
244             }
245         };
246
247         loop {
248             match action {
249                 Action::Access(accessor) => {
250                     let accessor: &mut dyn FnMut(&mut Resolver<'_>) =
251                         unsafe { ::std::mem::transmute(accessor.get()) };
252                     (*accessor)(&mut resolver);
253                     unsafe {
254                         let marker = Marker::<fn(&mut Resolver<'_>)>::new();
255                         action = yield YieldType::Accessor(marker);
256                     };
257                 }
258                 Action::Complete => break,
259                 Action::Initial => {
260                     panic!("unexpected box_region action: Initial")
261                 }
262             }
263         }
264
265         resolver.into_outputs()
266     });
267     result.map(|k| (k, resolver))
268 }
269
270 impl BoxedResolver {
271     pub fn to_resolver_outputs(resolver: Rc<RefCell<BoxedResolver>>) -> ResolverOutputs {
272         match Rc::try_unwrap(resolver) {
273             Ok(resolver) => resolver.into_inner().complete(),
274             Err(resolver) => resolver.borrow_mut().access(|resolver| resolver.clone_outputs()),
275         }
276     }
277 }
278
279 pub fn register_plugins<'a>(
280     sess: &'a Session,
281     metadata_loader: &'a dyn MetadataLoader,
282     register_lints: impl Fn(&Session, &mut LintStore),
283     mut krate: ast::Crate,
284     crate_name: &str,
285 ) -> Result<(ast::Crate, Lrc<LintStore>)> {
286     krate = sess.time("attributes_injection", || {
287         rustc_builtin_macros::cmdline_attrs::inject(
288             krate,
289             &sess.parse_sess,
290             &sess.opts.debugging_opts.crate_attr,
291         )
292     });
293
294     let (krate, features) = rustc_expand::config::features(sess, krate);
295     // these need to be set "early" so that expansion sees `quote` if enabled.
296     sess.init_features(features);
297
298     let crate_types = util::collect_crate_types(sess, &krate.attrs);
299     sess.init_crate_types(crate_types);
300
301     let disambiguator = util::compute_crate_disambiguator(sess);
302     sess.crate_disambiguator.set(disambiguator).expect("not yet initialized");
303     rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator)?;
304
305     if sess.opts.incremental.is_some() {
306         sess.time("incr_comp_garbage_collect_session_directories", || {
307             if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
308                 warn!(
309                     "Error while trying to garbage collect incremental \
310                      compilation cache directory: {}",
311                     e
312                 );
313             }
314         });
315     }
316
317     sess.time("recursion_limit", || {
318         middle::limits::update_limits(sess, &krate);
319     });
320
321     let mut lint_store = rustc_lint::new_lint_store(
322         sess.opts.debugging_opts.no_interleave_lints,
323         sess.unstable_options(),
324     );
325     register_lints(&sess, &mut lint_store);
326
327     let registrars =
328         sess.time("plugin_loading", || plugin::load::load_plugins(sess, metadata_loader, &krate));
329     sess.time("plugin_registration", || {
330         let mut registry = plugin::Registry { lint_store: &mut lint_store };
331         for registrar in registrars {
332             registrar(&mut registry);
333         }
334     });
335
336     let lint_store = Lrc::new(lint_store);
337     sess.init_lint_store(lint_store.clone());
338
339     Ok((krate, lint_store))
340 }
341
342 fn pre_expansion_lint(
343     sess: &Session,
344     lint_store: &LintStore,
345     krate: &ast::Crate,
346     crate_name: &str,
347 ) {
348     sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", crate_name).run(|| {
349         rustc_lint::check_ast_crate(
350             sess,
351             lint_store,
352             &krate,
353             true,
354             None,
355             rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
356         );
357     });
358 }
359
360 fn configure_and_expand_inner<'a>(
361     sess: &'a Session,
362     lint_store: &'a LintStore,
363     mut krate: ast::Crate,
364     crate_name: &str,
365     resolver_arenas: &'a ResolverArenas<'a>,
366     metadata_loader: &'a MetadataLoaderDyn,
367 ) -> Result<(ast::Crate, Resolver<'a>)> {
368     tracing::trace!("configure_and_expand_inner");
369     pre_expansion_lint(sess, lint_store, &krate, crate_name);
370
371     let mut resolver = Resolver::new(sess, &krate, crate_name, metadata_loader, &resolver_arenas);
372     rustc_builtin_macros::register_builtin_macros(&mut resolver);
373
374     krate = sess.time("crate_injection", || {
375         let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| Symbol::intern(s));
376         rustc_builtin_macros::standard_library_imports::inject(
377             krate,
378             &mut resolver,
379             &sess,
380             alt_std_name,
381         )
382     });
383
384     util::check_attr_crate_type(&sess, &krate.attrs, &mut resolver.lint_buffer());
385
386     // Expand all macros
387     krate = sess.time("macro_expand_crate", || {
388         // Windows dlls do not have rpaths, so they don't know how to find their
389         // dependencies. It's up to us to tell the system where to find all the
390         // dependent dlls. Note that this uses cfg!(windows) as opposed to
391         // targ_cfg because syntax extensions are always loaded for the host
392         // compiler, not for the target.
393         //
394         // This is somewhat of an inherently racy operation, however, as
395         // multiple threads calling this function could possibly continue
396         // extending PATH far beyond what it should. To solve this for now we
397         // just don't add any new elements to PATH which are already there
398         // within PATH. This is basically a targeted fix at #17360 for rustdoc
399         // which runs rustc in parallel but has been seen (#33844) to cause
400         // problems with PATH becoming too long.
401         let mut old_path = OsString::new();
402         if cfg!(windows) {
403             old_path = env::var_os("PATH").unwrap_or(old_path);
404             let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
405             for path in env::split_paths(&old_path) {
406                 if !new_path.contains(&path) {
407                     new_path.push(path);
408                 }
409             }
410             env::set_var(
411                 "PATH",
412                 &env::join_paths(
413                     new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
414                 )
415                 .unwrap(),
416             );
417         }
418
419         // Create the config for macro expansion
420         let features = sess.features_untracked();
421         let cfg = rustc_expand::expand::ExpansionConfig {
422             features: Some(&features),
423             recursion_limit: sess.recursion_limit(),
424             trace_mac: sess.opts.debugging_opts.trace_macros,
425             should_test: sess.opts.test,
426             span_debug: sess.opts.debugging_opts.span_debug,
427             proc_macro_backtrace: sess.opts.debugging_opts.proc_macro_backtrace,
428             ..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string())
429         };
430
431         let extern_mod_loaded = |ident: Ident, attrs, items, span| {
432             let krate = ast::Crate { attrs, items, span, proc_macros: vec![] };
433             pre_expansion_lint(sess, lint_store, &krate, &ident.name.as_str());
434             (krate.attrs, krate.items)
435         };
436         let mut ecx = ExtCtxt::new(&sess, cfg, &mut resolver, Some(&extern_mod_loaded));
437
438         // Expand macros now!
439         let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
440
441         // The rest is error reporting
442
443         sess.time("check_unused_macros", || {
444             ecx.check_unused_macros();
445         });
446
447         let mut missing_fragment_specifiers: Vec<_> = ecx
448             .sess
449             .parse_sess
450             .missing_fragment_specifiers
451             .borrow()
452             .iter()
453             .map(|(span, node_id)| (*span, *node_id))
454             .collect();
455         missing_fragment_specifiers.sort_unstable_by_key(|(span, _)| *span);
456
457         let recursion_limit_hit = ecx.reduced_recursion_limit.is_some();
458
459         for (span, node_id) in missing_fragment_specifiers {
460             let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
461             let msg = "missing fragment specifier";
462             resolver.lint_buffer().buffer_lint(lint, node_id, span, msg);
463         }
464         if cfg!(windows) {
465             env::set_var("PATH", &old_path);
466         }
467
468         if recursion_limit_hit {
469             // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
470             // with a large AST
471             Err(ErrorReported)
472         } else {
473             Ok(krate)
474         }
475     })?;
476
477     sess.time("maybe_building_test_harness", || {
478         rustc_builtin_macros::test_harness::inject(&sess, &mut resolver, &mut krate)
479     });
480
481     if let Some(PpMode::Source(PpSourceMode::EveryBodyLoops)) = sess.opts.pretty {
482         tracing::debug!("replacing bodies with loop {{}}");
483         util::ReplaceBodyWithLoop::new(&mut resolver).visit_crate(&mut krate);
484     }
485
486     let has_proc_macro_decls = sess.time("AST_validation", || {
487         rustc_ast_passes::ast_validation::check_crate(sess, &krate, &mut resolver.lint_buffer())
488     });
489
490     let crate_types = sess.crate_types();
491     let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
492
493     // For backwards compatibility, we don't try to run proc macro injection
494     // if rustdoc is run on a proc macro crate without '--crate-type proc-macro' being
495     // specified. This should only affect users who manually invoke 'rustdoc', as
496     // 'cargo doc' will automatically pass the proper '--crate-type' flags.
497     // However, we do emit a warning, to let such users know that they should
498     // start passing '--crate-type proc-macro'
499     if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate {
500         let mut msg = sess.diagnostic().struct_warn(
501             &"Trying to document proc macro crate \
502             without passing '--crate-type proc-macro to rustdoc",
503         );
504
505         msg.warn("The generated documentation may be incorrect");
506         msg.emit()
507     } else {
508         krate = sess.time("maybe_create_a_macro_crate", || {
509             let num_crate_types = crate_types.len();
510             let is_test_crate = sess.opts.test;
511             rustc_builtin_macros::proc_macro_harness::inject(
512                 &sess,
513                 &mut resolver,
514                 krate,
515                 is_proc_macro_crate,
516                 has_proc_macro_decls,
517                 is_test_crate,
518                 num_crate_types,
519                 sess.diagnostic(),
520             )
521         });
522     }
523
524     // Done with macro expansion!
525
526     if sess.opts.debugging_opts.input_stats {
527         eprintln!("Post-expansion node count: {}", count_nodes(&krate));
528     }
529
530     if sess.opts.debugging_opts.hir_stats {
531         hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
532     }
533
534     if sess.opts.debugging_opts.ast_json {
535         println!("{}", json::as_json(&krate));
536     }
537
538     resolver.resolve_crate(&krate);
539
540     // Needs to go *after* expansion to be able to check the results of macro expansion.
541     sess.time("complete_gated_feature_checking", || {
542         rustc_ast_passes::feature_gate::check_crate(&krate, sess);
543     });
544
545     // Add all buffered lints from the `ParseSess` to the `Session`.
546     sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
547         info!("{} parse sess buffered_lints", buffered_lints.len());
548         for early_lint in buffered_lints.drain(..) {
549             resolver.lint_buffer().add_early_lint(early_lint);
550         }
551     });
552
553     Ok((krate, resolver))
554 }
555
556 pub fn lower_to_hir<'res, 'tcx>(
557     sess: &'tcx Session,
558     lint_store: &LintStore,
559     resolver: &'res mut Resolver<'_>,
560     dep_graph: &'res DepGraph,
561     krate: &'res ast::Crate,
562     arena: &'tcx rustc_ast_lowering::Arena<'tcx>,
563 ) -> Crate<'tcx> {
564     // We're constructing the HIR here; we don't care what we will
565     // read, since we haven't even constructed the *input* to
566     // incr. comp. yet.
567     dep_graph.assert_ignored();
568
569     // Lower AST to HIR.
570     let hir_crate = rustc_ast_lowering::lower_crate(
571         sess,
572         &krate,
573         resolver,
574         rustc_parse::nt_to_tokenstream,
575         arena,
576     );
577
578     if sess.opts.debugging_opts.hir_stats {
579         hir_stats::print_hir_stats(&hir_crate);
580     }
581
582     sess.time("early_lint_checks", || {
583         rustc_lint::check_ast_crate(
584             sess,
585             lint_store,
586             &krate,
587             false,
588             Some(std::mem::take(resolver.lint_buffer())),
589             rustc_lint::BuiltinCombinedEarlyLintPass::new(),
590         )
591     });
592
593     // Discard hygiene data, which isn't required after lowering to HIR.
594     if !sess.opts.debugging_opts.keep_hygiene_data {
595         rustc_span::hygiene::clear_syntax_context_map();
596     }
597
598     hir_crate
599 }
600
601 // Returns all the paths that correspond to generated files.
602 fn generated_output_paths(
603     sess: &Session,
604     outputs: &OutputFilenames,
605     exact_name: bool,
606     crate_name: &str,
607 ) -> Vec<PathBuf> {
608     let mut out_filenames = Vec::new();
609     for output_type in sess.opts.output_types.keys() {
610         let file = outputs.path(*output_type);
611         match *output_type {
612             // If the filename has been overridden using `-o`, it will not be modified
613             // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
614             OutputType::Exe if !exact_name => {
615                 for crate_type in sess.crate_types().iter() {
616                     let p = filename_for_input(sess, *crate_type, crate_name, outputs);
617                     out_filenames.push(p);
618                 }
619             }
620             OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
621                 // Don't add the dep-info output when omitting it from dep-info targets
622             }
623             _ => {
624                 out_filenames.push(file);
625             }
626         }
627     }
628     out_filenames
629 }
630
631 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
632 // returns None for every file path.
633 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
634 where
635     F: Fn(&PathBuf) -> Option<T>,
636 {
637     for output_path in output_paths {
638         if let Some(result) = f(output_path) {
639             return Some(result);
640         }
641     }
642     None
643 }
644
645 fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
646     let input_path = input_path.canonicalize().ok();
647     if input_path.is_none() {
648         return false;
649     }
650     let check = |output_path: &PathBuf| {
651         if output_path.canonicalize().ok() == input_path { Some(()) } else { None }
652     };
653     check_output(output_paths, check).is_some()
654 }
655
656 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
657     let check = |output_path: &PathBuf| output_path.is_dir().then(|| output_path.clone());
658     check_output(output_paths, check)
659 }
660
661 fn escape_dep_filename(filename: &String) -> String {
662     // Apparently clang and gcc *only* escape spaces:
663     // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
664     filename.replace(" ", "\\ ")
665 }
666
667 // Makefile comments only need escaping newlines and `\`.
668 // The result can be unescaped by anything that can unescape `escape_default` and friends.
669 fn escape_dep_env(symbol: Symbol) -> String {
670     let s = symbol.as_str();
671     let mut escaped = String::with_capacity(s.len());
672     for c in s.chars() {
673         match c {
674             '\n' => escaped.push_str(r"\n"),
675             '\r' => escaped.push_str(r"\r"),
676             '\\' => escaped.push_str(r"\\"),
677             _ => escaped.push(c),
678         }
679     }
680     escaped
681 }
682
683 fn write_out_deps(
684     sess: &Session,
685     boxed_resolver: &Steal<Rc<RefCell<BoxedResolver>>>,
686     outputs: &OutputFilenames,
687     out_filenames: &[PathBuf],
688 ) {
689     // Write out dependency rules to the dep-info file if requested
690     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
691         return;
692     }
693     let deps_filename = outputs.path(OutputType::DepInfo);
694
695     let result = (|| -> io::Result<()> {
696         // Build a list of files used to compile the output and
697         // write Makefile-compatible dependency rules
698         let mut files: Vec<String> = sess
699             .source_map()
700             .files()
701             .iter()
702             .filter(|fmap| fmap.is_real_file())
703             .filter(|fmap| !fmap.is_imported())
704             .map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
705             .collect();
706
707         if let Some(ref backend) = sess.opts.debugging_opts.codegen_backend {
708             files.push(backend.to_string());
709         }
710
711         if sess.binary_dep_depinfo() {
712             boxed_resolver.borrow().borrow_mut().access(|resolver| {
713                 for cnum in resolver.cstore().crates_untracked() {
714                     let source = resolver.cstore().crate_source_untracked(cnum);
715                     if let Some((path, _)) = source.dylib {
716                         files.push(escape_dep_filename(&path.display().to_string()));
717                     }
718                     if let Some((path, _)) = source.rlib {
719                         files.push(escape_dep_filename(&path.display().to_string()));
720                     }
721                     if let Some((path, _)) = source.rmeta {
722                         files.push(escape_dep_filename(&path.display().to_string()));
723                     }
724                 }
725             });
726         }
727
728         let mut file = BufWriter::new(fs::File::create(&deps_filename)?);
729         for path in out_filenames {
730             writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
731         }
732
733         // Emit a fake target for each input file to the compilation. This
734         // prevents `make` from spitting out an error if a file is later
735         // deleted. For more info see #28735
736         for path in files {
737             writeln!(file, "{}:", path)?;
738         }
739
740         // Emit special comments with information about accessed environment variables.
741         let env_depinfo = sess.parse_sess.env_depinfo.borrow();
742         if !env_depinfo.is_empty() {
743             let mut envs: Vec<_> = env_depinfo
744                 .iter()
745                 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
746                 .collect();
747             envs.sort_unstable();
748             writeln!(file)?;
749             for (k, v) in envs {
750                 write!(file, "# env-dep:{}", k)?;
751                 if let Some(v) = v {
752                     write!(file, "={}", v)?;
753                 }
754                 writeln!(file)?;
755             }
756         }
757
758         Ok(())
759     })();
760
761     match result {
762         Ok(_) => {
763             if sess.opts.json_artifact_notifications {
764                 sess.parse_sess
765                     .span_diagnostic
766                     .emit_artifact_notification(&deps_filename, "dep-info");
767             }
768         }
769         Err(e) => sess.fatal(&format!(
770             "error writing dependencies to `{}`: {}",
771             deps_filename.display(),
772             e
773         )),
774     }
775 }
776
777 pub fn prepare_outputs(
778     sess: &Session,
779     compiler: &Compiler,
780     krate: &ast::Crate,
781     boxed_resolver: &Steal<Rc<RefCell<BoxedResolver>>>,
782     crate_name: &str,
783 ) -> Result<OutputFilenames> {
784     let _timer = sess.timer("prepare_outputs");
785
786     // FIXME: rustdoc passes &[] instead of &krate.attrs here
787     let outputs = util::build_output_filenames(
788         &compiler.input,
789         &compiler.output_dir,
790         &compiler.output_file,
791         &krate.attrs,
792         sess,
793     );
794
795     let output_paths =
796         generated_output_paths(sess, &outputs, compiler.output_file.is_some(), &crate_name);
797
798     // Ensure the source file isn't accidentally overwritten during compilation.
799     if let Some(ref input_path) = compiler.input_path {
800         if sess.opts.will_create_output_file() {
801             if output_contains_path(&output_paths, input_path) {
802                 sess.err(&format!(
803                     "the input file \"{}\" would be overwritten by the generated \
804                         executable",
805                     input_path.display()
806                 ));
807                 return Err(ErrorReported);
808             }
809             if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
810                 sess.err(&format!(
811                     "the generated executable for the input file \"{}\" conflicts with the \
812                         existing directory \"{}\"",
813                     input_path.display(),
814                     dir_path.display()
815                 ));
816                 return Err(ErrorReported);
817             }
818         }
819     }
820
821     write_out_deps(sess, boxed_resolver, &outputs, &output_paths);
822
823     let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
824         && sess.opts.output_types.len() == 1;
825
826     if !only_dep_info {
827         if let Some(ref dir) = compiler.output_dir {
828             if fs::create_dir_all(dir).is_err() {
829                 sess.err("failed to find or create the directory specified by `--out-dir`");
830                 return Err(ErrorReported);
831             }
832         }
833     }
834
835     Ok(outputs)
836 }
837
838 pub static DEFAULT_QUERY_PROVIDERS: SyncLazy<Providers> = SyncLazy::new(|| {
839     let providers = &mut Providers::default();
840     providers.analysis = analysis;
841     proc_macro_decls::provide(providers);
842     plugin::build::provide(providers);
843     rustc_middle::hir::provide(providers);
844     mir::provide(providers);
845     mir_build::provide(providers);
846     rustc_privacy::provide(providers);
847     typeck::provide(providers);
848     ty::provide(providers);
849     traits::provide(providers);
850     rustc_passes::provide(providers);
851     rustc_resolve::provide(providers);
852     rustc_traits::provide(providers);
853     rustc_ty_utils::provide(providers);
854     rustc_metadata::provide(providers);
855     rustc_lint::provide(providers);
856     rustc_symbol_mangling::provide(providers);
857     rustc_codegen_ssa::provide(providers);
858     *providers
859 });
860
861 pub static DEFAULT_EXTERN_QUERY_PROVIDERS: SyncLazy<Providers> = SyncLazy::new(|| {
862     let mut extern_providers = *DEFAULT_QUERY_PROVIDERS;
863     rustc_metadata::provide_extern(&mut extern_providers);
864     rustc_codegen_ssa::provide_extern(&mut extern_providers);
865     extern_providers
866 });
867
868 pub struct QueryContext<'tcx> {
869     gcx: &'tcx GlobalCtxt<'tcx>,
870 }
871
872 impl<'tcx> QueryContext<'tcx> {
873     pub fn enter<F, R>(&mut self, f: F) -> R
874     where
875         F: FnOnce(TyCtxt<'tcx>) -> R,
876     {
877         let icx = ty::tls::ImplicitCtxt::new(self.gcx);
878         ty::tls::enter_context(&icx, |_| f(icx.tcx))
879     }
880 }
881
882 pub fn create_global_ctxt<'tcx>(
883     compiler: &'tcx Compiler,
884     lint_store: Lrc<LintStore>,
885     krate: &'tcx Crate<'tcx>,
886     dep_graph: DepGraph,
887     resolver_outputs: ResolverOutputs,
888     outputs: OutputFilenames,
889     crate_name: &str,
890     queries: &'tcx OnceCell<TcxQueries<'tcx>>,
891     global_ctxt: &'tcx OnceCell<GlobalCtxt<'tcx>>,
892     arena: &'tcx WorkerLocal<Arena<'tcx>>,
893 ) -> QueryContext<'tcx> {
894     let sess = &compiler.session();
895
896     let def_path_table = resolver_outputs.definitions.def_path_table();
897     let query_result_on_disk_cache =
898         rustc_incremental::load_query_result_cache(sess, def_path_table);
899
900     let codegen_backend = compiler.codegen_backend();
901     let mut local_providers = *DEFAULT_QUERY_PROVIDERS;
902     codegen_backend.provide(&mut local_providers);
903
904     let mut extern_providers = *DEFAULT_EXTERN_QUERY_PROVIDERS;
905     codegen_backend.provide(&mut extern_providers);
906     codegen_backend.provide_extern(&mut extern_providers);
907
908     if let Some(callback) = compiler.override_queries {
909         callback(sess, &mut local_providers, &mut extern_providers);
910     }
911
912     let queries = queries.get_or_init(|| TcxQueries::new(local_providers, extern_providers));
913
914     let gcx = sess.time("setup_global_ctxt", || {
915         global_ctxt.get_or_init(|| {
916             TyCtxt::create_global_ctxt(
917                 sess,
918                 lint_store,
919                 arena,
920                 resolver_outputs,
921                 krate,
922                 dep_graph,
923                 query_result_on_disk_cache,
924                 queries.as_dyn(),
925                 &crate_name,
926                 outputs,
927             )
928         })
929     });
930
931     QueryContext { gcx }
932 }
933
934 /// Runs the resolution, type-checking, region checking and other
935 /// miscellaneous analysis passes on the crate.
936 fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> {
937     rustc_passes::hir_id_validator::check_crate(tcx);
938
939     let sess = tcx.sess;
940     let mut entry_point = None;
941
942     sess.time("misc_checking_1", || {
943         parallel!(
944             {
945                 entry_point = sess.time("looking_for_entry_point", || tcx.entry_fn(()));
946
947                 sess.time("looking_for_plugin_registrar", || tcx.ensure().plugin_registrar_fn(()));
948
949                 sess.time("looking_for_derive_registrar", || {
950                     tcx.ensure().proc_macro_decls_static(())
951                 });
952
953                 let cstore = tcx
954                     .cstore_as_any()
955                     .downcast_ref::<CStore>()
956                     .expect("`tcx.cstore` is not a `CStore`");
957                 cstore.report_unused_deps(tcx);
958             },
959             {
960                 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
961                     tcx.ensure().check_mod_loops(module);
962                     tcx.ensure().check_mod_attrs(module);
963                     tcx.ensure().check_mod_naked_functions(module);
964                     tcx.ensure().check_mod_unstable_api_usage(module);
965                     tcx.ensure().check_mod_const_bodies(module);
966                 });
967             }
968         );
969     });
970
971     // passes are timed inside typeck
972     typeck::check_crate(tcx)?;
973
974     sess.time("misc_checking_2", || {
975         parallel!(
976             {
977                 sess.time("match_checking", || {
978                     tcx.par_body_owners(|def_id| {
979                         tcx.ensure().check_match(def_id.to_def_id());
980                     });
981                 });
982             },
983             {
984                 sess.time("liveness_and_intrinsic_checking", || {
985                     par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
986                         // this must run before MIR dump, because
987                         // "not all control paths return a value" is reported here.
988                         //
989                         // maybe move the check to a MIR pass?
990                         tcx.ensure().check_mod_liveness(module);
991                         tcx.ensure().check_mod_intrinsics(module);
992                     });
993                 });
994             }
995         );
996     });
997
998     sess.time("MIR_borrow_checking", || {
999         tcx.par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
1000     });
1001
1002     sess.time("MIR_effect_checking", || {
1003         for def_id in tcx.body_owners() {
1004             tcx.ensure().thir_check_unsafety(def_id);
1005             if !tcx.sess.opts.debugging_opts.thir_unsafeck {
1006                 mir::transform::check_unsafety::check_unsafety(tcx, def_id);
1007             }
1008
1009             if tcx.hir().body_const_context(def_id).is_some() {
1010                 tcx.ensure()
1011                     .mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(def_id));
1012             }
1013         }
1014     });
1015
1016     sess.time("layout_testing", || layout_test::test_layout(tcx));
1017
1018     // Avoid overwhelming user with errors if borrow checking failed.
1019     // I'm not sure how helpful this is, to be honest, but it avoids a
1020     // lot of annoying errors in the ui tests (basically,
1021     // lint warnings and so on -- kindck used to do this abort, but
1022     // kindck is gone now). -nmatsakis
1023     if sess.has_errors() {
1024         return Err(ErrorReported);
1025     }
1026
1027     sess.time("misc_checking_3", || {
1028         parallel!(
1029             {
1030                 tcx.ensure().privacy_access_levels(());
1031
1032                 parallel!(
1033                     {
1034                         tcx.ensure().check_private_in_public(());
1035                     },
1036                     {
1037                         sess.time("death_checking", || rustc_passes::dead::check_crate(tcx));
1038                     },
1039                     {
1040                         sess.time("unused_lib_feature_checking", || {
1041                             rustc_passes::stability::check_unused_or_stable_features(tcx)
1042                         });
1043                     },
1044                     {
1045                         sess.time("lint_checking", || {
1046                             rustc_lint::check_crate(tcx, || {
1047                                 rustc_lint::BuiltinCombinedLateLintPass::new()
1048                             });
1049                         });
1050                     }
1051                 );
1052             },
1053             {
1054                 sess.time("privacy_checking_modules", || {
1055                     par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
1056                         tcx.ensure().check_mod_privacy(module);
1057                     });
1058                 });
1059             }
1060         );
1061     });
1062
1063     Ok(())
1064 }
1065
1066 fn encode_and_write_metadata(
1067     tcx: TyCtxt<'_>,
1068     outputs: &OutputFilenames,
1069 ) -> (middle::cstore::EncodedMetadata, bool) {
1070     #[derive(PartialEq, Eq, PartialOrd, Ord)]
1071     enum MetadataKind {
1072         None,
1073         Uncompressed,
1074         Compressed,
1075     }
1076
1077     let metadata_kind = tcx
1078         .sess
1079         .crate_types()
1080         .iter()
1081         .map(|ty| match *ty {
1082             CrateType::Executable | CrateType::Staticlib | CrateType::Cdylib => MetadataKind::None,
1083
1084             CrateType::Rlib => MetadataKind::Uncompressed,
1085
1086             CrateType::Dylib | CrateType::ProcMacro => MetadataKind::Compressed,
1087         })
1088         .max()
1089         .unwrap_or(MetadataKind::None);
1090
1091     let metadata = match metadata_kind {
1092         MetadataKind::None => middle::cstore::EncodedMetadata::new(),
1093         MetadataKind::Uncompressed | MetadataKind::Compressed => tcx.encode_metadata(),
1094     };
1095
1096     let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
1097
1098     let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
1099     if need_metadata_file {
1100         let crate_name = &tcx.crate_name(LOCAL_CRATE).as_str();
1101         let out_filename = filename_for_metadata(tcx.sess, crate_name, outputs);
1102         // To avoid races with another rustc process scanning the output directory,
1103         // we need to write the file somewhere else and atomically move it to its
1104         // final destination, with an `fs::rename` call. In order for the rename to
1105         // always succeed, the temporary file needs to be on the same filesystem,
1106         // which is why we create it inside the output directory specifically.
1107         let metadata_tmpdir = TempFileBuilder::new()
1108             .prefix("rmeta")
1109             .tempdir_in(out_filename.parent().unwrap())
1110             .unwrap_or_else(|err| tcx.sess.fatal(&format!("couldn't create a temp dir: {}", err)));
1111         let metadata_tmpdir = MaybeTempDir::new(metadata_tmpdir, tcx.sess.opts.cg.save_temps);
1112         let metadata_filename = emit_metadata(tcx.sess, &metadata.raw_data, &metadata_tmpdir);
1113         if let Err(e) = util::non_durable_rename(&metadata_filename, &out_filename) {
1114             tcx.sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
1115         }
1116         if tcx.sess.opts.json_artifact_notifications {
1117             tcx.sess
1118                 .parse_sess
1119                 .span_diagnostic
1120                 .emit_artifact_notification(&out_filename, "metadata");
1121         }
1122     }
1123
1124     let need_metadata_module = metadata_kind == MetadataKind::Compressed;
1125
1126     (metadata, need_metadata_module)
1127 }
1128
1129 /// Runs the codegen backend, after which the AST and analysis can
1130 /// be discarded.
1131 pub fn start_codegen<'tcx>(
1132     codegen_backend: &dyn CodegenBackend,
1133     tcx: TyCtxt<'tcx>,
1134     outputs: &OutputFilenames,
1135 ) -> Box<dyn Any> {
1136     info!("Pre-codegen\n{:?}", tcx.debug_stats());
1137
1138     let (metadata, need_metadata_module) = encode_and_write_metadata(tcx, outputs);
1139
1140     let codegen = tcx.sess.time("codegen_crate", move || {
1141         codegen_backend.codegen_crate(tcx, metadata, need_metadata_module)
1142     });
1143
1144     // Don't run these test assertions when not doing codegen. Compiletest tries to build
1145     // build-fail tests in check mode first and expects it to not give an error in that case.
1146     if tcx.sess.opts.output_types.should_codegen() {
1147         rustc_incremental::assert_module_sources::assert_module_sources(tcx);
1148         rustc_symbol_mangling::test::report_symbol_names(tcx);
1149     }
1150
1151     info!("Post-codegen\n{:?}", tcx.debug_stats());
1152
1153     if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1154         if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
1155             tcx.sess.err(&format!("could not emit MIR: {}", e));
1156             tcx.sess.abort_if_errors();
1157         }
1158     }
1159
1160     codegen
1161 }