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, 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, static_recursion, hir_stats};
40 use rustc_const_eval::{self, check_match};
41 use super::Compilation;
47 use std::ffi::{OsString, OsStr};
49 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
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 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
127 phase_2_configure_and_expand(
134 control.make_glob_map,
136 let mut state = CompileState::state_after_expand(
137 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
139 controller_entry_point!(after_expand, sess, state, Ok(()));
145 let output_paths = generated_output_paths(sess, &outputs, &crate_name);
147 // Ensure the source file isn't accidentally overwritten during compilation.
148 if let Some(ref input_path) = *input_path {
149 if sess.opts.will_create_output_file() {
150 if output_contains_path(&output_paths, input_path) {
152 "the input file \"{}\" would be overwritten by the generated \
154 input_path.display()));
155 return Err(CompileIncomplete::Stopped);
157 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
159 "the generated executable for the input file \"{}\" conflicts with the \
160 existing directory \"{}\"",
161 input_path.display(), dir_path.display()));
162 return Err(CompileIncomplete::Stopped);
167 write_out_deps(sess, &outputs, &output_paths);
168 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
169 sess.opts.output_types.keys().count() == 1 {
173 let arenas = AllArenas::new();
175 // Construct the HIR map
176 let hir_map = time(sess.time_passes(),
178 || hir_map::map_crate(sess, cstore, &mut hir_forest, &defs));
181 hir_map.dep_graph.assert_ignored();
182 controller_entry_point!(after_hir_lowering,
184 CompileState::state_after_hir_lowering(input,
200 let opt_crate = if control.keep_ast {
201 Some(&expanded_crate)
203 drop(expanded_crate);
207 phase_3_run_analysis_passes(&*trans,
217 |tcx, analysis, rx, result| {
219 // Eventually, we will want to track plugins.
220 tcx.dep_graph.with_ignore(|| {
221 let mut state = CompileState::state_after_analysis(input,
230 (control.after_analysis.callback)(&mut state);
233 if control.after_analysis.stop == Compilation::Stop {
234 return result.and_then(|_| Err(CompileIncomplete::Stopped));
240 if log_enabled!(::log::Level::Info) {
241 println!("Pre-trans");
242 tcx.print_debug_stats();
245 let ongoing_trans = phase_4_translate_to_llvm(&*trans, tcx, rx);
247 if log_enabled!(::log::Level::Info) {
248 println!("Post-trans");
249 tcx.print_debug_stats();
252 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
253 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
254 sess.err(&format!("could not emit MIR: {}", e));
255 sess.abort_if_errors();
259 Ok((outputs.clone(), ongoing_trans, tcx.dep_graph.clone()))
263 if sess.opts.debugging_opts.print_type_sizes {
264 sess.code_stats.borrow().print_type_sizes();
267 trans.join_trans_and_link(ongoing_trans, sess, &dep_graph, &outputs)?;
269 if sess.opts.debugging_opts.perf_stats {
270 sess.print_perf_stats();
273 controller_entry_point!(
276 CompileState::state_when_compilation_done(input, sess, outdir, output),
283 pub fn source_name(input: &Input) -> FileName {
285 Input::File(ref ifile) => ifile.clone().into(),
286 Input::Str { ref name, .. } => name.clone(),
290 /// CompileController is used to customize compilation, it allows compilation to
291 /// be stopped and/or to call arbitrary code at various points in compilation.
292 /// It also allows for various flags to be set to influence what information gets
293 /// collected during compilation.
295 /// This is a somewhat higher level controller than a Session - the Session
296 /// controls what happens in each phase, whereas the CompileController controls
297 /// whether a phase is run at all and whether other code (from outside the
298 /// compiler) is run between phases.
300 /// Note that if compilation is set to stop and a callback is provided for a
301 /// given entry point, the callback is called before compilation is stopped.
303 /// Expect more entry points to be added in the future.
304 pub struct CompileController<'a> {
305 pub after_parse: PhaseController<'a>,
306 pub after_expand: PhaseController<'a>,
307 pub after_hir_lowering: PhaseController<'a>,
308 pub after_analysis: PhaseController<'a>,
309 pub compilation_done: PhaseController<'a>,
311 // FIXME we probably want to group the below options together and offer a
312 // better API, rather than this ad-hoc approach.
313 pub make_glob_map: MakeGlobMap,
314 // Whether the compiler should keep the ast beyond parsing.
316 // -Zcontinue-parse-after-error
317 pub continue_parse_after_error: bool,
319 /// Allows overriding default rustc query providers,
320 /// after `default_provide` has installed them.
321 pub provide: Box<Fn(&mut ty::maps::Providers) + 'a>,
322 /// Same as `provide`, but only for non-local crates,
323 /// applied after `default_provide_extern`.
324 pub provide_extern: Box<Fn(&mut ty::maps::Providers) + 'a>,
327 impl<'a> CompileController<'a> {
328 pub fn basic() -> CompileController<'a> {
330 after_parse: PhaseController::basic(),
331 after_expand: PhaseController::basic(),
332 after_hir_lowering: PhaseController::basic(),
333 after_analysis: PhaseController::basic(),
334 compilation_done: PhaseController::basic(),
335 make_glob_map: MakeGlobMap::No,
337 continue_parse_after_error: false,
339 provide_extern: box |_| {},
344 pub struct PhaseController<'a> {
345 pub stop: Compilation,
346 // If true then the compiler will try to run the callback even if the phase
347 // ends with an error. Note that this is not always possible.
348 pub run_callback_on_error: bool,
349 pub callback: Box<Fn(&mut CompileState) + 'a>,
352 impl<'a> PhaseController<'a> {
353 pub fn basic() -> PhaseController<'a> {
355 stop: Compilation::Continue,
356 run_callback_on_error: false,
357 callback: box |_| {},
362 /// State that is passed to a callback. What state is available depends on when
363 /// during compilation the callback is made. See the various constructor methods
364 /// (`state_*`) in the impl to see which data is provided for any given entry point.
365 pub struct CompileState<'a, 'tcx: 'a> {
366 pub input: &'a Input,
367 pub session: &'tcx Session,
368 pub krate: Option<ast::Crate>,
369 pub registry: Option<Registry<'a>>,
370 pub cstore: Option<&'tcx CStore>,
371 pub crate_name: Option<&'a str>,
372 pub output_filenames: Option<&'a OutputFilenames>,
373 pub out_dir: Option<&'a Path>,
374 pub out_file: Option<&'a Path>,
375 pub arenas: Option<&'tcx AllArenas<'tcx>>,
376 pub expanded_crate: Option<&'a ast::Crate>,
377 pub hir_crate: Option<&'a hir::Crate>,
378 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
379 pub resolutions: Option<&'a Resolutions>,
380 pub analysis: Option<&'a ty::CrateAnalysis>,
381 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
384 impl<'a, 'tcx> CompileState<'a, 'tcx> {
385 fn empty(input: &'a Input,
386 session: &'tcx Session,
387 out_dir: &'a Option<PathBuf>)
392 out_dir: out_dir.as_ref().map(|s| &**s),
399 output_filenames: None,
400 expanded_crate: None,
409 fn state_after_parse(input: &'a Input,
410 session: &'tcx Session,
411 out_dir: &'a Option<PathBuf>,
412 out_file: &'a Option<PathBuf>,
414 cstore: &'tcx CStore)
417 // Initialize the registry before moving `krate`
418 registry: Some(Registry::new(&session, krate.span)),
420 cstore: Some(cstore),
421 out_file: out_file.as_ref().map(|s| &**s),
422 ..CompileState::empty(input, session, out_dir)
426 fn state_after_expand(input: &'a Input,
427 session: &'tcx Session,
428 out_dir: &'a Option<PathBuf>,
429 out_file: &'a Option<PathBuf>,
430 cstore: &'tcx CStore,
431 expanded_crate: &'a ast::Crate,
435 crate_name: Some(crate_name),
436 cstore: Some(cstore),
437 expanded_crate: Some(expanded_crate),
438 out_file: out_file.as_ref().map(|s| &**s),
439 ..CompileState::empty(input, session, out_dir)
443 fn state_after_hir_lowering(input: &'a Input,
444 session: &'tcx Session,
445 out_dir: &'a Option<PathBuf>,
446 out_file: &'a Option<PathBuf>,
447 arenas: &'tcx AllArenas<'tcx>,
448 cstore: &'tcx CStore,
449 hir_map: &'a hir_map::Map<'tcx>,
450 analysis: &'a ty::CrateAnalysis,
451 resolutions: &'a Resolutions,
452 krate: &'a ast::Crate,
453 hir_crate: &'a hir::Crate,
454 output_filenames: &'a OutputFilenames,
458 crate_name: Some(crate_name),
459 arenas: Some(arenas),
460 cstore: Some(cstore),
461 hir_map: Some(hir_map),
462 analysis: Some(analysis),
463 resolutions: Some(resolutions),
464 expanded_crate: Some(krate),
465 hir_crate: Some(hir_crate),
466 output_filenames: Some(output_filenames),
467 out_file: out_file.as_ref().map(|s| &**s),
468 ..CompileState::empty(input, session, out_dir)
472 fn state_after_analysis(input: &'a Input,
473 session: &'tcx Session,
474 out_dir: &'a Option<PathBuf>,
475 out_file: &'a Option<PathBuf>,
476 krate: Option<&'a ast::Crate>,
477 hir_crate: &'a hir::Crate,
478 analysis: &'a ty::CrateAnalysis,
479 tcx: TyCtxt<'a, 'tcx, 'tcx>,
483 analysis: Some(analysis),
485 expanded_crate: krate,
486 hir_crate: Some(hir_crate),
487 crate_name: Some(crate_name),
488 out_file: out_file.as_ref().map(|s| &**s),
489 ..CompileState::empty(input, session, out_dir)
493 fn state_when_compilation_done(input: &'a Input,
494 session: &'tcx Session,
495 out_dir: &'a Option<PathBuf>,
496 out_file: &'a Option<PathBuf>)
499 out_file: out_file.as_ref().map(|s| &**s),
500 ..CompileState::empty(input, session, out_dir)
505 pub fn phase_1_parse_input<'a>(control: &CompileController,
508 -> PResult<'a, ast::Crate> {
509 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
511 if sess.profile_queries() {
515 let krate = time(sess.time_passes(), "parsing", || {
517 Input::File(ref file) => {
518 parse::parse_crate_from_file(file, &sess.parse_sess)
520 Input::Str { ref input, ref name } => {
521 parse::parse_crate_from_source_str(name.clone(),
528 sess.diagnostic().set_continue_after_error(true);
530 if sess.opts.debugging_opts.ast_json_noexpand {
531 println!("{}", json::as_json(&krate));
534 if sess.opts.debugging_opts.input_stats {
535 println!("Lines of code: {}", sess.codemap().count_lines());
536 println!("Pre-expansion node count: {}", count_nodes(&krate));
539 if let Some(ref s) = sess.opts.debugging_opts.show_span {
540 syntax::show_span::run(sess.diagnostic(), s, &krate);
543 if sess.opts.debugging_opts.hir_stats {
544 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
550 fn count_nodes(krate: &ast::Crate) -> usize {
551 let mut counter = NodeCounter::new();
552 visit::walk_crate(&mut counter, krate);
556 // For continuing compilation after a parsed crate has been
559 pub struct ExpansionResult {
560 pub expanded_crate: ast::Crate,
561 pub defs: hir_map::Definitions,
562 pub analysis: ty::CrateAnalysis,
563 pub resolutions: Resolutions,
564 pub hir_forest: hir_map::Forest,
567 pub struct InnerExpansionResult<'a> {
568 pub expanded_crate: ast::Crate,
569 pub resolver: Resolver<'a>,
570 pub hir_forest: hir_map::Forest,
573 /// Run the "early phases" of the compiler: initial `cfg` processing,
574 /// loading compiler plugins (including those from `addl_plugins`),
575 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
576 /// harness if one is to be provided, injection of a dependency on the
577 /// standard library and prelude, and name resolution.
579 /// Returns `None` if we're aborting after handling -W help.
580 pub fn phase_2_configure_and_expand<F>(sess: &Session,
583 registry: Option<Registry>,
585 addl_plugins: Option<Vec<String>>,
586 make_glob_map: MakeGlobMap,
588 -> Result<ExpansionResult, CompileIncomplete>
589 where F: FnOnce(&ast::Crate) -> CompileResult {
590 // Currently, we ignore the name resolution data structures for the purposes of dependency
591 // tracking. Instead we will run name resolution and include its output in the hash of each
592 // item, much like we do for macro expansion. In other words, the hash reflects not just
593 // its contents but the results of name resolution on those contents. Hopefully we'll push
594 // this back at some point.
595 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
596 let resolver_arenas = Resolver::arenas();
597 let result = phase_2_configure_and_expand_inner(sess, cstore, krate, registry, crate_name,
598 addl_plugins, make_glob_map, &resolver_arenas,
599 &mut crate_loader, after_expand);
601 Ok(InnerExpansionResult {expanded_crate, resolver, hir_forest}) => {
604 defs: resolver.definitions,
606 resolutions: Resolutions {
607 freevars: resolver.freevars,
608 export_map: resolver.export_map,
609 trait_map: resolver.trait_map,
610 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
611 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
614 analysis: ty::CrateAnalysis {
615 access_levels: Rc::new(AccessLevels::default()),
616 name: crate_name.to_string(),
617 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
625 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
627 pub fn phase_2_configure_and_expand_inner<'a, F>(sess: &'a Session,
630 registry: Option<Registry>,
632 addl_plugins: Option<Vec<String>>,
633 make_glob_map: MakeGlobMap,
634 resolver_arenas: &'a ResolverArenas<'a>,
635 crate_loader: &'a mut CrateLoader,
637 -> Result<InnerExpansionResult<'a>, 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 let mut resolver = Resolver::new(sess,
733 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
734 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
736 krate = time(time_passes, "expansion", || {
737 // Windows dlls do not have rpaths, so they don't know how to find their
738 // dependencies. It's up to us to tell the system where to find all the
739 // dependent dlls. Note that this uses cfg!(windows) as opposed to
740 // targ_cfg because syntax extensions are always loaded for the host
741 // compiler, not for the target.
743 // This is somewhat of an inherently racy operation, however, as
744 // multiple threads calling this function could possibly continue
745 // extending PATH far beyond what it should. To solve this for now we
746 // just don't add any new elements to PATH which are already there
747 // within PATH. This is basically a targeted fix at #17360 for rustdoc
748 // which runs rustc in parallel but has been seen (#33844) to cause
749 // problems with PATH becoming too long.
750 let mut old_path = OsString::new();
752 old_path = env::var_os("PATH").unwrap_or(old_path);
753 let mut new_path = sess.host_filesearch(PathKind::All)
754 .get_dylib_search_paths();
755 for path in env::split_paths(&old_path) {
756 if !new_path.contains(&path) {
761 &env::join_paths(new_path.iter()
762 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
765 let features = sess.features.borrow();
766 let cfg = syntax::ext::expand::ExpansionConfig {
767 features: Some(&features),
768 recursion_limit: sess.recursion_limit.get(),
769 trace_mac: sess.opts.debugging_opts.trace_macros,
770 should_test: sess.opts.test,
771 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
774 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
775 let err_count = ecx.parse_sess.span_diagnostic.err_count();
777 let krate = ecx.monotonic_expander().expand_crate(krate);
779 ecx.check_unused_macros();
781 let mut missing_fragment_specifiers: Vec<_> =
782 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
783 missing_fragment_specifiers.sort();
784 for span in missing_fragment_specifiers {
785 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
786 let msg = "missing fragment specifier";
787 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
789 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
790 ecx.parse_sess.span_diagnostic.abort_if_errors();
793 env::set_var("PATH", &old_path);
798 krate = time(time_passes, "maybe building test harness", || {
799 syntax::test::modify_for_testing(&sess.parse_sess,
806 // If we're actually rustdoc then there's no need to actually compile
807 // anything, so switch everything to just looping
808 if sess.opts.actually_rustdoc {
809 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
812 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
813 // bunch of checks in the `modify` function below. For now just skip this
814 // step entirely if we're rustdoc as it's not too useful anyway.
815 if !sess.opts.actually_rustdoc {
816 krate = time(time_passes, "maybe creating a macro crate", || {
817 let crate_types = sess.crate_types.borrow();
818 let num_crate_types = crate_types.len();
819 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
820 let is_test_crate = sess.opts.test;
821 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
831 krate = time(time_passes, "creating allocators", || {
832 allocator::expand::modify(&sess.parse_sess,
838 after_expand(&krate)?;
840 if sess.opts.debugging_opts.input_stats {
841 println!("Post-expansion node count: {}", count_nodes(&krate));
844 if sess.opts.debugging_opts.hir_stats {
845 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
848 if sess.opts.debugging_opts.ast_json {
849 println!("{}", json::as_json(&krate));
854 || ast_validation::check_crate(sess, &krate));
856 time(time_passes, "name resolution", || -> CompileResult {
857 resolver.resolve_crate(&krate);
861 if resolver.found_unresolved_macro {
862 sess.parse_sess.span_diagnostic.abort_if_errors();
865 // Needs to go *after* expansion to be able to check the results of macro expansion.
866 time(time_passes, "complete gated feature checking", || {
867 sess.track_errors(|| {
868 syntax::feature_gate::check_crate(&krate,
870 &sess.features.borrow(),
872 sess.opts.unstable_features);
877 // First, we need to collect the dep_graph.
878 let dep_graph = match future_dep_graph {
879 None => DepGraph::new_disabled(),
881 let prev_graph = time(time_passes, "blocked while dep-graph loading finishes", || {
883 .expect("Could not join with background dep_graph thread")
886 DepGraph::new(prev_graph)
889 let hir_forest = time(time_passes, "lowering ast -> hir", || {
890 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
892 if sess.opts.debugging_opts.hir_stats {
893 hir_stats::print_hir_stats(&hir_crate);
896 hir_map::Forest::new(hir_crate, &dep_graph)
901 || lint::check_ast_crate(sess, &krate));
903 // Discard hygiene data, which isn't required after lowering to HIR.
904 if !sess.opts.debugging_opts.keep_hygiene_data {
905 syntax::ext::hygiene::clear_markings();
908 Ok(InnerExpansionResult {
909 expanded_crate: krate,
915 pub fn default_provide(providers: &mut ty::maps::Providers) {
916 borrowck::provide(providers);
917 mir::provide(providers);
918 reachable::provide(providers);
919 resolve_lifetime::provide(providers);
920 rustc_privacy::provide(providers);
921 typeck::provide(providers);
922 ty::provide(providers);
923 traits::provide(providers);
924 reachable::provide(providers);
925 rustc_const_eval::provide(providers);
926 rustc_passes::provide(providers);
927 middle::region::provide(providers);
928 cstore::provide(providers);
929 lint::provide(providers);
932 pub fn default_provide_extern(providers: &mut ty::maps::Providers) {
933 cstore::provide_extern(providers);
936 /// Run the resolution, typechecking, region checking and other
937 /// miscellaneous analysis passes on the crate. Return various
938 /// structures carrying the results of the analysis.
939 pub fn phase_3_run_analysis_passes<'tcx, F, R>(trans: &TransCrate,
940 control: &CompileController,
942 cstore: &'tcx CrateStore,
943 hir_map: hir_map::Map<'tcx>,
944 mut analysis: ty::CrateAnalysis,
945 resolutions: Resolutions,
946 arenas: &'tcx AllArenas<'tcx>,
948 output_filenames: &OutputFilenames,
950 -> Result<R, CompileIncomplete>
951 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
953 mpsc::Receiver<Box<Any + Send>>,
956 let time_passes = sess.time_passes();
958 let query_result_on_disk_cache = time(time_passes,
959 "load query result cache",
960 || rustc_incremental::load_query_result_cache(sess));
963 "looking for entry point",
964 || middle::entry::find_entry_point(sess, &hir_map));
966 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
967 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
969 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
973 || loops::check_crate(sess, &hir_map));
976 "static item recursion checking",
977 || static_recursion::check_crate(sess, &hir_map))?;
979 let mut local_providers = ty::maps::Providers::default();
980 default_provide(&mut local_providers);
981 trans.provide(&mut local_providers);
982 (control.provide)(&mut local_providers);
984 let mut extern_providers = local_providers;
985 default_provide_extern(&mut extern_providers);
986 trans.provide_extern(&mut extern_providers);
987 (control.provide_extern)(&mut extern_providers);
989 let (tx, rx) = mpsc::channel();
991 TyCtxt::create_and_enter(sess,
998 query_result_on_disk_cache,
1003 // Do some initialization of the DepGraph that can only be done with the
1005 rustc_incremental::dep_graph_tcx_init(tcx);
1007 time(sess.time_passes(), "attribute checking", || {
1008 hir::check_attr::check_crate(tcx)
1012 "stability checking",
1013 || stability::check_unstable_api_usage(tcx));
1015 // passes are timed inside typeck
1016 match typeck::check_crate(tcx) {
1019 f(tcx, analysis, rx, Err(x));
1026 || consts::check_crate(tcx));
1028 analysis.access_levels =
1029 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1032 "intrinsic checking",
1033 || middle::intrinsicck::check_crate(tcx));
1037 || check_match::check_crate(tcx));
1039 // this must run before MIR dump, because
1040 // "not all control paths return a value" is reported here.
1042 // maybe move the check to a MIR pass?
1044 "liveness checking",
1045 || middle::liveness::check_crate(tcx));
1049 || borrowck::check_crate(tcx));
1052 "MIR borrow checking",
1053 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id); });
1056 "MIR effect checking",
1057 || for def_id in tcx.body_owners() {
1058 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1060 // Avoid overwhelming user with errors if type checking failed.
1061 // I'm not sure how helpful this is, to be honest, but it avoids
1063 // lot of annoying errors in the compile-fail tests (basically,
1064 // lint warnings and so on -- kindck used to do this abort, but
1065 // kindck is gone now). -nmatsakis
1066 if sess.err_count() > 0 {
1067 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1070 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1072 time(time_passes, "unused lib feature checking", || {
1073 stability::check_unused_or_stable_features(tcx)
1076 time(time_passes, "lint checking", || lint::check_crate(tcx));
1078 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1082 /// Run the translation phase to LLVM, after which the AST and analysis can
1084 pub fn phase_4_translate_to_llvm<'a, 'tcx>(trans: &TransCrate,
1085 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1086 rx: mpsc::Receiver<Box<Any + Send>>)
1088 let time_passes = tcx.sess.time_passes();
1091 "resolving dependency formats",
1092 || ::rustc::middle::dependency_format::calculate(tcx));
1095 time(time_passes, "translation", move || {
1096 trans.trans_crate(tcx, rx)
1098 if tcx.sess.profile_queries() {
1099 profile::dump("profile_queries".to_string())
1105 fn escape_dep_filename(filename: &FileName) -> String {
1106 // Apparently clang and gcc *only* escape spaces:
1107 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1108 filename.to_string().replace(" ", "\\ ")
1111 // Returns all the paths that correspond to generated files.
1112 fn generated_output_paths(sess: &Session,
1113 outputs: &OutputFilenames,
1114 crate_name: &str) -> Vec<PathBuf> {
1115 let mut out_filenames = Vec::new();
1116 for output_type in sess.opts.output_types.keys() {
1117 let file = outputs.path(*output_type);
1118 match *output_type {
1119 OutputType::Exe => {
1120 for output in sess.crate_types.borrow().iter() {
1121 let p = ::rustc_trans_utils::link::filename_for_input(
1127 out_filenames.push(p);
1130 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1131 // Don't add the dep-info output when omitting it from dep-info targets
1134 out_filenames.push(file);
1141 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1142 // returns None for every file path.
1143 fn check_output<F, T>(output_paths: &Vec<PathBuf>, f: F) -> Option<T>
1144 where F: Fn(&PathBuf) -> Option<T> {
1145 for output_path in output_paths {
1146 if let Some(result) = f(output_path) {
1147 return Some(result);
1153 pub fn output_contains_path(output_paths: &Vec<PathBuf>, input_path: &PathBuf) -> bool {
1154 let input_path = input_path.canonicalize().ok();
1155 if input_path.is_none() {
1158 let check = |output_path: &PathBuf| {
1159 if output_path.canonicalize().ok() == input_path {
1163 check_output(output_paths, check).is_some()
1166 pub fn output_conflicts_with_dir(output_paths: &Vec<PathBuf>) -> Option<PathBuf> {
1167 let check = |output_path: &PathBuf| {
1168 if output_path.is_dir() {
1169 Some(output_path.clone())
1172 check_output(output_paths, check)
1175 fn write_out_deps(sess: &Session,
1176 outputs: &OutputFilenames,
1177 out_filenames: &Vec<PathBuf>) {
1178 // Write out dependency rules to the dep-info file if requested
1179 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1182 let deps_filename = outputs.path(OutputType::DepInfo);
1185 (|| -> io::Result<()> {
1186 // Build a list of files used to compile the output and
1187 // write Makefile-compatible dependency rules
1188 let files: Vec<String> = sess.codemap()
1191 .filter(|fmap| fmap.is_real_file())
1192 .filter(|fmap| !fmap.is_imported())
1193 .map(|fmap| escape_dep_filename(&fmap.name))
1195 let mut file = fs::File::create(&deps_filename)?;
1196 for path in out_filenames {
1197 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1200 // Emit a fake target for each input file to the compilation. This
1201 // prevents `make` from spitting out an error if a file is later
1202 // deleted. For more info see #28735
1204 writeln!(file, "{}:", path)?;
1212 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1213 deps_filename.display(),
1219 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1220 // Unconditionally collect crate types from attributes to make them used
1221 let attr_types: Vec<config::CrateType> =
1224 if a.check_name("crate_type") {
1225 match a.value_str() {
1226 Some(ref n) if *n == "rlib" => {
1227 Some(config::CrateTypeRlib)
1229 Some(ref n) if *n == "dylib" => {
1230 Some(config::CrateTypeDylib)
1232 Some(ref n) if *n == "cdylib" => {
1233 Some(config::CrateTypeCdylib)
1235 Some(ref n) if *n == "lib" => {
1236 Some(config::default_lib_output())
1238 Some(ref n) if *n == "staticlib" => {
1239 Some(config::CrateTypeStaticlib)
1241 Some(ref n) if *n == "proc-macro" => {
1242 Some(config::CrateTypeProcMacro)
1244 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1246 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1249 "invalid `crate_type` value");
1253 session.struct_span_err(a.span, "`crate_type` requires a value")
1254 .note("for example: `#![crate_type=\"lib\"]`")
1265 // If we're generating a test executable, then ignore all other output
1266 // styles at all other locations
1267 if session.opts.test {
1268 return vec![config::CrateTypeExecutable];
1271 // Only check command line flags if present. If no types are specified by
1272 // command line, then reuse the empty `base` Vec to hold the types that
1273 // will be found in crate attributes.
1274 let mut base = session.opts.crate_types.clone();
1275 if base.is_empty() {
1276 base.extend(attr_types);
1277 if base.is_empty() {
1278 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1285 .filter(|crate_type| {
1286 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1289 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1291 session.opts.target_triple));
1299 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1300 use std::hash::Hasher;
1302 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1303 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1304 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1305 // should still be safe enough to avoid collisions in practice.
1306 let mut hasher = StableHasher::<Fingerprint>::new();
1308 let mut metadata = session.opts.cg.metadata.clone();
1309 // We don't want the crate_disambiguator to dependent on the order
1310 // -C metadata arguments, so sort them:
1312 // Every distinct -C metadata value is only incorporated once:
1315 hasher.write(b"metadata");
1316 for s in &metadata {
1317 // Also incorporate the length of a metadata string, so that we generate
1318 // different values for `-Cmetadata=ab -Cmetadata=c` and
1319 // `-Cmetadata=a -Cmetadata=bc`
1320 hasher.write_usize(s.len());
1321 hasher.write(s.as_bytes());
1324 // Also incorporate crate type, so that we don't get symbol conflicts when
1325 // linking against a library of the same name, if this is an executable.
1326 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1327 hasher.write(if is_exe { b"exe" } else { b"lib" });
1329 CrateDisambiguator::from(hasher.finish())
1333 pub fn build_output_filenames(input: &Input,
1334 odir: &Option<PathBuf>,
1335 ofile: &Option<PathBuf>,
1336 attrs: &[ast::Attribute],
1338 -> OutputFilenames {
1341 // "-" as input file will cause the parser to read from stdin so we
1342 // have to make up a name
1343 // We want to toss everything after the final '.'
1344 let dirpath = match *odir {
1345 Some(ref d) => d.clone(),
1346 None => PathBuf::new(),
1349 // If a crate name is present, we use it as the link name
1350 let stem = sess.opts
1353 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1354 .unwrap_or(input.filestem());
1357 out_directory: dirpath,
1359 single_output_file: None,
1360 extra: sess.opts.cg.extra_filename.clone(),
1361 outputs: sess.opts.output_types.clone(),
1365 Some(ref out_file) => {
1366 let unnamed_output_types = sess.opts
1369 .filter(|a| a.is_none())
1371 let ofile = if unnamed_output_types > 1 {
1372 sess.warn("due to multiple output types requested, the explicitly specified \
1373 output file name will be adapted for each output type");
1376 Some(out_file.clone())
1379 sess.warn("ignoring --out-dir flag due to -o flag.");
1381 if !sess.opts.cg.extra_filename.is_empty() {
1382 sess.warn("ignoring -C extra-filename flag due to -o flag.");
1385 let cur_dir = Path::new("");
1388 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1389 out_filestem: out_file.file_stem()
1390 .unwrap_or(OsStr::new(""))
1394 single_output_file: ofile,
1395 extra: sess.opts.cg.extra_filename.clone(),
1396 outputs: sess.opts.output_types.clone(),