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