1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::dep_graph::DepGraph;
12 use rustc::hir::{self, map as hir_map};
13 use rustc::hir::lowering::lower_crate;
14 use rustc::ich::Fingerprint;
15 use rustc_data_structures::stable_hasher::StableHasher;
17 use rustc::session::{Session, CompileResult, CrateDisambiguator};
18 use rustc::session::CompileIncomplete;
19 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
20 use rustc::session::search_paths::PathKind;
22 use rustc::middle::{self, stability, reachable, resolve_lifetime};
23 use rustc::middle::cstore::CrateStore;
24 use rustc::middle::privacy::AccessLevels;
25 use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
27 use rustc::util::common::{ErrorReported, time, install_panic_hook};
28 use rustc_allocator as allocator;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental;
31 use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
34 use rustc_trans_utils::trans_crate::TransCrate;
35 use rustc_typeck as typeck;
37 use rustc_plugin::registry::Registry;
38 use rustc_plugin as plugin;
39 use rustc_passes::{self, ast_validation, loops, consts, hir_stats};
40 use rustc_mir::const_eval::check_match;
41 use super::Compilation;
47 use std::ffi::{OsString, OsStr};
49 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
52 use rustc_data_structures::sync::Lrc;
54 use syntax::{self, ast, attr, diagnostics, visit};
55 use syntax::ext::base::ExtCtxt;
56 use syntax::fold::Folder;
57 use syntax::parse::{self, PResult};
58 use syntax::util::node_count::NodeCounter;
59 use syntax_pos::FileName;
63 use pretty::ReplaceBodyWithLoop;
67 pub fn compile_input(trans: Box<TransCrate>,
70 input_path: &Option<PathBuf>,
72 outdir: &Option<PathBuf>,
73 output: &Option<PathBuf>,
74 addl_plugins: Option<Vec<String>>,
75 control: &CompileController) -> CompileResult {
76 macro_rules! controller_entry_point {
77 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
78 let state = &mut $make_state;
79 let phase_result: &CompileResult = &$phase_result;
80 if phase_result.is_ok() || control.$point.run_callback_on_error {
81 (control.$point.callback)(state);
84 if control.$point.stop == Compilation::Stop {
85 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
86 // if there are no errors?
87 return $tsess.compile_status();
92 if sess.profile_queries() {
96 // We need nested scopes here, because the intermediate results can keep
97 // large chunks of memory alive and we want to free them as soon as
98 // possible to keep the peak memory usage low
99 let (outputs, ongoing_trans, dep_graph) = {
100 let krate = match phase_1_parse_input(control, sess, input) {
102 Err(mut parse_error) => {
104 return Err(CompileIncomplete::Errored(ErrorReported));
108 let (krate, registry) = {
109 let mut compile_state = CompileState::state_after_parse(input,
115 controller_entry_point!(after_parse,
120 (compile_state.krate.unwrap(), compile_state.registry)
123 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
125 ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
126 install_panic_hook();
128 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
129 phase_2_configure_and_expand(
136 control.make_glob_map,
138 let mut state = CompileState::state_after_expand(
139 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
141 controller_entry_point!(after_expand, sess, state, Ok(()));
147 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
149 // Ensure the source file isn't accidentally overwritten during compilation.
150 if let Some(ref input_path) = *input_path {
151 if sess.opts.will_create_output_file() {
152 if output_contains_path(&output_paths, input_path) {
154 "the input file \"{}\" would be overwritten by the generated \
156 input_path.display()));
157 return Err(CompileIncomplete::Stopped);
159 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
161 "the generated executable for the input file \"{}\" conflicts with the \
162 existing directory \"{}\"",
163 input_path.display(), dir_path.display()));
164 return Err(CompileIncomplete::Stopped);
169 write_out_deps(sess, &outputs, &output_paths);
170 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
171 sess.opts.output_types.keys().count() == 1 {
175 if let &Some(ref dir) = outdir {
176 if fs::create_dir_all(dir).is_err() {
177 sess.err("failed to find or create the directory specified by --out-dir");
178 return Err(CompileIncomplete::Stopped);
182 let arenas = AllArenas::new();
184 // Construct the HIR map
185 let hir_map = time(sess.time_passes(),
187 || hir_map::map_crate(sess, cstore, &mut hir_forest, &defs));
190 hir_map.dep_graph.assert_ignored();
191 controller_entry_point!(after_hir_lowering,
193 CompileState::state_after_hir_lowering(input,
209 let opt_crate = if control.keep_ast {
210 Some(&expanded_crate)
212 drop(expanded_crate);
216 phase_3_run_analysis_passes(&*trans,
226 |tcx, analysis, rx, result| {
228 // Eventually, we will want to track plugins.
229 tcx.dep_graph.with_ignore(|| {
230 let mut state = CompileState::state_after_analysis(input,
239 (control.after_analysis.callback)(&mut state);
242 if control.after_analysis.stop == Compilation::Stop {
243 return result.and_then(|_| Err(CompileIncomplete::Stopped));
249 if log_enabled!(::log::Level::Info) {
250 println!("Pre-trans");
251 tcx.print_debug_stats();
254 let ongoing_trans = phase_4_translate_to_llvm(&*trans, tcx, rx);
256 if log_enabled!(::log::Level::Info) {
257 println!("Post-trans");
258 tcx.print_debug_stats();
261 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
262 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
263 sess.err(&format!("could not emit MIR: {}", e));
264 sess.abort_if_errors();
268 Ok((outputs.clone(), ongoing_trans, tcx.dep_graph.clone()))
272 if sess.opts.debugging_opts.print_type_sizes {
273 sess.code_stats.borrow().print_type_sizes();
276 trans.join_trans_and_link(ongoing_trans, sess, &dep_graph, &outputs)?;
278 if sess.opts.debugging_opts.perf_stats {
279 sess.print_perf_stats();
282 controller_entry_point!(
285 CompileState::state_when_compilation_done(input, sess, outdir, output),
292 pub fn source_name(input: &Input) -> FileName {
294 Input::File(ref ifile) => ifile.clone().into(),
295 Input::Str { ref name, .. } => name.clone(),
299 /// CompileController is used to customize compilation, it allows compilation to
300 /// be stopped and/or to call arbitrary code at various points in compilation.
301 /// It also allows for various flags to be set to influence what information gets
302 /// collected during compilation.
304 /// This is a somewhat higher level controller than a Session - the Session
305 /// controls what happens in each phase, whereas the CompileController controls
306 /// whether a phase is run at all and whether other code (from outside the
307 /// compiler) is run between phases.
309 /// Note that if compilation is set to stop and a callback is provided for a
310 /// given entry point, the callback is called before compilation is stopped.
312 /// Expect more entry points to be added in the future.
313 pub struct CompileController<'a> {
314 pub after_parse: PhaseController<'a>,
315 pub after_expand: PhaseController<'a>,
316 pub after_hir_lowering: PhaseController<'a>,
317 pub after_analysis: PhaseController<'a>,
318 pub compilation_done: PhaseController<'a>,
320 // FIXME we probably want to group the below options together and offer a
321 // better API, rather than this ad-hoc approach.
322 pub make_glob_map: MakeGlobMap,
323 // Whether the compiler should keep the ast beyond parsing.
325 // -Zcontinue-parse-after-error
326 pub continue_parse_after_error: bool,
328 /// Allows overriding default rustc query providers,
329 /// after `default_provide` has installed them.
330 pub provide: Box<Fn(&mut ty::maps::Providers) + 'a>,
331 /// Same as `provide`, but only for non-local crates,
332 /// applied after `default_provide_extern`.
333 pub provide_extern: Box<Fn(&mut ty::maps::Providers) + 'a>,
336 impl<'a> CompileController<'a> {
337 pub fn basic() -> CompileController<'a> {
339 after_parse: PhaseController::basic(),
340 after_expand: PhaseController::basic(),
341 after_hir_lowering: PhaseController::basic(),
342 after_analysis: PhaseController::basic(),
343 compilation_done: PhaseController::basic(),
344 make_glob_map: MakeGlobMap::No,
346 continue_parse_after_error: false,
348 provide_extern: box |_| {},
353 pub struct PhaseController<'a> {
354 pub stop: Compilation,
355 // If true then the compiler will try to run the callback even if the phase
356 // ends with an error. Note that this is not always possible.
357 pub run_callback_on_error: bool,
358 pub callback: Box<Fn(&mut CompileState) + 'a>,
361 impl<'a> PhaseController<'a> {
362 pub fn basic() -> PhaseController<'a> {
364 stop: Compilation::Continue,
365 run_callback_on_error: false,
366 callback: box |_| {},
371 /// State that is passed to a callback. What state is available depends on when
372 /// during compilation the callback is made. See the various constructor methods
373 /// (`state_*`) in the impl to see which data is provided for any given entry point.
374 pub struct CompileState<'a, 'tcx: 'a> {
375 pub input: &'a Input,
376 pub session: &'tcx Session,
377 pub krate: Option<ast::Crate>,
378 pub registry: Option<Registry<'a>>,
379 pub cstore: Option<&'tcx CStore>,
380 pub crate_name: Option<&'a str>,
381 pub output_filenames: Option<&'a OutputFilenames>,
382 pub out_dir: Option<&'a Path>,
383 pub out_file: Option<&'a Path>,
384 pub arenas: Option<&'tcx AllArenas<'tcx>>,
385 pub expanded_crate: Option<&'a ast::Crate>,
386 pub hir_crate: Option<&'a hir::Crate>,
387 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
388 pub resolutions: Option<&'a Resolutions>,
389 pub analysis: Option<&'a ty::CrateAnalysis>,
390 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
393 impl<'a, 'tcx> CompileState<'a, 'tcx> {
394 fn empty(input: &'a Input,
395 session: &'tcx Session,
396 out_dir: &'a Option<PathBuf>)
401 out_dir: out_dir.as_ref().map(|s| &**s),
408 output_filenames: None,
409 expanded_crate: None,
418 fn state_after_parse(input: &'a Input,
419 session: &'tcx Session,
420 out_dir: &'a Option<PathBuf>,
421 out_file: &'a Option<PathBuf>,
423 cstore: &'tcx CStore)
426 // Initialize the registry before moving `krate`
427 registry: Some(Registry::new(&session, krate.span)),
429 cstore: Some(cstore),
430 out_file: out_file.as_ref().map(|s| &**s),
431 ..CompileState::empty(input, session, out_dir)
435 fn state_after_expand(input: &'a Input,
436 session: &'tcx Session,
437 out_dir: &'a Option<PathBuf>,
438 out_file: &'a Option<PathBuf>,
439 cstore: &'tcx CStore,
440 expanded_crate: &'a ast::Crate,
444 crate_name: Some(crate_name),
445 cstore: Some(cstore),
446 expanded_crate: Some(expanded_crate),
447 out_file: out_file.as_ref().map(|s| &**s),
448 ..CompileState::empty(input, session, out_dir)
452 fn state_after_hir_lowering(input: &'a Input,
453 session: &'tcx Session,
454 out_dir: &'a Option<PathBuf>,
455 out_file: &'a Option<PathBuf>,
456 arenas: &'tcx AllArenas<'tcx>,
457 cstore: &'tcx CStore,
458 hir_map: &'a hir_map::Map<'tcx>,
459 analysis: &'a ty::CrateAnalysis,
460 resolutions: &'a Resolutions,
461 krate: &'a ast::Crate,
462 hir_crate: &'a hir::Crate,
463 output_filenames: &'a OutputFilenames,
467 crate_name: Some(crate_name),
468 arenas: Some(arenas),
469 cstore: Some(cstore),
470 hir_map: Some(hir_map),
471 analysis: Some(analysis),
472 resolutions: Some(resolutions),
473 expanded_crate: Some(krate),
474 hir_crate: Some(hir_crate),
475 output_filenames: Some(output_filenames),
476 out_file: out_file.as_ref().map(|s| &**s),
477 ..CompileState::empty(input, session, out_dir)
481 fn state_after_analysis(input: &'a Input,
482 session: &'tcx Session,
483 out_dir: &'a Option<PathBuf>,
484 out_file: &'a Option<PathBuf>,
485 krate: Option<&'a ast::Crate>,
486 hir_crate: &'a hir::Crate,
487 analysis: &'a ty::CrateAnalysis,
488 tcx: TyCtxt<'a, 'tcx, 'tcx>,
492 analysis: Some(analysis),
494 expanded_crate: krate,
495 hir_crate: Some(hir_crate),
496 crate_name: Some(crate_name),
497 out_file: out_file.as_ref().map(|s| &**s),
498 ..CompileState::empty(input, session, out_dir)
502 fn state_when_compilation_done(input: &'a Input,
503 session: &'tcx Session,
504 out_dir: &'a Option<PathBuf>,
505 out_file: &'a Option<PathBuf>)
508 out_file: out_file.as_ref().map(|s| &**s),
509 ..CompileState::empty(input, session, out_dir)
514 pub fn phase_1_parse_input<'a>(control: &CompileController,
517 -> PResult<'a, ast::Crate> {
518 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
520 if sess.profile_queries() {
524 let krate = time(sess.time_passes(), "parsing", || {
526 Input::File(ref file) => {
527 parse::parse_crate_from_file(file, &sess.parse_sess)
529 Input::Str { ref input, ref name } => {
530 parse::parse_crate_from_source_str(name.clone(),
537 sess.diagnostic().set_continue_after_error(true);
539 if sess.opts.debugging_opts.ast_json_noexpand {
540 println!("{}", json::as_json(&krate));
543 if sess.opts.debugging_opts.input_stats {
544 println!("Lines of code: {}", sess.codemap().count_lines());
545 println!("Pre-expansion node count: {}", count_nodes(&krate));
548 if let Some(ref s) = sess.opts.debugging_opts.show_span {
549 syntax::show_span::run(sess.diagnostic(), s, &krate);
552 if sess.opts.debugging_opts.hir_stats {
553 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
559 fn count_nodes(krate: &ast::Crate) -> usize {
560 let mut counter = NodeCounter::new();
561 visit::walk_crate(&mut counter, krate);
565 // For continuing compilation after a parsed crate has been
568 pub struct ExpansionResult {
569 pub expanded_crate: ast::Crate,
570 pub defs: hir_map::Definitions,
571 pub analysis: ty::CrateAnalysis,
572 pub resolutions: Resolutions,
573 pub hir_forest: hir_map::Forest,
576 pub struct InnerExpansionResult<'a> {
577 pub expanded_crate: ast::Crate,
578 pub resolver: Resolver<'a>,
579 pub hir_forest: hir_map::Forest,
582 /// Run the "early phases" of the compiler: initial `cfg` processing,
583 /// loading compiler plugins (including those from `addl_plugins`),
584 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
585 /// harness if one is to be provided, injection of a dependency on the
586 /// standard library and prelude, and name resolution.
588 /// Returns `None` if we're aborting after handling -W help.
589 pub fn phase_2_configure_and_expand<F>(sess: &Session,
592 registry: Option<Registry>,
594 addl_plugins: Option<Vec<String>>,
595 make_glob_map: MakeGlobMap,
597 -> Result<ExpansionResult, CompileIncomplete>
598 where F: FnOnce(&ast::Crate) -> CompileResult {
599 // Currently, we ignore the name resolution data structures for the purposes of dependency
600 // tracking. Instead we will run name resolution and include its output in the hash of each
601 // item, much like we do for macro expansion. In other words, the hash reflects not just
602 // its contents but the results of name resolution on those contents. Hopefully we'll push
603 // this back at some point.
604 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
605 let resolver_arenas = Resolver::arenas();
606 let result = phase_2_configure_and_expand_inner(sess, cstore, krate, registry, crate_name,
607 addl_plugins, make_glob_map, &resolver_arenas,
608 &mut crate_loader, after_expand);
610 Ok(InnerExpansionResult {expanded_crate, resolver, hir_forest}) => {
613 defs: resolver.definitions,
615 resolutions: Resolutions {
616 freevars: resolver.freevars,
617 export_map: resolver.export_map,
618 trait_map: resolver.trait_map,
619 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
620 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
623 analysis: ty::CrateAnalysis {
624 access_levels: Lrc::new(AccessLevels::default()),
625 name: crate_name.to_string(),
626 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
634 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
636 pub fn phase_2_configure_and_expand_inner<'a, F>(sess: &'a Session,
639 registry: Option<Registry>,
641 addl_plugins: Option<Vec<String>>,
642 make_glob_map: MakeGlobMap,
643 resolver_arenas: &'a ResolverArenas<'a>,
644 crate_loader: &'a mut CrateLoader,
646 -> Result<InnerExpansionResult<'a>, CompileIncomplete>
647 where F: FnOnce(&ast::Crate) -> CompileResult,
649 let time_passes = sess.time_passes();
651 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
652 // these need to be set "early" so that expansion sees `quote` if enabled.
653 sess.init_features(features);
655 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
657 let disambiguator = compute_crate_disambiguator(sess);
658 *sess.crate_disambiguator.borrow_mut() = Some(disambiguator);
659 rustc_incremental::prepare_session_directory(
665 if sess.opts.incremental.is_some() {
666 time(time_passes, "garbage collect incremental cache directory", || {
667 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
668 warn!("Error while trying to garbage collect incremental \
669 compilation cache directory: {}", e);
674 // If necessary, compute the dependency graph (in the background).
675 let future_dep_graph = if sess.opts.build_dep_graph() {
676 Some(rustc_incremental::load_dep_graph(sess, time_passes))
681 time(time_passes, "recursion limit", || {
682 middle::recursion_limit::update_limits(sess, &krate);
685 krate = time(time_passes, "crate injection", || {
686 let alt_std_name = sess.opts.alt_std_name.clone();
687 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
690 let mut addl_plugins = Some(addl_plugins);
691 let registrars = time(time_passes, "plugin loading", || {
692 plugin::load::load_plugins(sess,
696 addl_plugins.take().unwrap())
699 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
701 time(time_passes, "plugin registration", || {
702 if sess.features_untracked().rustc_diagnostic_macros {
703 registry.register_macro("__diagnostic_used",
704 diagnostics::plugin::expand_diagnostic_used);
705 registry.register_macro("__register_diagnostic",
706 diagnostics::plugin::expand_register_diagnostic);
707 registry.register_macro("__build_diagnostic_array",
708 diagnostics::plugin::expand_build_diagnostic_array);
711 for registrar in registrars {
712 registry.args_hidden = Some(registrar.args);
713 (registrar.fun)(&mut registry);
717 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
718 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
719 llvm_passes, attributes, .. } = registry;
721 sess.track_errors(|| {
722 let mut ls = sess.lint_store.borrow_mut();
723 for pass in early_lint_passes {
724 ls.register_early_pass(Some(sess), true, pass);
726 for pass in late_lint_passes {
727 ls.register_late_pass(Some(sess), true, pass);
730 for (name, to) in lint_groups {
731 ls.register_group(Some(sess), true, name, to);
734 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
735 *sess.plugin_attributes.borrow_mut() = attributes.clone();
738 // Lint plugins are registered; now we can process command line flags.
739 if sess.opts.describe_lints {
740 super::describe_lints(&sess, &sess.lint_store.borrow(), true);
741 return Err(CompileIncomplete::Stopped);
744 let mut resolver = Resolver::new(sess,
751 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
752 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features_untracked().quote);
754 krate = time(time_passes, "expansion", || {
755 // Windows dlls do not have rpaths, so they don't know how to find their
756 // dependencies. It's up to us to tell the system where to find all the
757 // dependent dlls. Note that this uses cfg!(windows) as opposed to
758 // targ_cfg because syntax extensions are always loaded for the host
759 // compiler, not for the target.
761 // This is somewhat of an inherently racy operation, however, as
762 // multiple threads calling this function could possibly continue
763 // extending PATH far beyond what it should. To solve this for now we
764 // just don't add any new elements to PATH which are already there
765 // within PATH. This is basically a targeted fix at #17360 for rustdoc
766 // which runs rustc in parallel but has been seen (#33844) to cause
767 // problems with PATH becoming too long.
768 let mut old_path = OsString::new();
770 old_path = env::var_os("PATH").unwrap_or(old_path);
771 let mut new_path = sess.host_filesearch(PathKind::All)
772 .get_dylib_search_paths();
773 for path in env::split_paths(&old_path) {
774 if !new_path.contains(&path) {
779 &env::join_paths(new_path.iter()
780 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
783 let features = sess.features_untracked();
784 let cfg = syntax::ext::expand::ExpansionConfig {
785 features: Some(&features),
786 recursion_limit: sess.recursion_limit.get(),
787 trace_mac: sess.opts.debugging_opts.trace_macros,
788 should_test: sess.opts.test,
789 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
792 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
793 let err_count = ecx.parse_sess.span_diagnostic.err_count();
795 let krate = ecx.monotonic_expander().expand_crate(krate);
797 ecx.check_unused_macros();
799 let mut missing_fragment_specifiers: Vec<_> =
800 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
801 missing_fragment_specifiers.sort();
802 for span in missing_fragment_specifiers {
803 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
804 let msg = "missing fragment specifier";
805 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
807 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
808 ecx.parse_sess.span_diagnostic.abort_if_errors();
811 env::set_var("PATH", &old_path);
816 krate = time(time_passes, "maybe building test harness", || {
817 syntax::test::modify_for_testing(&sess.parse_sess,
822 &sess.features_untracked())
825 // If we're actually rustdoc then there's no need to actually compile
826 // anything, so switch everything to just looping
827 if sess.opts.actually_rustdoc {
828 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
831 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
832 // bunch of checks in the `modify` function below. For now just skip this
833 // step entirely if we're rustdoc as it's not too useful anyway.
834 if !sess.opts.actually_rustdoc {
835 krate = time(time_passes, "maybe creating a macro crate", || {
836 let crate_types = sess.crate_types.borrow();
837 let num_crate_types = crate_types.len();
838 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
839 let is_test_crate = sess.opts.test;
840 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
850 krate = time(time_passes, "creating allocators", || {
851 allocator::expand::modify(&sess.parse_sess,
857 after_expand(&krate)?;
859 if sess.opts.debugging_opts.input_stats {
860 println!("Post-expansion node count: {}", count_nodes(&krate));
863 if sess.opts.debugging_opts.hir_stats {
864 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
867 if sess.opts.debugging_opts.ast_json {
868 println!("{}", json::as_json(&krate));
873 || ast_validation::check_crate(sess, &krate));
875 time(time_passes, "name resolution", || -> CompileResult {
876 resolver.resolve_crate(&krate);
880 if resolver.found_unresolved_macro {
881 sess.parse_sess.span_diagnostic.abort_if_errors();
884 // Needs to go *after* expansion to be able to check the results of macro expansion.
885 time(time_passes, "complete gated feature checking", || {
886 sess.track_errors(|| {
887 syntax::feature_gate::check_crate(&krate,
889 &sess.features_untracked(),
891 sess.opts.unstable_features);
896 // First, we need to collect the dep_graph.
897 let dep_graph = match future_dep_graph {
898 None => DepGraph::new_disabled(),
900 let prev_graph = time(time_passes, "blocked while dep-graph loading finishes", || {
902 .expect("Could not join with background dep_graph thread")
905 DepGraph::new(prev_graph)
908 let hir_forest = time(time_passes, "lowering ast -> hir", || {
909 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
911 if sess.opts.debugging_opts.hir_stats {
912 hir_stats::print_hir_stats(&hir_crate);
915 hir_map::Forest::new(hir_crate, &dep_graph)
920 || lint::check_ast_crate(sess, &krate));
922 // Discard hygiene data, which isn't required after lowering to HIR.
923 if !sess.opts.debugging_opts.keep_hygiene_data {
924 syntax::ext::hygiene::clear_markings();
927 Ok(InnerExpansionResult {
928 expanded_crate: krate,
934 pub fn default_provide(providers: &mut ty::maps::Providers) {
935 hir::provide(providers);
936 borrowck::provide(providers);
937 mir::provide(providers);
938 reachable::provide(providers);
939 resolve_lifetime::provide(providers);
940 rustc_privacy::provide(providers);
941 typeck::provide(providers);
942 ty::provide(providers);
943 traits::provide(providers);
944 reachable::provide(providers);
945 rustc_passes::provide(providers);
946 middle::region::provide(providers);
947 cstore::provide(providers);
948 lint::provide(providers);
951 pub fn default_provide_extern(providers: &mut ty::maps::Providers) {
952 cstore::provide_extern(providers);
955 /// Run the resolution, typechecking, region checking and other
956 /// miscellaneous analysis passes on the crate. Return various
957 /// structures carrying the results of the analysis.
958 pub fn phase_3_run_analysis_passes<'tcx, F, R>(trans: &TransCrate,
959 control: &CompileController,
961 cstore: &'tcx CrateStore,
962 hir_map: hir_map::Map<'tcx>,
963 mut analysis: ty::CrateAnalysis,
964 resolutions: Resolutions,
965 arenas: &'tcx AllArenas<'tcx>,
967 output_filenames: &OutputFilenames,
969 -> Result<R, CompileIncomplete>
970 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
972 mpsc::Receiver<Box<Any + Send>>,
975 let time_passes = sess.time_passes();
977 let query_result_on_disk_cache = time(time_passes,
978 "load query result cache",
979 || rustc_incremental::load_query_result_cache(sess));
982 "looking for entry point",
983 || middle::entry::find_entry_point(sess, &hir_map));
985 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
986 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
988 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
992 || loops::check_crate(sess, &hir_map));
994 let mut local_providers = ty::maps::Providers::default();
995 default_provide(&mut local_providers);
996 trans.provide(&mut local_providers);
997 (control.provide)(&mut local_providers);
999 let mut extern_providers = local_providers;
1000 default_provide_extern(&mut extern_providers);
1001 trans.provide_extern(&mut extern_providers);
1002 (control.provide_extern)(&mut extern_providers);
1004 let (tx, rx) = mpsc::channel();
1006 TyCtxt::create_and_enter(sess,
1013 query_result_on_disk_cache,
1018 // Do some initialization of the DepGraph that can only be done with the
1020 rustc_incremental::dep_graph_tcx_init(tcx);
1022 time(sess.time_passes(), "attribute checking", || {
1023 hir::check_attr::check_crate(tcx)
1027 "stability checking",
1028 || stability::check_unstable_api_usage(tcx));
1030 // passes are timed inside typeck
1031 match typeck::check_crate(tcx) {
1034 f(tcx, analysis, rx, Err(x));
1041 || consts::check_crate(tcx));
1043 analysis.access_levels =
1044 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1047 "intrinsic checking",
1048 || middle::intrinsicck::check_crate(tcx));
1052 || check_match::check_crate(tcx));
1054 // this must run before MIR dump, because
1055 // "not all control paths return a value" is reported here.
1057 // maybe move the check to a MIR pass?
1059 "liveness checking",
1060 || middle::liveness::check_crate(tcx));
1064 || borrowck::check_crate(tcx));
1067 "MIR borrow checking",
1068 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id); });
1071 "MIR effect checking",
1072 || for def_id in tcx.body_owners() {
1073 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1075 // Avoid overwhelming user with errors if type checking failed.
1076 // I'm not sure how helpful this is, to be honest, but it avoids
1078 // lot of annoying errors in the compile-fail tests (basically,
1079 // lint warnings and so on -- kindck used to do this abort, but
1080 // kindck is gone now). -nmatsakis
1081 if sess.err_count() > 0 {
1082 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1085 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1087 time(time_passes, "unused lib feature checking", || {
1088 stability::check_unused_or_stable_features(tcx)
1094 || for def_id in tcx.body_owners() {
1095 mir::const_eval::check::check(tcx, def_id)
1098 time(time_passes, "lint checking", || lint::check_crate(tcx));
1100 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1104 /// Run the translation phase to LLVM, after which the AST and analysis can
1106 pub fn phase_4_translate_to_llvm<'a, 'tcx>(trans: &TransCrate,
1107 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1108 rx: mpsc::Receiver<Box<Any + Send>>)
1110 let time_passes = tcx.sess.time_passes();
1113 "resolving dependency formats",
1114 || ::rustc::middle::dependency_format::calculate(tcx));
1117 time(time_passes, "translation", move || {
1118 trans.trans_crate(tcx, rx)
1120 if tcx.sess.profile_queries() {
1121 profile::dump("profile_queries".to_string())
1127 fn escape_dep_filename(filename: &FileName) -> String {
1128 // Apparently clang and gcc *only* escape spaces:
1129 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1130 filename.to_string().replace(" ", "\\ ")
1133 // Returns all the paths that correspond to generated files.
1134 fn generated_output_paths(sess: &Session,
1135 outputs: &OutputFilenames,
1137 crate_name: &str) -> Vec<PathBuf> {
1138 let mut out_filenames = Vec::new();
1139 for output_type in sess.opts.output_types.keys() {
1140 let file = outputs.path(*output_type);
1141 match *output_type {
1142 // If the filename has been overridden using `-o`, it will not be modified
1143 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1144 OutputType::Exe if !exact_name => {
1145 for crate_type in sess.crate_types.borrow().iter() {
1146 let p = ::rustc_trans_utils::link::filename_for_input(
1152 out_filenames.push(p);
1155 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1156 // Don't add the dep-info output when omitting it from dep-info targets
1159 out_filenames.push(file);
1166 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1167 // returns None for every file path.
1168 fn check_output<F, T>(output_paths: &Vec<PathBuf>, f: F) -> Option<T>
1169 where F: Fn(&PathBuf) -> Option<T> {
1170 for output_path in output_paths {
1171 if let Some(result) = f(output_path) {
1172 return Some(result);
1178 pub fn output_contains_path(output_paths: &Vec<PathBuf>, input_path: &PathBuf) -> bool {
1179 let input_path = input_path.canonicalize().ok();
1180 if input_path.is_none() {
1183 let check = |output_path: &PathBuf| {
1184 if output_path.canonicalize().ok() == input_path {
1188 check_output(output_paths, check).is_some()
1191 pub fn output_conflicts_with_dir(output_paths: &Vec<PathBuf>) -> Option<PathBuf> {
1192 let check = |output_path: &PathBuf| {
1193 if output_path.is_dir() {
1194 Some(output_path.clone())
1197 check_output(output_paths, check)
1200 fn write_out_deps(sess: &Session,
1201 outputs: &OutputFilenames,
1202 out_filenames: &Vec<PathBuf>) {
1203 // Write out dependency rules to the dep-info file if requested
1204 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1207 let deps_filename = outputs.path(OutputType::DepInfo);
1210 (|| -> io::Result<()> {
1211 // Build a list of files used to compile the output and
1212 // write Makefile-compatible dependency rules
1213 let files: Vec<String> = sess.codemap()
1216 .filter(|fmap| fmap.is_real_file())
1217 .filter(|fmap| !fmap.is_imported())
1218 .map(|fmap| escape_dep_filename(&fmap.name))
1220 let mut file = fs::File::create(&deps_filename)?;
1221 for path in out_filenames {
1222 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1225 // Emit a fake target for each input file to the compilation. This
1226 // prevents `make` from spitting out an error if a file is later
1227 // deleted. For more info see #28735
1229 writeln!(file, "{}:", path)?;
1237 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1238 deps_filename.display(),
1244 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1245 // Unconditionally collect crate types from attributes to make them used
1246 let attr_types: Vec<config::CrateType> =
1249 if a.check_name("crate_type") {
1250 match a.value_str() {
1251 Some(ref n) if *n == "rlib" => {
1252 Some(config::CrateTypeRlib)
1254 Some(ref n) if *n == "dylib" => {
1255 Some(config::CrateTypeDylib)
1257 Some(ref n) if *n == "cdylib" => {
1258 Some(config::CrateTypeCdylib)
1260 Some(ref n) if *n == "lib" => {
1261 Some(config::default_lib_output())
1263 Some(ref n) if *n == "staticlib" => {
1264 Some(config::CrateTypeStaticlib)
1266 Some(ref n) if *n == "proc-macro" => {
1267 Some(config::CrateTypeProcMacro)
1269 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1271 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1274 "invalid `crate_type` value");
1278 session.struct_span_err(a.span, "`crate_type` requires a value")
1279 .note("for example: `#![crate_type=\"lib\"]`")
1290 // If we're generating a test executable, then ignore all other output
1291 // styles at all other locations
1292 if session.opts.test {
1293 return vec![config::CrateTypeExecutable];
1296 // Only check command line flags if present. If no types are specified by
1297 // command line, then reuse the empty `base` Vec to hold the types that
1298 // will be found in crate attributes.
1299 let mut base = session.opts.crate_types.clone();
1300 if base.is_empty() {
1301 base.extend(attr_types);
1302 if base.is_empty() {
1303 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1310 .filter(|crate_type| {
1311 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1314 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1316 session.opts.target_triple));
1324 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1325 use std::hash::Hasher;
1327 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1328 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1329 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1330 // should still be safe enough to avoid collisions in practice.
1331 let mut hasher = StableHasher::<Fingerprint>::new();
1333 let mut metadata = session.opts.cg.metadata.clone();
1334 // We don't want the crate_disambiguator to dependent on the order
1335 // -C metadata arguments, so sort them:
1337 // Every distinct -C metadata value is only incorporated once:
1340 hasher.write(b"metadata");
1341 for s in &metadata {
1342 // Also incorporate the length of a metadata string, so that we generate
1343 // different values for `-Cmetadata=ab -Cmetadata=c` and
1344 // `-Cmetadata=a -Cmetadata=bc`
1345 hasher.write_usize(s.len());
1346 hasher.write(s.as_bytes());
1349 // Also incorporate crate type, so that we don't get symbol conflicts when
1350 // linking against a library of the same name, if this is an executable.
1351 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1352 hasher.write(if is_exe { b"exe" } else { b"lib" });
1354 CrateDisambiguator::from(hasher.finish())
1358 pub fn build_output_filenames(input: &Input,
1359 odir: &Option<PathBuf>,
1360 ofile: &Option<PathBuf>,
1361 attrs: &[ast::Attribute],
1363 -> OutputFilenames {
1366 // "-" as input file will cause the parser to read from stdin so we
1367 // have to make up a name
1368 // We want to toss everything after the final '.'
1369 let dirpath = match *odir {
1370 Some(ref d) => d.clone(),
1371 None => PathBuf::new(),
1374 // If a crate name is present, we use it as the link name
1375 let stem = sess.opts
1378 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1379 .unwrap_or(input.filestem());
1382 out_directory: dirpath,
1384 single_output_file: None,
1385 extra: sess.opts.cg.extra_filename.clone(),
1386 outputs: sess.opts.output_types.clone(),
1390 Some(ref out_file) => {
1391 let unnamed_output_types = sess.opts
1394 .filter(|a| a.is_none())
1396 let ofile = if unnamed_output_types > 1 {
1397 sess.warn("due to multiple output types requested, the explicitly specified \
1398 output file name will be adapted for each output type");
1401 Some(out_file.clone())
1404 sess.warn("ignoring --out-dir flag due to -o flag");
1406 if !sess.opts.cg.extra_filename.is_empty() {
1407 sess.warn("ignoring -C extra-filename flag due to -o flag");
1410 let cur_dir = Path::new("");
1413 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1414 out_filestem: out_file.file_stem()
1415 .unwrap_or(OsStr::new(""))
1419 single_output_file: ofile,
1420 extra: sess.opts.cg.extra_filename.clone(),
1421 outputs: sess.opts.output_types.clone(),