]> git.lizzy.rs Git - rust.git/blob - src/librustc_interface/passes.rs
Move metadata encoding earlier.
[rust.git] / src / librustc_interface / passes.rs
1 use crate::interface::{Compiler, Result};
2 use crate::util;
3 use crate::proc_macro_decls;
4
5 use log::{debug, info, warn, log_enabled};
6 use rustc::dep_graph::DepGraph;
7 use rustc::hir;
8 use rustc::hir::lowering::lower_crate;
9 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
10 use rustc::lint;
11 use rustc::middle::{self, reachable, resolve_lifetime, stability};
12 use rustc::middle::privacy::AccessLevels;
13 use rustc::ty::{self, AllArenas, Resolutions, TyCtxt, GlobalCtxt};
14 use rustc::ty::steal::Steal;
15 use rustc::traits;
16 use rustc::util::common::{time, ErrorReported};
17 use rustc::util::profiling::ProfileCategory;
18 use rustc::session::{CompileResult, CrateDisambiguator, Session};
19 use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType};
20 use rustc::session::search_paths::PathKind;
21 use rustc_allocator as allocator;
22 use rustc_borrowck as borrowck;
23 use rustc_codegen_utils::codegen_backend::CodegenBackend;
24 use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel};
25 use rustc_data_structures::fingerprint::Fingerprint;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_data_structures::sync::{Lrc, ParallelIterator, par_iter};
28 use rustc_incremental;
29 use rustc_incremental::DepGraphFuture;
30 use rustc_metadata::creader::CrateLoader;
31 use rustc_metadata::cstore::{self, CStore};
32 use rustc_mir as mir;
33 use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion, layout_test};
34 use rustc_plugin as plugin;
35 use rustc_plugin::registry::Registry;
36 use rustc_privacy;
37 use rustc_resolve::{Resolver, ResolverArenas};
38 use rustc_traits;
39 use rustc_typeck as typeck;
40 use syntax::{self, ast, attr, diagnostics, visit};
41 use syntax::early_buffered_lints::BufferedEarlyLint;
42 use syntax::ext::base::{NamedSyntaxExtension, ExtCtxt};
43 use syntax::mut_visit::MutVisitor;
44 use syntax::parse::{self, PResult};
45 use syntax::util::node_count::NodeCounter;
46 use syntax::util::lev_distance::find_best_match_for_name;
47 use syntax::symbol::Symbol;
48 use syntax::feature_gate::AttributeType;
49 use syntax_pos::{FileName, hygiene};
50 use syntax_ext;
51
52 use serialize::json;
53
54 use std::any::Any;
55 use std::env;
56 use std::ffi::OsString;
57 use std::fs;
58 use std::io::{self, Write};
59 use std::iter;
60 use std::path::{Path, PathBuf};
61 use std::sync::mpsc;
62 use std::cell::RefCell;
63 use std::rc::Rc;
64 use std::mem;
65 use std::ops::Generator;
66
67 pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
68     sess.diagnostic()
69         .set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error);
70     hygiene::set_default_edition(sess.edition());
71
72     sess.profiler(|p| p.start_activity("parsing"));
73     let krate = time(sess, "parsing", || match *input {
74         Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
75         Input::Str {
76             ref input,
77             ref name,
78         } => parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess),
79     })?;
80     sess.profiler(|p| p.end_activity("parsing"));
81
82     sess.diagnostic().set_continue_after_error(true);
83
84     if sess.opts.debugging_opts.ast_json_noexpand {
85         println!("{}", json::as_json(&krate));
86     }
87
88     if sess.opts.debugging_opts.input_stats {
89         println!(
90             "Lines of code:             {}",
91             sess.source_map().count_lines()
92         );
93         println!("Pre-expansion node count:  {}", count_nodes(&krate));
94     }
95
96     if let Some(ref s) = sess.opts.debugging_opts.show_span {
97         syntax::show_span::run(sess.diagnostic(), s, &krate);
98     }
99
100     if sess.opts.debugging_opts.hir_stats {
101         hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
102     }
103
104     Ok(krate)
105 }
106
107 fn count_nodes(krate: &ast::Crate) -> usize {
108     let mut counter = NodeCounter::new();
109     visit::walk_crate(&mut counter, krate);
110     counter.count
111 }
112
113 declare_box_region_type!(
114     pub BoxedResolver,
115     for(),
116     (&mut Resolver<'_>) -> (Result<ast::Crate>, ExpansionResult)
117 );
118
119 /// Runs the "early phases" of the compiler: initial `cfg` processing,
120 /// loading compiler plugins (including those from `addl_plugins`),
121 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
122 /// harness if one is to be provided, injection of a dependency on the
123 /// standard library and prelude, and name resolution.
124 ///
125 /// Returns `None` if we're aborting after handling -W help.
126 pub fn configure_and_expand(
127     sess: Lrc<Session>,
128     cstore: Lrc<CStore>,
129     krate: ast::Crate,
130     crate_name: &str,
131     plugin_info: PluginInfo,
132 ) -> Result<(ast::Crate, BoxedResolver)> {
133     // Currently, we ignore the name resolution data structures for the purposes of dependency
134     // tracking. Instead we will run name resolution and include its output in the hash of each
135     // item, much like we do for macro expansion. In other words, the hash reflects not just
136     // its contents but the results of name resolution on those contents. Hopefully we'll push
137     // this back at some point.
138     let crate_name = crate_name.to_string();
139     let (result, resolver) = BoxedResolver::new(static move || {
140         let sess = &*sess;
141         let mut crate_loader = CrateLoader::new(sess, &*cstore, &crate_name);
142         let resolver_arenas = Resolver::arenas();
143         let res = configure_and_expand_inner(
144             sess,
145             &*cstore,
146             krate,
147             &crate_name,
148             &resolver_arenas,
149             &mut crate_loader,
150             plugin_info,
151         );
152         let mut resolver = match res {
153             Err(v) => {
154                 yield BoxedResolver::initial_yield(Err(v));
155                 panic!()
156             }
157             Ok((krate, resolver)) => {
158                 yield BoxedResolver::initial_yield(Ok(krate));
159                 resolver
160             }
161         };
162         box_region_allow_access!(for(), (&mut Resolver<'_>), (&mut resolver));
163         ExpansionResult::from_owned_resolver(resolver)
164     });
165     result.map(|k| (k, resolver))
166 }
167
168 pub struct ExpansionResult {
169     pub defs: Steal<hir::map::Definitions>,
170     pub resolutions: Steal<Resolutions>,
171 }
172
173 impl ExpansionResult {
174     fn from_owned_resolver(
175         resolver: Resolver<'_>,
176     ) -> Self {
177         ExpansionResult {
178             defs: Steal::new(resolver.definitions),
179             resolutions: Steal::new(Resolutions {
180                 freevars: resolver.freevars,
181                 export_map: resolver.export_map,
182                 trait_map: resolver.trait_map,
183                 glob_map: resolver.glob_map,
184                 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
185                 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
186                 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
187                     (ident.name, entry.introduced_by_item)
188                 }).collect(),
189             }),
190         }
191     }
192
193     pub fn from_resolver_ref(
194         resolver: &Resolver<'_>,
195     ) -> Self {
196         ExpansionResult {
197             defs: Steal::new(resolver.definitions.clone()),
198             resolutions: Steal::new(Resolutions {
199                 freevars: resolver.freevars.clone(),
200                 export_map: resolver.export_map.clone(),
201                 trait_map: resolver.trait_map.clone(),
202                 glob_map: resolver.glob_map.clone(),
203                 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
204                 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
205                 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
206                     (ident.name, entry.introduced_by_item)
207                 }).collect(),
208             }),
209         }
210     }
211 }
212
213 impl BoxedResolver {
214     pub fn to_expansion_result(
215         mut resolver: Rc<Option<RefCell<BoxedResolver>>>,
216     ) -> ExpansionResult {
217         if let Some(resolver) = Rc::get_mut(&mut resolver) {
218             mem::replace(resolver, None).unwrap().into_inner().complete()
219         } else {
220             let resolver = &*resolver;
221             resolver.as_ref().unwrap().borrow_mut().access(|resolver| {
222                 ExpansionResult::from_resolver_ref(resolver)
223             })
224         }
225     }
226 }
227
228 pub struct PluginInfo {
229     syntax_exts: Vec<NamedSyntaxExtension>,
230     attributes: Vec<(String, AttributeType)>,
231 }
232
233 pub fn register_plugins<'a>(
234     compiler: &Compiler,
235     sess: &'a Session,
236     cstore: &'a CStore,
237     mut krate: ast::Crate,
238     crate_name: &str,
239 ) -> Result<(ast::Crate, PluginInfo)> {
240     krate = time(sess, "attributes injection", || {
241         syntax::attr::inject(krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr)
242     });
243
244     let (mut krate, features) = syntax::config::features(
245         krate,
246         &sess.parse_sess,
247         sess.edition(),
248         &sess.opts.debugging_opts.allow_features,
249     );
250     // these need to be set "early" so that expansion sees `quote` if enabled.
251     sess.init_features(features);
252
253     let crate_types = util::collect_crate_types(sess, &krate.attrs);
254     sess.crate_types.set(crate_types);
255
256     let disambiguator = util::compute_crate_disambiguator(sess);
257     sess.crate_disambiguator.set(disambiguator);
258     rustc_incremental::prepare_session_directory(sess, &crate_name, disambiguator);
259
260     if sess.opts.incremental.is_some() {
261         time(sess, "garbage collect incremental cache directory", || {
262             if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
263                 warn!(
264                     "Error while trying to garbage collect incremental \
265                      compilation cache directory: {}",
266                     e
267                 );
268             }
269         });
270     }
271
272     // If necessary, compute the dependency graph (in the background).
273     compiler.dep_graph_future().ok();
274
275     time(sess, "recursion limit", || {
276         middle::recursion_limit::update_limits(sess, &krate);
277     });
278
279     krate = time(sess, "crate injection", || {
280         let alt_std_name = sess.opts.alt_std_name.as_ref().map(|s| &**s);
281         syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name, sess.edition())
282     });
283
284     let registrars = time(sess, "plugin loading", || {
285         plugin::load::load_plugins(
286             sess,
287             &cstore,
288             &krate,
289             crate_name,
290             Some(sess.opts.debugging_opts.extra_plugins.clone()),
291         )
292     });
293
294     let mut registry = Registry::new(sess, krate.span);
295
296     time(sess, "plugin registration", || {
297         if sess.features_untracked().rustc_diagnostic_macros {
298             registry.register_macro(
299                 "__diagnostic_used",
300                 diagnostics::plugin::expand_diagnostic_used,
301             );
302             registry.register_macro(
303                 "__register_diagnostic",
304                 diagnostics::plugin::expand_register_diagnostic,
305             );
306             registry.register_macro(
307                 "__build_diagnostic_array",
308                 diagnostics::plugin::expand_build_diagnostic_array,
309             );
310         }
311
312         for registrar in registrars {
313             registry.args_hidden = Some(registrar.args);
314             (registrar.fun)(&mut registry);
315         }
316     });
317
318     let Registry {
319         syntax_exts,
320         early_lint_passes,
321         late_lint_passes,
322         lint_groups,
323         llvm_passes,
324         attributes,
325         ..
326     } = registry;
327
328     let mut ls = sess.lint_store.borrow_mut();
329     for pass in early_lint_passes {
330         ls.register_early_pass(Some(sess), true, false, pass);
331     }
332     for pass in late_lint_passes {
333         ls.register_late_pass(Some(sess), true, false, false, pass);
334     }
335
336     for (name, (to, deprecated_name)) in lint_groups {
337         ls.register_group(Some(sess), true, name, deprecated_name, to);
338     }
339
340     *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
341     *sess.plugin_attributes.borrow_mut() = attributes.clone();
342
343     Ok((krate, PluginInfo {
344         syntax_exts,
345         attributes,
346     }))
347 }
348
349 fn configure_and_expand_inner<'a>(
350     sess: &'a Session,
351     cstore: &'a CStore,
352     mut krate: ast::Crate,
353     crate_name: &str,
354     resolver_arenas: &'a ResolverArenas<'a>,
355     crate_loader: &'a mut CrateLoader<'a>,
356     plugin_info: PluginInfo,
357 ) -> Result<(ast::Crate, Resolver<'a>)> {
358     let attributes = plugin_info.attributes;
359     time(sess, "pre ast expansion lint checks", || {
360         lint::check_ast_crate(
361             sess,
362             &krate,
363             true,
364             rustc_lint::BuiltinCombinedPreExpansionLintPass::new());
365     });
366
367     let mut resolver = Resolver::new(
368         sess,
369         cstore,
370         &krate,
371         crate_name,
372         crate_loader,
373         &resolver_arenas,
374     );
375     syntax_ext::register_builtins(&mut resolver, plugin_info.syntax_exts);
376
377     // Expand all macros
378     sess.profiler(|p| p.start_activity("macro expansion"));
379     krate = time(sess, "expansion", || {
380         // Windows dlls do not have rpaths, so they don't know how to find their
381         // dependencies. It's up to us to tell the system where to find all the
382         // dependent dlls. Note that this uses cfg!(windows) as opposed to
383         // targ_cfg because syntax extensions are always loaded for the host
384         // compiler, not for the target.
385         //
386         // This is somewhat of an inherently racy operation, however, as
387         // multiple threads calling this function could possibly continue
388         // extending PATH far beyond what it should. To solve this for now we
389         // just don't add any new elements to PATH which are already there
390         // within PATH. This is basically a targeted fix at #17360 for rustdoc
391         // which runs rustc in parallel but has been seen (#33844) to cause
392         // problems with PATH becoming too long.
393         let mut old_path = OsString::new();
394         if cfg!(windows) {
395             old_path = env::var_os("PATH").unwrap_or(old_path);
396             let mut new_path = sess.host_filesearch(PathKind::All).search_path_dirs();
397             for path in env::split_paths(&old_path) {
398                 if !new_path.contains(&path) {
399                     new_path.push(path);
400                 }
401             }
402             env::set_var(
403                 "PATH",
404                 &env::join_paths(
405                     new_path
406                         .iter()
407                         .filter(|p| env::join_paths(iter::once(p)).is_ok()),
408                 ).unwrap(),
409             );
410         }
411
412         // Create the config for macro expansion
413         let features = sess.features_untracked();
414         let cfg = syntax::ext::expand::ExpansionConfig {
415             features: Some(&features),
416             recursion_limit: *sess.recursion_limit.get(),
417             trace_mac: sess.opts.debugging_opts.trace_macros,
418             should_test: sess.opts.test,
419             ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
420         };
421
422         let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
423
424         // Expand macros now!
425         let krate = time(sess, "expand crate", || {
426             ecx.monotonic_expander().expand_crate(krate)
427         });
428
429         // The rest is error reporting
430
431         time(sess, "check unused macros", || {
432             ecx.check_unused_macros();
433         });
434
435         let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess
436             .missing_fragment_specifiers
437             .borrow()
438             .iter()
439             .cloned()
440             .collect();
441         missing_fragment_specifiers.sort();
442
443         for span in missing_fragment_specifiers {
444             let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
445             let msg = "missing fragment specifier";
446             sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
447         }
448         if cfg!(windows) {
449             env::set_var("PATH", &old_path);
450         }
451         krate
452     });
453     sess.profiler(|p| p.end_activity("macro expansion"));
454
455     time(sess, "maybe building test harness", || {
456         syntax::test::modify_for_testing(
457             &sess.parse_sess,
458             &mut resolver,
459             sess.opts.test,
460             &mut krate,
461             sess.diagnostic(),
462             &sess.features_untracked(),
463         )
464     });
465
466     // If we're actually rustdoc then there's no need to actually compile
467     // anything, so switch everything to just looping
468     if sess.opts.actually_rustdoc {
469         util::ReplaceBodyWithLoop::new(sess).visit_crate(&mut krate);
470     }
471
472     let (has_proc_macro_decls, has_global_allocator) = time(sess, "AST validation", || {
473         ast_validation::check_crate(sess, &krate)
474     });
475
476     // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
477     // bunch of checks in the `modify` function below. For now just skip this
478     // step entirely if we're rustdoc as it's not too useful anyway.
479     if !sess.opts.actually_rustdoc {
480         krate = time(sess, "maybe creating a macro crate", || {
481             let crate_types = sess.crate_types.borrow();
482             let num_crate_types = crate_types.len();
483             let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro);
484             let is_test_crate = sess.opts.test;
485             syntax_ext::proc_macro_decls::modify(
486                 &sess.parse_sess,
487                 &mut resolver,
488                 krate,
489                 is_proc_macro_crate,
490                 has_proc_macro_decls,
491                 is_test_crate,
492                 num_crate_types,
493                 sess.diagnostic(),
494             )
495         });
496     }
497
498     if has_global_allocator {
499         // Expand global allocators, which are treated as an in-tree proc macro
500         time(sess, "creating allocators", || {
501             allocator::expand::modify(
502                 &sess.parse_sess,
503                 &mut resolver,
504                 &mut krate,
505                 crate_name.to_string(),
506                 sess.diagnostic(),
507             )
508         });
509     }
510
511     // Done with macro expansion!
512
513     if sess.opts.debugging_opts.input_stats {
514         println!("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     time(sess, "name resolution", || {
526         resolver.resolve_crate(&krate);
527     });
528
529     // Needs to go *after* expansion to be able to check the results of macro expansion.
530     time(sess, "complete gated feature checking", || {
531         syntax::feature_gate::check_crate(
532             &krate,
533             &sess.parse_sess,
534             &sess.features_untracked(),
535             &attributes,
536             sess.opts.unstable_features,
537         );
538     });
539
540     // Add all buffered lints from the `ParseSess` to the `Session`.
541     sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
542         info!("{} parse sess buffered_lints", buffered_lints.len());
543         for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) {
544             let lint = lint::Lint::from_parser_lint_id(lint_id);
545             sess.buffer_lint(lint, id, span, &msg);
546         }
547     });
548
549     Ok((krate, resolver))
550 }
551
552 pub fn lower_to_hir(
553     sess: &Session,
554     cstore: &CStore,
555     resolver: &mut Resolver<'_>,
556     dep_graph: &DepGraph,
557     krate: &ast::Crate,
558 ) -> Result<hir::map::Forest> {
559     // Lower ast -> hir
560     let hir_forest = time(sess, "lowering ast -> hir", || {
561         let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, resolver);
562
563         if sess.opts.debugging_opts.hir_stats {
564             hir_stats::print_hir_stats(&hir_crate);
565         }
566
567         hir::map::Forest::new(hir_crate, &dep_graph)
568     });
569
570     time(sess, "early lint checks", || {
571         lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new())
572     });
573
574     // Discard hygiene data, which isn't required after lowering to HIR.
575     if !sess.opts.debugging_opts.keep_hygiene_data {
576         syntax::ext::hygiene::clear_markings();
577     }
578
579     Ok(hir_forest)
580 }
581
582 // Returns all the paths that correspond to generated files.
583 fn generated_output_paths(
584     sess: &Session,
585     outputs: &OutputFilenames,
586     exact_name: bool,
587     crate_name: &str,
588 ) -> Vec<PathBuf> {
589     let mut out_filenames = Vec::new();
590     for output_type in sess.opts.output_types.keys() {
591         let file = outputs.path(*output_type);
592         match *output_type {
593             // If the filename has been overridden using `-o`, it will not be modified
594             // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
595             OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() {
596                 let p = ::rustc_codegen_utils::link::filename_for_input(
597                     sess,
598                     *crate_type,
599                     crate_name,
600                     outputs,
601                 );
602                 out_filenames.push(p);
603             },
604             OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
605                 // Don't add the dep-info output when omitting it from dep-info targets
606             }
607             _ => {
608                 out_filenames.push(file);
609             }
610         }
611     }
612     out_filenames
613 }
614
615 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
616 // returns None for every file path.
617 fn check_output<F, T>(output_paths: &[PathBuf], f: F) -> Option<T>
618 where
619     F: Fn(&PathBuf) -> Option<T>,
620 {
621     for output_path in output_paths {
622         if let Some(result) = f(output_path) {
623             return Some(result);
624         }
625     }
626     None
627 }
628
629 fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
630     let input_path = input_path.canonicalize().ok();
631     if input_path.is_none() {
632         return false;
633     }
634     let check = |output_path: &PathBuf| {
635         if output_path.canonicalize().ok() == input_path {
636             Some(())
637         } else {
638             None
639         }
640     };
641     check_output(output_paths, check).is_some()
642 }
643
644 fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
645     let check = |output_path: &PathBuf| {
646         if output_path.is_dir() {
647             Some(output_path.clone())
648         } else {
649             None
650         }
651     };
652     check_output(output_paths, check)
653 }
654
655 fn escape_dep_filename(filename: &FileName) -> String {
656     // Apparently clang and gcc *only* escape spaces:
657     // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
658     filename.to_string().replace(" ", "\\ ")
659 }
660
661 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
662     // Write out dependency rules to the dep-info file if requested
663     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
664         return;
665     }
666     let deps_filename = outputs.path(OutputType::DepInfo);
667
668     let result = (|| -> io::Result<()> {
669         // Build a list of files used to compile the output and
670         // write Makefile-compatible dependency rules
671         let files: Vec<String> = sess.source_map()
672             .files()
673             .iter()
674             .filter(|fmap| fmap.is_real_file())
675             .filter(|fmap| !fmap.is_imported())
676             .map(|fmap| escape_dep_filename(&fmap.name))
677             .collect();
678         let mut file = fs::File::create(&deps_filename)?;
679         for path in out_filenames {
680             writeln!(file, "{}: {}\n", path.display(), files.join(" "))?;
681         }
682
683         // Emit a fake target for each input file to the compilation. This
684         // prevents `make` from spitting out an error if a file is later
685         // deleted. For more info see #28735
686         for path in files {
687             writeln!(file, "{}:", path)?;
688         }
689         Ok(())
690     })();
691
692     if let Err(e) = result {
693         sess.fatal(&format!(
694             "error writing dependencies to `{}`: {}",
695             deps_filename.display(),
696             e
697         ));
698     }
699 }
700
701 pub fn prepare_outputs(
702     sess: &Session,
703     compiler: &Compiler,
704     krate: &ast::Crate,
705     crate_name: &str
706 ) -> Result<OutputFilenames> {
707     // FIXME: rustdoc passes &[] instead of &krate.attrs here
708     let outputs = util::build_output_filenames(
709         &compiler.input,
710         &compiler.output_dir,
711         &compiler.output_file,
712         &krate.attrs,
713         sess
714     );
715
716     let output_paths = generated_output_paths(
717         sess,
718         &outputs,
719         compiler.output_file.is_some(),
720         &crate_name,
721     );
722
723     // Ensure the source file isn't accidentally overwritten during compilation.
724     if let Some(ref input_path) = compiler.input_path {
725         if sess.opts.will_create_output_file() {
726             if output_contains_path(&output_paths, input_path) {
727                 sess.err(&format!(
728                     "the input file \"{}\" would be overwritten by the generated \
729                         executable",
730                     input_path.display()
731                 ));
732                 return Err(ErrorReported);
733             }
734             if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
735                 sess.err(&format!(
736                     "the generated executable for the input file \"{}\" conflicts with the \
737                         existing directory \"{}\"",
738                     input_path.display(),
739                     dir_path.display()
740                 ));
741                 return Err(ErrorReported);
742             }
743         }
744     }
745
746     write_out_deps(sess, &outputs, &output_paths);
747
748     let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
749         && sess.opts.output_types.len() == 1;
750
751     if !only_dep_info {
752         if let Some(ref dir) = compiler.output_dir {
753             if fs::create_dir_all(dir).is_err() {
754                 sess.err("failed to find or create the directory specified by --out-dir");
755                 return Err(ErrorReported);
756             }
757         }
758     }
759
760     Ok(outputs)
761 }
762
763 pub fn default_provide(providers: &mut ty::query::Providers<'_>) {
764     providers.analysis = analysis;
765     proc_macro_decls::provide(providers);
766     plugin::build::provide(providers);
767     hir::provide(providers);
768     borrowck::provide(providers);
769     mir::provide(providers);
770     reachable::provide(providers);
771     resolve_lifetime::provide(providers);
772     rustc_privacy::provide(providers);
773     typeck::provide(providers);
774     ty::provide(providers);
775     traits::provide(providers);
776     stability::provide(providers);
777     middle::intrinsicck::provide(providers);
778     middle::liveness::provide(providers);
779     reachable::provide(providers);
780     rustc_passes::provide(providers);
781     rustc_traits::provide(providers);
782     middle::region::provide(providers);
783     middle::entry::provide(providers);
784     cstore::provide(providers);
785     lint::provide(providers);
786     rustc_lint::provide(providers);
787 }
788
789 pub fn default_provide_extern(providers: &mut ty::query::Providers<'_>) {
790     cstore::provide_extern(providers);
791 }
792
793 declare_box_region_type!(
794     pub BoxedGlobalCtxt,
795     for('gcx),
796     (&'gcx GlobalCtxt<'gcx>) -> ((), ())
797 );
798
799 impl BoxedGlobalCtxt {
800     pub fn enter<F, R>(&mut self, f: F) -> R
801     where
802         F: for<'tcx> FnOnce(TyCtxt<'tcx, 'tcx, 'tcx>) -> R
803     {
804         self.access(|gcx| ty::tls::enter_global(gcx, |tcx| f(tcx)))
805     }
806 }
807
808 pub fn create_global_ctxt(
809     compiler: &Compiler,
810     mut hir_forest: hir::map::Forest,
811     defs: hir::map::Definitions,
812     resolutions: Resolutions,
813     outputs: OutputFilenames,
814     tx: mpsc::Sender<Box<dyn Any + Send>>,
815     crate_name: &str
816 ) -> BoxedGlobalCtxt {
817     let sess = compiler.session().clone();
818     let cstore = compiler.cstore.clone();
819     let codegen_backend = compiler.codegen_backend().clone();
820     let crate_name = crate_name.to_string();
821
822     let ((), result) = BoxedGlobalCtxt::new(static move || {
823         let sess = &*sess;
824         let cstore = &*cstore;
825
826         let global_ctxt: Option<GlobalCtxt<'_>>;
827         let arenas = AllArenas::new();
828
829         // Construct the HIR map
830         let hir_map = time(sess, "indexing hir", || {
831             hir::map::map_crate(sess, cstore, &mut hir_forest, &defs)
832         });
833
834         let query_result_on_disk_cache = time(sess, "load query result cache", || {
835             rustc_incremental::load_query_result_cache(sess)
836         });
837
838         let mut local_providers = ty::query::Providers::default();
839         default_provide(&mut local_providers);
840         codegen_backend.provide(&mut local_providers);
841
842         let mut extern_providers = local_providers;
843         default_provide_extern(&mut extern_providers);
844         codegen_backend.provide_extern(&mut extern_providers);
845
846         let gcx = TyCtxt::create_global_ctxt(
847             sess,
848             cstore,
849             local_providers,
850             extern_providers,
851             &arenas,
852             resolutions,
853             hir_map,
854             query_result_on_disk_cache,
855             &crate_name,
856             tx,
857             &outputs
858         );
859
860         global_ctxt = Some(gcx);
861         let gcx = global_ctxt.as_ref().unwrap();
862
863         ty::tls::enter_global(gcx, |tcx| {
864             // Do some initialization of the DepGraph that can only be done with the
865             // tcx available.
866             time(tcx.sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
867         });
868
869         yield BoxedGlobalCtxt::initial_yield(());
870         box_region_allow_access!(for('gcx), (&'gcx GlobalCtxt<'gcx>), (gcx));
871
872         if sess.opts.debugging_opts.query_stats {
873             gcx.queries.print_stats();
874         }
875     });
876
877     result
878 }
879
880 /// Runs the resolution, type-checking, region checking and other
881 /// miscellaneous analysis passes on the crate.
882 fn analysis<'tcx>(
883     tcx: TyCtxt<'_, 'tcx, 'tcx>,
884     cnum: CrateNum,
885 ) -> Result<()> {
886     assert_eq!(cnum, LOCAL_CRATE);
887
888     let sess = tcx.sess;
889     let mut entry_point = None;
890
891     time(sess, "misc checking 1", || {
892         parallel!({
893             entry_point = time(sess, "looking for entry point", || {
894                 middle::entry::find_entry_point(tcx)
895             });
896
897             time(sess, "looking for plugin registrar", || {
898                 plugin::build::find_plugin_registrar(tcx)
899             });
900
901             time(sess, "looking for derive registrar", || {
902                 proc_macro_decls::find(tcx)
903             });
904         }, {
905             par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
906                 tcx.ensure().check_mod_loops(tcx.hir().local_def_id(module));
907                 tcx.ensure().check_mod_attrs(tcx.hir().local_def_id(module));
908                 tcx.ensure().check_mod_unstable_api_usage(tcx.hir().local_def_id(module));
909             });
910         });
911     });
912
913     // passes are timed inside typeck
914     typeck::check_crate(tcx)?;
915
916     time(sess, "misc checking 2", || {
917         parallel!({
918             time(sess, "rvalue promotion + match checking", || {
919                 tcx.par_body_owners(|def_id| {
920                     tcx.ensure().const_is_rvalue_promotable_to_static(def_id);
921                     tcx.ensure().check_match(def_id);
922                 });
923             });
924         }, {
925             time(sess, "liveness checking + intrinsic checking", || {
926                 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
927                     // this must run before MIR dump, because
928                     // "not all control paths return a value" is reported here.
929                     //
930                     // maybe move the check to a MIR pass?
931                     tcx.ensure().check_mod_liveness(tcx.hir().local_def_id(module));
932
933                     tcx.ensure().check_mod_intrinsics(tcx.hir().local_def_id(module));
934                 });
935             });
936         });
937     });
938
939     time(sess, "borrow checking", || {
940         if tcx.use_ast_borrowck() {
941             borrowck::check_crate(tcx);
942         }
943     });
944
945     time(sess, "MIR borrow checking", || {
946         tcx.par_body_owners(|def_id| tcx.ensure().mir_borrowck(def_id));
947     });
948
949     time(sess, "dumping chalk-like clauses", || {
950         rustc_traits::lowering::dump_program_clauses(tcx);
951     });
952
953     time(sess, "MIR effect checking", || {
954         for def_id in tcx.body_owners() {
955             mir::transform::check_unsafety::check_unsafety(tcx, def_id)
956         }
957     });
958
959     time(sess, "layout testing", || layout_test::test_layout(tcx));
960
961     // Avoid overwhelming user with errors if borrow checking failed.
962     // I'm not sure how helpful this is, to be honest, but it avoids a
963     // lot of annoying errors in the compile-fail tests (basically,
964     // lint warnings and so on -- kindck used to do this abort, but
965     // kindck is gone now). -nmatsakis
966     if sess.err_count() > 0 {
967         return Err(ErrorReported);
968     }
969
970     time(sess, "misc checking 3", || {
971         parallel!({
972             time(sess, "privacy access levels", || {
973                 tcx.ensure().privacy_access_levels(LOCAL_CRATE);
974             });
975             parallel!({
976                 time(sess, "private in public", || {
977                     tcx.ensure().check_private_in_public(LOCAL_CRATE);
978                 });
979             }, {
980                 time(sess, "death checking", || middle::dead::check_crate(tcx));
981             },  {
982                 time(sess, "unused lib feature checking", || {
983                     stability::check_unused_or_stable_features(tcx)
984                 });
985             }, {
986                 time(sess, "lint checking", || {
987                     lint::check_crate(tcx, || rustc_lint::BuiltinCombinedLateLintPass::new());
988                 });
989             });
990         }, {
991             time(sess, "privacy checking modules", || {
992                 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
993                     tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module));
994                 });
995             });
996         });
997     });
998
999     Ok(())
1000 }
1001
1002 fn encode_metadata<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> (middle::cstore::EncodedMetadata, bool) {
1003     #[derive(PartialEq, Eq, PartialOrd, Ord)]
1004     enum MetadataKind {
1005         None,
1006         Uncompressed,
1007         Compressed
1008     }
1009
1010     let metadata_kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
1011         match *ty {
1012             CrateType::Executable |
1013             CrateType::Staticlib |
1014             CrateType::Cdylib => MetadataKind::None,
1015
1016             CrateType::Rlib => MetadataKind::Uncompressed,
1017
1018             CrateType::Dylib |
1019             CrateType::ProcMacro => MetadataKind::Compressed,
1020         }
1021     }).max().unwrap_or(MetadataKind::None);
1022
1023     let need_metadata_module = metadata_kind == MetadataKind::Compressed;
1024
1025     let metadata = match metadata_kind {
1026         MetadataKind::None => middle::cstore::EncodedMetadata::new(),
1027         MetadataKind::Uncompressed |
1028         MetadataKind::Compressed => tcx.encode_metadata(),
1029     };
1030
1031     (metadata, need_metadata_module)
1032 }
1033
1034 /// Runs the codegen backend, after which the AST and analysis can
1035 /// be discarded.
1036 pub fn start_codegen<'tcx>(
1037     codegen_backend: &dyn CodegenBackend,
1038     tcx: TyCtxt<'_, 'tcx, 'tcx>,
1039     rx: mpsc::Receiver<Box<dyn Any + Send>>,
1040     outputs: &OutputFilenames,
1041 ) -> Box<dyn Any> {
1042     if log_enabled!(::log::Level::Info) {
1043         println!("Pre-codegen");
1044         tcx.print_debug_stats();
1045     }
1046
1047     time(tcx.sess, "resolving dependency formats", || {
1048         middle::dependency_format::calculate(tcx)
1049     });
1050
1051     let (metadata, need_metadata_module) = time(tcx.sess, "metadata encoding", || {
1052         encode_metadata(tcx)
1053     });
1054
1055     tcx.sess.profiler(|p| p.start_activity("codegen crate"));
1056     let codegen = time(tcx.sess, "codegen", move || {
1057         codegen_backend.codegen_crate(tcx, metadata, need_metadata_module, rx)
1058     });
1059     tcx.sess.profiler(|p| p.end_activity("codegen crate"));
1060
1061     if log_enabled!(::log::Level::Info) {
1062         println!("Post-codegen");
1063         tcx.print_debug_stats();
1064     }
1065
1066     if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1067         if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
1068             tcx.sess.err(&format!("could not emit MIR: {}", e));
1069             tcx.sess.abort_if_errors();
1070         }
1071     }
1072
1073     codegen
1074 }