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