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};
28 use rustc_allocator as allocator;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental;
31 use rustc_resolve::{MakeGlobMap, Resolver};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
34 use rustc_trans as trans;
35 use rustc_trans_utils::trans_crate::TransCrate;
36 use rustc_typeck as typeck;
38 use rustc_plugin::registry::Registry;
39 use rustc_plugin as plugin;
40 use rustc_passes::{self, ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
41 use rustc_const_eval::{self, check_match};
42 use super::Compilation;
43 use ::DefaultTransCrate;
49 use std::ffi::{OsString, OsStr};
51 use std::io::{self, Write};
53 use std::path::{Path, PathBuf};
56 use syntax::{ast, diagnostics, visit};
58 use syntax::ext::base::ExtCtxt;
59 use syntax::fold::Folder;
60 use syntax::parse::{self, PResult};
61 use syntax::util::node_count::NodeCounter;
62 use syntax_pos::FileName;
67 use pretty::ReplaceBodyWithLoop;
71 pub fn compile_input(sess: &Session,
73 input_path: &Option<PathBuf>,
75 outdir: &Option<PathBuf>,
76 output: &Option<PathBuf>,
77 addl_plugins: Option<Vec<String>>,
78 control: &CompileController) -> CompileResult {
79 use rustc::session::config::CrateType;
81 macro_rules! controller_entry_point {
82 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
83 let state = &mut $make_state;
84 let phase_result: &CompileResult = &$phase_result;
85 if phase_result.is_ok() || control.$point.run_callback_on_error {
86 (control.$point.callback)(state);
89 if control.$point.stop == Compilation::Stop {
90 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
91 // if there are no errors?
92 return $tsess.compile_status();
97 if cfg!(not(feature="llvm")) {
98 for cty in sess.opts.crate_types.iter() {
100 CrateType::CrateTypeRlib | CrateType::CrateTypeDylib |
101 CrateType::CrateTypeExecutable => {},
103 sess.parse_sess.span_diagnostic.warn(
104 &format!("LLVM unsupported, so output type {} is not supported", cty)
110 sess.abort_if_errors();
113 if sess.profile_queries() {
117 // We need nested scopes here, because the intermediate results can keep
118 // large chunks of memory alive and we want to free them as soon as
119 // possible to keep the peak memory usage low
120 let (outputs, trans, dep_graph) = {
121 let krate = match phase_1_parse_input(control, sess, input) {
123 Err(mut parse_error) => {
125 return Err(CompileIncomplete::Errored(ErrorReported));
129 let (krate, registry) = {
130 let mut compile_state = CompileState::state_after_parse(input,
136 controller_entry_point!(after_parse,
141 (compile_state.krate.unwrap(), compile_state.registry)
144 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
146 // Ensure the source file isn't accidentally overwritten during compilation.
148 Some(ref input_path) => {
149 if outputs.contains_path(input_path) && sess.opts.will_create_output_file() {
151 "the input file \"{}\" would be overwritten by the generated executable",
152 input_path.display()));
153 return Err(CompileIncomplete::Stopped);
160 ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
161 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
162 phase_2_configure_and_expand(
169 control.make_glob_map,
171 let mut state = CompileState::state_after_expand(
172 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
174 controller_entry_point!(after_expand, sess, state, Ok(()));
180 write_out_deps(sess, &outputs, &crate_name);
181 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
182 sess.opts.output_types.keys().count() == 1 {
186 let arenas = AllArenas::new();
188 // Construct the HIR map
189 let hir_map = time(sess.time_passes(),
191 || hir_map::map_crate(sess, cstore, &mut hir_forest, &defs));
194 let _ignore = hir_map.dep_graph.in_ignore();
195 controller_entry_point!(after_hir_lowering,
197 CompileState::state_after_hir_lowering(input,
213 time(sess.time_passes(), "attribute checking", || {
214 hir::check_attr::check_crate(sess, &expanded_crate);
217 let opt_crate = if control.keep_ast {
218 Some(&expanded_crate)
220 drop(expanded_crate);
224 phase_3_run_analysis_passes(control,
233 |tcx, analysis, rx, result| {
235 // Eventually, we will want to track plugins.
236 let _ignore = tcx.dep_graph.in_ignore();
238 let mut state = CompileState::state_after_analysis(input,
247 (control.after_analysis.callback)(&mut state);
249 if control.after_analysis.stop == Compilation::Stop {
250 return result.and_then(|_| Err(CompileIncomplete::Stopped));
256 if log_enabled!(::log::LogLevel::Info) {
257 println!("Pre-trans");
258 tcx.print_debug_stats();
261 let trans = phase_4_translate_to_llvm::<DefaultTransCrate>(tcx, rx);
263 if log_enabled!(::log::LogLevel::Info) {
264 println!("Post-trans");
265 tcx.print_debug_stats();
268 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
269 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
270 sess.err(&format!("could not emit MIR: {}", e));
271 sess.abort_if_errors();
275 Ok((outputs.clone(), trans, tcx.dep_graph.clone()))
279 if sess.opts.debugging_opts.print_type_sizes {
280 sess.code_stats.borrow().print_type_sizes();
283 let (phase5_result, trans) =
284 phase_5_run_llvm_passes::<DefaultTransCrate>(sess, &dep_graph, trans);
286 controller_entry_point!(after_llvm,
288 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
292 // Run the linker on any artifacts that resulted from the LLVM run.
293 // This should produce either a finished executable or library.
294 time(sess.time_passes(), "linking", || {
295 DefaultTransCrate::link_binary(sess, &trans, &outputs)
298 // Now that we won't touch anything in the incremental compilation directory
299 // any more, we can finalize it (which involves renaming it)
300 #[cfg(feature="llvm")]
301 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
303 if sess.opts.debugging_opts.perf_stats {
304 sess.print_perf_stats();
307 controller_entry_point!(
310 CompileState::state_when_compilation_done(input, sess, outdir, output),
317 fn keep_hygiene_data(sess: &Session) -> bool {
318 sess.opts.debugging_opts.keep_hygiene_data
321 pub fn source_name(input: &Input) -> FileName {
323 Input::File(ref ifile) => ifile.clone().into(),
324 Input::Str { ref name, .. } => name.clone(),
328 /// CompileController is used to customize compilation, it allows compilation to
329 /// be stopped and/or to call arbitrary code at various points in compilation.
330 /// It also allows for various flags to be set to influence what information gets
331 /// collected during compilation.
333 /// This is a somewhat higher level controller than a Session - the Session
334 /// controls what happens in each phase, whereas the CompileController controls
335 /// whether a phase is run at all and whether other code (from outside the
336 /// compiler) is run between phases.
338 /// Note that if compilation is set to stop and a callback is provided for a
339 /// given entry point, the callback is called before compilation is stopped.
341 /// Expect more entry points to be added in the future.
342 pub struct CompileController<'a> {
343 pub after_parse: PhaseController<'a>,
344 pub after_expand: PhaseController<'a>,
345 pub after_hir_lowering: PhaseController<'a>,
346 pub after_analysis: PhaseController<'a>,
347 pub after_llvm: PhaseController<'a>,
348 pub compilation_done: PhaseController<'a>,
350 // FIXME we probably want to group the below options together and offer a
351 // better API, rather than this ad-hoc approach.
352 pub make_glob_map: MakeGlobMap,
353 // Whether the compiler should keep the ast beyond parsing.
355 // -Zcontinue-parse-after-error
356 pub continue_parse_after_error: bool,
358 /// Allows overriding default rustc query providers,
359 /// after `default_provide` has installed them.
360 pub provide: Box<Fn(&mut ty::maps::Providers) + 'a>,
361 /// Same as `provide`, but only for non-local crates,
362 /// applied after `default_provide_extern`.
363 pub provide_extern: Box<Fn(&mut ty::maps::Providers) + 'a>,
366 impl<'a> CompileController<'a> {
367 pub fn basic() -> CompileController<'a> {
369 after_parse: PhaseController::basic(),
370 after_expand: PhaseController::basic(),
371 after_hir_lowering: PhaseController::basic(),
372 after_analysis: PhaseController::basic(),
373 after_llvm: PhaseController::basic(),
374 compilation_done: PhaseController::basic(),
375 make_glob_map: MakeGlobMap::No,
377 continue_parse_after_error: false,
379 provide_extern: box |_| {},
384 pub struct PhaseController<'a> {
385 pub stop: Compilation,
386 // If true then the compiler will try to run the callback even if the phase
387 // ends with an error. Note that this is not always possible.
388 pub run_callback_on_error: bool,
389 pub callback: Box<Fn(&mut CompileState) + 'a>,
392 impl<'a> PhaseController<'a> {
393 pub fn basic() -> PhaseController<'a> {
395 stop: Compilation::Continue,
396 run_callback_on_error: false,
397 callback: box |_| {},
402 /// State that is passed to a callback. What state is available depends on when
403 /// during compilation the callback is made. See the various constructor methods
404 /// (`state_*`) in the impl to see which data is provided for any given entry point.
405 pub struct CompileState<'a, 'tcx: 'a> {
406 pub input: &'a Input,
407 pub session: &'tcx Session,
408 pub krate: Option<ast::Crate>,
409 pub registry: Option<Registry<'a>>,
410 pub cstore: Option<&'tcx CStore>,
411 pub crate_name: Option<&'a str>,
412 pub output_filenames: Option<&'a OutputFilenames>,
413 pub out_dir: Option<&'a Path>,
414 pub out_file: Option<&'a Path>,
415 pub arenas: Option<&'tcx AllArenas<'tcx>>,
416 pub expanded_crate: Option<&'a ast::Crate>,
417 pub hir_crate: Option<&'a hir::Crate>,
418 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
419 pub resolutions: Option<&'a Resolutions>,
420 pub analysis: Option<&'a ty::CrateAnalysis>,
421 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
422 pub trans: Option<&'a trans::CrateTranslation>,
425 impl<'a, 'tcx> CompileState<'a, 'tcx> {
426 fn empty(input: &'a Input,
427 session: &'tcx Session,
428 out_dir: &'a Option<PathBuf>)
433 out_dir: out_dir.as_ref().map(|s| &**s),
440 output_filenames: None,
441 expanded_crate: None,
451 fn state_after_parse(input: &'a Input,
452 session: &'tcx Session,
453 out_dir: &'a Option<PathBuf>,
454 out_file: &'a Option<PathBuf>,
456 cstore: &'tcx CStore)
459 // Initialize the registry before moving `krate`
460 registry: Some(Registry::new(&session, krate.span)),
462 cstore: Some(cstore),
463 out_file: out_file.as_ref().map(|s| &**s),
464 ..CompileState::empty(input, session, out_dir)
468 fn state_after_expand(input: &'a Input,
469 session: &'tcx Session,
470 out_dir: &'a Option<PathBuf>,
471 out_file: &'a Option<PathBuf>,
472 cstore: &'tcx CStore,
473 expanded_crate: &'a ast::Crate,
477 crate_name: Some(crate_name),
478 cstore: Some(cstore),
479 expanded_crate: Some(expanded_crate),
480 out_file: out_file.as_ref().map(|s| &**s),
481 ..CompileState::empty(input, session, out_dir)
485 fn state_after_hir_lowering(input: &'a Input,
486 session: &'tcx Session,
487 out_dir: &'a Option<PathBuf>,
488 out_file: &'a Option<PathBuf>,
489 arenas: &'tcx AllArenas<'tcx>,
490 cstore: &'tcx CStore,
491 hir_map: &'a hir_map::Map<'tcx>,
492 analysis: &'a ty::CrateAnalysis,
493 resolutions: &'a Resolutions,
494 krate: &'a ast::Crate,
495 hir_crate: &'a hir::Crate,
496 output_filenames: &'a OutputFilenames,
500 crate_name: Some(crate_name),
501 arenas: Some(arenas),
502 cstore: Some(cstore),
503 hir_map: Some(hir_map),
504 analysis: Some(analysis),
505 resolutions: Some(resolutions),
506 expanded_crate: Some(krate),
507 hir_crate: Some(hir_crate),
508 output_filenames: Some(output_filenames),
509 out_file: out_file.as_ref().map(|s| &**s),
510 ..CompileState::empty(input, session, out_dir)
514 fn state_after_analysis(input: &'a Input,
515 session: &'tcx Session,
516 out_dir: &'a Option<PathBuf>,
517 out_file: &'a Option<PathBuf>,
518 krate: Option<&'a ast::Crate>,
519 hir_crate: &'a hir::Crate,
520 analysis: &'a ty::CrateAnalysis,
521 tcx: TyCtxt<'a, 'tcx, 'tcx>,
525 analysis: Some(analysis),
527 expanded_crate: krate,
528 hir_crate: Some(hir_crate),
529 crate_name: Some(crate_name),
530 out_file: out_file.as_ref().map(|s| &**s),
531 ..CompileState::empty(input, session, out_dir)
535 fn state_after_llvm(input: &'a Input,
536 session: &'tcx Session,
537 out_dir: &'a Option<PathBuf>,
538 out_file: &'a Option<PathBuf>,
539 trans: &'a trans::CrateTranslation)
543 out_file: out_file.as_ref().map(|s| &**s),
544 ..CompileState::empty(input, session, out_dir)
548 fn state_when_compilation_done(input: &'a Input,
549 session: &'tcx Session,
550 out_dir: &'a Option<PathBuf>,
551 out_file: &'a Option<PathBuf>)
554 out_file: out_file.as_ref().map(|s| &**s),
555 ..CompileState::empty(input, session, out_dir)
560 pub fn phase_1_parse_input<'a>(control: &CompileController,
563 -> PResult<'a, ast::Crate> {
564 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
566 if sess.profile_queries() {
570 let krate = time(sess.time_passes(), "parsing", || {
572 Input::File(ref file) => {
573 parse::parse_crate_from_file(file, &sess.parse_sess)
575 Input::Str { ref input, ref name } => {
576 parse::parse_crate_from_source_str(name.clone(),
583 sess.diagnostic().set_continue_after_error(true);
585 if sess.opts.debugging_opts.ast_json_noexpand {
586 println!("{}", json::as_json(&krate));
589 if sess.opts.debugging_opts.input_stats {
590 println!("Lines of code: {}", sess.codemap().count_lines());
591 println!("Pre-expansion node count: {}", count_nodes(&krate));
594 if let Some(ref s) = sess.opts.debugging_opts.show_span {
595 syntax::show_span::run(sess.diagnostic(), s, &krate);
598 if sess.opts.debugging_opts.hir_stats {
599 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
605 fn count_nodes(krate: &ast::Crate) -> usize {
606 let mut counter = NodeCounter::new();
607 visit::walk_crate(&mut counter, krate);
611 // For continuing compilation after a parsed crate has been
614 pub struct ExpansionResult {
615 pub expanded_crate: ast::Crate,
616 pub defs: hir_map::Definitions,
617 pub analysis: ty::CrateAnalysis,
618 pub resolutions: Resolutions,
619 pub hir_forest: hir_map::Forest,
622 /// Run the "early phases" of the compiler: initial `cfg` processing,
623 /// loading compiler plugins (including those from `addl_plugins`),
624 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
625 /// harness if one is to be provided, injection of a dependency on the
626 /// standard library and prelude, and name resolution.
628 /// Returns `None` if we're aborting after handling -W help.
629 pub fn phase_2_configure_and_expand<F>(sess: &Session,
632 registry: Option<Registry>,
634 addl_plugins: Option<Vec<String>>,
635 make_glob_map: MakeGlobMap,
637 -> Result<ExpansionResult, CompileIncomplete>
638 where F: FnOnce(&ast::Crate) -> CompileResult,
640 let time_passes = sess.time_passes();
642 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
643 // these need to be set "early" so that expansion sees `quote` if enabled.
644 *sess.features.borrow_mut() = features;
646 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
648 let disambiguator = compute_crate_disambiguator(sess);
649 *sess.crate_disambiguator.borrow_mut() = Some(disambiguator);
650 rustc_incremental::prepare_session_directory(
656 // If necessary, compute the dependency graph (in the background).
657 let future_dep_graph = if sess.opts.build_dep_graph() {
658 Some(rustc_incremental::load_dep_graph(sess, time_passes))
663 time(time_passes, "recursion limit", || {
664 middle::recursion_limit::update_limits(sess, &krate);
667 krate = time(time_passes, "crate injection", || {
668 let alt_std_name = sess.opts.alt_std_name.clone();
669 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
672 let mut addl_plugins = Some(addl_plugins);
673 let registrars = time(time_passes, "plugin loading", || {
674 plugin::load::load_plugins(sess,
678 addl_plugins.take().unwrap())
681 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
683 time(time_passes, "plugin registration", || {
684 if sess.features.borrow().rustc_diagnostic_macros {
685 registry.register_macro("__diagnostic_used",
686 diagnostics::plugin::expand_diagnostic_used);
687 registry.register_macro("__register_diagnostic",
688 diagnostics::plugin::expand_register_diagnostic);
689 registry.register_macro("__build_diagnostic_array",
690 diagnostics::plugin::expand_build_diagnostic_array);
693 for registrar in registrars {
694 registry.args_hidden = Some(registrar.args);
695 (registrar.fun)(&mut registry);
699 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
700 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
701 llvm_passes, attributes, .. } = registry;
703 sess.track_errors(|| {
704 let mut ls = sess.lint_store.borrow_mut();
705 for pass in early_lint_passes {
706 ls.register_early_pass(Some(sess), true, pass);
708 for pass in late_lint_passes {
709 ls.register_late_pass(Some(sess), true, pass);
712 for (name, to) in lint_groups {
713 ls.register_group(Some(sess), true, name, to);
716 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
717 *sess.plugin_attributes.borrow_mut() = attributes.clone();
720 // Lint plugins are registered; now we can process command line flags.
721 if sess.opts.describe_lints {
722 super::describe_lints(&sess.lint_store.borrow(), true);
723 return Err(CompileIncomplete::Stopped);
726 // Currently, we ignore the name resolution data structures for the purposes of dependency
727 // tracking. Instead we will run name resolution and include its output in the hash of each
728 // item, much like we do for macro expansion. In other words, the hash reflects not just
729 // its contents but the results of name resolution on those contents. Hopefully we'll push
730 // this back at some point.
731 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
732 let resolver_arenas = Resolver::arenas();
733 let mut resolver = Resolver::new(sess,
740 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
741 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
743 krate = time(time_passes, "expansion", || {
744 // Windows dlls do not have rpaths, so they don't know how to find their
745 // dependencies. It's up to us to tell the system where to find all the
746 // dependent dlls. Note that this uses cfg!(windows) as opposed to
747 // targ_cfg because syntax extensions are always loaded for the host
748 // compiler, not for the target.
750 // This is somewhat of an inherently racy operation, however, as
751 // multiple threads calling this function could possibly continue
752 // extending PATH far beyond what it should. To solve this for now we
753 // just don't add any new elements to PATH which are already there
754 // within PATH. This is basically a targeted fix at #17360 for rustdoc
755 // which runs rustc in parallel but has been seen (#33844) to cause
756 // problems with PATH becoming too long.
757 let mut old_path = OsString::new();
759 old_path = env::var_os("PATH").unwrap_or(old_path);
760 let mut new_path = sess.host_filesearch(PathKind::All)
761 .get_dylib_search_paths();
762 for path in env::split_paths(&old_path) {
763 if !new_path.contains(&path) {
768 &env::join_paths(new_path.iter()
769 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
772 let features = sess.features.borrow();
773 let cfg = syntax::ext::expand::ExpansionConfig {
774 features: Some(&features),
775 recursion_limit: sess.recursion_limit.get(),
776 trace_mac: sess.opts.debugging_opts.trace_macros,
777 should_test: sess.opts.test,
778 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
781 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
782 let err_count = ecx.parse_sess.span_diagnostic.err_count();
784 let krate = ecx.monotonic_expander().expand_crate(krate);
786 ecx.check_unused_macros();
788 let mut missing_fragment_specifiers: Vec<_> =
789 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
790 missing_fragment_specifiers.sort();
791 for span in missing_fragment_specifiers {
792 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
793 let msg = "missing fragment specifier";
794 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
796 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
797 ecx.parse_sess.span_diagnostic.abort_if_errors();
800 env::set_var("PATH", &old_path);
805 krate = time(time_passes, "maybe building test harness", || {
806 syntax::test::modify_for_testing(&sess.parse_sess,
813 // If we're actually rustdoc then there's no need to actually compile
814 // anything, so switch everything to just looping
815 if sess.opts.actually_rustdoc {
816 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
819 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
820 // bunch of checks in the `modify` function below. For now just skip this
821 // step entirely if we're rustdoc as it's not too useful anyway.
822 if !sess.opts.actually_rustdoc {
823 krate = time(time_passes, "maybe creating a macro crate", || {
824 let crate_types = sess.crate_types.borrow();
825 let num_crate_types = crate_types.len();
826 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
827 let is_test_crate = sess.opts.test;
828 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
838 krate = time(time_passes, "creating allocators", || {
839 allocator::expand::modify(&sess.parse_sess,
845 after_expand(&krate)?;
847 if sess.opts.debugging_opts.input_stats {
848 println!("Post-expansion node count: {}", count_nodes(&krate));
851 if sess.opts.debugging_opts.hir_stats {
852 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
855 if sess.opts.debugging_opts.ast_json {
856 println!("{}", json::as_json(&krate));
860 "checking for inline asm in case the target doesn't support it",
861 || no_asm::check_crate(sess, &krate));
865 || ast_validation::check_crate(sess, &krate));
867 time(time_passes, "name resolution", || -> CompileResult {
868 resolver.resolve_crate(&krate);
872 if resolver.found_unresolved_macro {
873 sess.parse_sess.span_diagnostic.abort_if_errors();
876 // Needs to go *after* expansion to be able to check the results of macro expansion.
877 time(time_passes, "complete gated feature checking", || {
878 sess.track_errors(|| {
879 syntax::feature_gate::check_crate(&krate,
881 &sess.features.borrow(),
883 sess.opts.unstable_features);
888 // First, we need to collect the dep_graph.
889 let dep_graph = match future_dep_graph {
890 None => DepGraph::new_disabled(),
892 let prev_graph = future
894 .expect("Could not join with background dep_graph thread")
896 DepGraph::new(prev_graph)
899 let hir_forest = time(time_passes, "lowering ast -> hir", || {
900 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
902 if sess.opts.debugging_opts.hir_stats {
903 hir_stats::print_hir_stats(&hir_crate);
906 hir_map::Forest::new(hir_crate, &dep_graph)
911 || lint::check_ast_crate(sess, &krate));
913 // Discard hygiene data, which isn't required after lowering to HIR.
914 if !keep_hygiene_data(sess) {
915 syntax::ext::hygiene::clear_markings();
919 expanded_crate: krate,
920 defs: resolver.definitions,
921 analysis: ty::CrateAnalysis {
922 access_levels: Rc::new(AccessLevels::default()),
923 name: crate_name.to_string(),
924 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
926 resolutions: Resolutions {
927 freevars: resolver.freevars,
928 export_map: resolver.export_map,
929 trait_map: resolver.trait_map,
930 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
931 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
937 pub fn default_provide(providers: &mut ty::maps::Providers) {
938 borrowck::provide(providers);
939 mir::provide(providers);
940 reachable::provide(providers);
941 resolve_lifetime::provide(providers);
942 rustc_privacy::provide(providers);
943 DefaultTransCrate::provide(providers);
944 typeck::provide(providers);
945 ty::provide(providers);
946 traits::provide(providers);
947 reachable::provide(providers);
948 rustc_const_eval::provide(providers);
949 rustc_passes::provide(providers);
950 middle::region::provide(providers);
951 cstore::provide(providers);
952 lint::provide(providers);
955 pub fn default_provide_extern(providers: &mut ty::maps::Providers) {
956 cstore::provide_extern(providers);
957 DefaultTransCrate::provide_extern(providers);
960 /// Run the resolution, typechecking, region checking and other
961 /// miscellaneous analysis passes on the crate. Return various
962 /// structures carrying the results of the analysis.
963 pub fn phase_3_run_analysis_passes<'tcx, F, R>(control: &CompileController,
965 cstore: &'tcx CrateStore,
966 hir_map: hir_map::Map<'tcx>,
967 mut analysis: ty::CrateAnalysis,
968 resolutions: Resolutions,
969 arenas: &'tcx AllArenas<'tcx>,
971 output_filenames: &OutputFilenames,
973 -> Result<R, CompileIncomplete>
974 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
976 mpsc::Receiver<Box<Any + Send>>,
979 macro_rules! try_with_f {
980 ($e: expr, ($($t:tt)*)) => {
991 let time_passes = sess.time_passes();
993 let query_result_on_disk_cache = time(time_passes,
994 "load query result cache",
995 || rustc_incremental::load_query_result_cache(sess));
998 "looking for entry point",
999 || middle::entry::find_entry_point(sess, &hir_map));
1001 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
1002 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
1004 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
1008 || loops::check_crate(sess, &hir_map));
1011 "static item recursion checking",
1012 || static_recursion::check_crate(sess, &hir_map))?;
1014 let mut local_providers = ty::maps::Providers::default();
1015 default_provide(&mut local_providers);
1016 (control.provide)(&mut local_providers);
1018 let mut extern_providers = local_providers;
1019 default_provide_extern(&mut extern_providers);
1020 (control.provide_extern)(&mut extern_providers);
1022 let (tx, rx) = mpsc::channel();
1024 TyCtxt::create_and_enter(sess,
1031 query_result_on_disk_cache,
1036 // Do some initialization of the DepGraph that can only be done with the
1038 rustc_incremental::dep_graph_tcx_init(tcx);
1041 "stability checking",
1042 || stability::check_unstable_api_usage(tcx));
1044 // passes are timed inside typeck
1045 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, rx));
1049 || consts::check_crate(tcx));
1051 analysis.access_levels =
1052 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1055 "intrinsic checking",
1056 || middle::intrinsicck::check_crate(tcx));
1060 || check_match::check_crate(tcx));
1062 // this must run before MIR dump, because
1063 // "not all control paths return a value" is reported here.
1065 // maybe move the check to a MIR pass?
1067 "liveness checking",
1068 || middle::liveness::check_crate(tcx));
1072 || borrowck::check_crate(tcx));
1075 "MIR borrow checking",
1076 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id); });
1079 "MIR effect checking",
1080 || for def_id in tcx.body_owners() {
1081 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1083 // Avoid overwhelming user with errors if type checking failed.
1084 // I'm not sure how helpful this is, to be honest, but it avoids
1086 // lot of annoying errors in the compile-fail tests (basically,
1087 // lint warnings and so on -- kindck used to do this abort, but
1088 // kindck is gone now). -nmatsakis
1089 if sess.err_count() > 0 {
1090 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1093 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1095 time(time_passes, "unused lib feature checking", || {
1096 stability::check_unused_or_stable_features(tcx)
1099 time(time_passes, "lint checking", || lint::check_crate(tcx));
1101 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1105 /// Run the translation phase to LLVM, after which the AST and analysis can
1107 pub fn phase_4_translate_to_llvm<'a, 'tcx, Trans: TransCrate>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1108 rx: mpsc::Receiver<Box<Any + Send>>)
1109 -> <Trans as TransCrate>::OngoingCrateTranslation {
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 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1128 /// as a side effect.
1129 pub fn phase_5_run_llvm_passes<Trans: TransCrate>(sess: &Session,
1130 dep_graph: &DepGraph,
1131 trans: <Trans as TransCrate>::OngoingCrateTranslation)
1132 -> (CompileResult, <Trans as TransCrate>::TranslatedCrate) {
1133 let trans = Trans::join_trans(trans, sess, dep_graph);
1135 if sess.opts.debugging_opts.incremental_info {
1136 Trans::dump_incremental_data(&trans);
1139 time(sess.time_passes(),
1140 "serialize work products",
1141 move || rustc_incremental::save_work_products(sess, dep_graph));
1143 (sess.compile_status(), trans)
1146 fn escape_dep_filename(filename: &FileName) -> String {
1147 // Apparently clang and gcc *only* escape spaces:
1148 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1149 filename.to_string().replace(" ", "\\ ")
1152 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1153 let mut out_filenames = Vec::new();
1154 for output_type in sess.opts.output_types.keys() {
1155 let file = outputs.path(*output_type);
1156 match *output_type {
1157 OutputType::Exe => {
1158 for output in sess.crate_types.borrow().iter() {
1159 let p = ::rustc_trans_utils::link::filename_for_input(
1165 out_filenames.push(p);
1169 out_filenames.push(file);
1174 // Write out dependency rules to the dep-info file if requested
1175 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1178 let deps_filename = outputs.path(OutputType::DepInfo);
1181 (|| -> io::Result<()> {
1182 // Build a list of files used to compile the output and
1183 // write Makefile-compatible dependency rules
1184 let files: Vec<String> = sess.codemap()
1187 .filter(|fmap| fmap.is_real_file())
1188 .filter(|fmap| !fmap.is_imported())
1189 .map(|fmap| escape_dep_filename(&fmap.name))
1191 let mut file = fs::File::create(&deps_filename)?;
1192 for path in &out_filenames {
1193 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1196 // Emit a fake target for each input file to the compilation. This
1197 // prevents `make` from spitting out an error if a file is later
1198 // deleted. For more info see #28735
1200 writeln!(file, "{}:", path)?;
1208 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1209 deps_filename.display(),
1215 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1216 // Unconditionally collect crate types from attributes to make them used
1217 let attr_types: Vec<config::CrateType> =
1220 if a.check_name("crate_type") {
1221 match a.value_str() {
1222 Some(ref n) if *n == "rlib" => {
1223 Some(config::CrateTypeRlib)
1225 Some(ref n) if *n == "dylib" => {
1226 Some(config::CrateTypeDylib)
1228 Some(ref n) if *n == "cdylib" => {
1229 Some(config::CrateTypeCdylib)
1231 Some(ref n) if *n == "lib" => {
1232 Some(config::default_lib_output())
1234 Some(ref n) if *n == "staticlib" => {
1235 Some(config::CrateTypeStaticlib)
1237 Some(ref n) if *n == "proc-macro" => {
1238 Some(config::CrateTypeProcMacro)
1240 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1242 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1245 "invalid `crate_type` value");
1249 session.struct_span_err(a.span, "`crate_type` requires a value")
1250 .note("for example: `#![crate_type=\"lib\"]`")
1261 // If we're generating a test executable, then ignore all other output
1262 // styles at all other locations
1263 if session.opts.test {
1264 return vec![config::CrateTypeExecutable];
1267 // Only check command line flags if present. If no types are specified by
1268 // command line, then reuse the empty `base` Vec to hold the types that
1269 // will be found in crate attributes.
1270 let mut base = session.opts.crate_types.clone();
1271 if base.is_empty() {
1272 base.extend(attr_types);
1273 if base.is_empty() {
1274 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1281 .filter(|crate_type| {
1282 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1285 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1287 session.opts.target_triple));
1295 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1296 use std::hash::Hasher;
1298 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1299 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1300 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1301 // should still be safe enough to avoid collisions in practice.
1302 let mut hasher = StableHasher::<Fingerprint>::new();
1304 let mut metadata = session.opts.cg.metadata.clone();
1305 // We don't want the crate_disambiguator to dependent on the order
1306 // -C metadata arguments, so sort them:
1308 // Every distinct -C metadata value is only incorporated once:
1311 hasher.write(b"metadata");
1312 for s in &metadata {
1313 // Also incorporate the length of a metadata string, so that we generate
1314 // different values for `-Cmetadata=ab -Cmetadata=c` and
1315 // `-Cmetadata=a -Cmetadata=bc`
1316 hasher.write_usize(s.len());
1317 hasher.write(s.as_bytes());
1320 // Also incorporate crate type, so that we don't get symbol conflicts when
1321 // linking against a library of the same name, if this is an executable.
1322 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1323 hasher.write(if is_exe { b"exe" } else { b"lib" });
1325 CrateDisambiguator::from(hasher.finish())
1329 pub fn build_output_filenames(input: &Input,
1330 odir: &Option<PathBuf>,
1331 ofile: &Option<PathBuf>,
1332 attrs: &[ast::Attribute],
1334 -> OutputFilenames {
1337 // "-" as input file will cause the parser to read from stdin so we
1338 // have to make up a name
1339 // We want to toss everything after the final '.'
1340 let dirpath = match *odir {
1341 Some(ref d) => d.clone(),
1342 None => PathBuf::new(),
1345 // If a crate name is present, we use it as the link name
1346 let stem = sess.opts
1349 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1350 .unwrap_or(input.filestem());
1353 out_directory: dirpath,
1355 single_output_file: None,
1356 extra: sess.opts.cg.extra_filename.clone(),
1357 outputs: sess.opts.output_types.clone(),
1361 Some(ref out_file) => {
1362 let unnamed_output_types = sess.opts
1365 .filter(|a| a.is_none())
1367 let ofile = if unnamed_output_types > 1 {
1368 sess.warn("due to multiple output types requested, the explicitly specified \
1369 output file name will be adapted for each output type");
1372 Some(out_file.clone())
1375 sess.warn("ignoring --out-dir flag due to -o flag.");
1378 let cur_dir = Path::new("");
1381 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1382 out_filestem: out_file.file_stem()
1383 .unwrap_or(OsStr::new(""))
1387 single_output_file: ofile,
1388 extra: sess.opts.cg.extra_filename.clone(),
1389 outputs: sess.opts.output_types.clone(),