]> git.proxmox.com Git - rustc.git/blob - src/librustc_driver/driver.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / librustc_driver / driver.rs
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.
4 //
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.
10
11 use rustc::front;
12 use rustc::front::map as hir_map;
13 use rustc_mir as mir;
14 use rustc_mir::mir_map::MirMap;
15 use rustc::session::Session;
16 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
17 use rustc::session::search_paths::PathKind;
18 use rustc::lint;
19 use rustc::middle::{stability, ty, reachable};
20 use rustc::middle::dependency_format;
21 use rustc::middle;
22 use rustc::util::common::time;
23 use rustc_borrowck as borrowck;
24 use rustc_resolve as resolve;
25 use rustc_metadata::macro_import;
26 use rustc_metadata::creader::LocalCrateReader;
27 use rustc_metadata::cstore::CStore;
28 use rustc_trans::back::link;
29 use rustc_trans::back::write;
30 use rustc_trans::trans;
31 use rustc_typeck as typeck;
32 use rustc_privacy;
33 use rustc_plugin::registry::Registry;
34 use rustc_plugin as plugin;
35 use rustc_front::hir;
36 use rustc_front::lowering::{lower_crate, LoweringContext};
37 use super::Compilation;
38
39 use serialize::json;
40
41 use std::collections::HashMap;
42 use std::env;
43 use std::ffi::{OsString, OsStr};
44 use std::fs;
45 use std::io::{self, Write};
46 use std::path::{Path, PathBuf};
47 use syntax::ast::{self, NodeIdAssigner};
48 use syntax::attr;
49 use syntax::attr::AttrMetaMethods;
50 use syntax::diagnostics;
51 use syntax::fold::Folder;
52 use syntax::parse;
53 use syntax::parse::token;
54 use syntax::util::node_count::NodeCounter;
55 use syntax::visit;
56 use syntax;
57
58 pub fn compile_input(sess: Session,
59 cstore: &CStore,
60 cfg: ast::CrateConfig,
61 input: &Input,
62 outdir: &Option<PathBuf>,
63 output: &Option<PathBuf>,
64 addl_plugins: Option<Vec<String>>,
65 control: CompileController) {
66 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
67 let state = $make_state;
68 (control.$point.callback)(state);
69
70 $tsess.abort_if_errors();
71 if control.$point.stop == Compilation::Stop {
72 return;
73 }
74 })}
75
76 // We need nested scopes here, because the intermediate results can keep
77 // large chunks of memory alive and we want to free them as soon as
78 // possible to keep the peak memory usage low
79 let result = {
80 let (outputs, expanded_crate, id) = {
81 let krate = phase_1_parse_input(&sess, cfg, input);
82
83 controller_entry_point!(after_parse,
84 sess,
85 CompileState::state_after_parse(input, &sess, outdir, &krate));
86
87 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, &sess);
88 let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
89 let expanded_crate = match phase_2_configure_and_expand(&sess,
90 &cstore,
91 krate,
92 &id[..],
93 addl_plugins) {
94 None => return,
95 Some(k) => k,
96 };
97
98 (outputs, expanded_crate, id)
99 };
100
101 controller_entry_point!(after_expand,
102 sess,
103 CompileState::state_after_expand(input,
104 &sess,
105 outdir,
106 &expanded_crate,
107 &id[..]));
108
109 let expanded_crate = assign_node_ids(&sess, expanded_crate);
110 // Lower ast -> hir.
111 let lcx = LoweringContext::new(&sess, Some(&expanded_crate));
112 let mut hir_forest = time(sess.time_passes(),
113 "lowering ast -> hir",
114 || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate)));
115
116 // Discard MTWT tables that aren't required past lowering to HIR.
117 if !sess.opts.debugging_opts.keep_mtwt_tables &&
118 !sess.opts.debugging_opts.save_analysis {
119 syntax::ext::mtwt::clear_tables();
120 }
121
122 let arenas = ty::CtxtArenas::new();
123 let ast_map = make_map(&sess, &mut hir_forest);
124
125 write_out_deps(&sess, &outputs, &id);
126
127 controller_entry_point!(after_write_deps,
128 sess,
129 CompileState::state_after_write_deps(input,
130 &sess,
131 outdir,
132 &ast_map,
133 &expanded_crate,
134 &ast_map.krate(),
135 &id[..],
136 &lcx));
137
138 time(sess.time_passes(), "attribute checking", || {
139 front::check_attr::check_crate(&sess, &expanded_crate);
140 });
141
142 time(sess.time_passes(),
143 "early lint checks",
144 || lint::check_ast_crate(&sess, &expanded_crate));
145
146 phase_3_run_analysis_passes(&sess,
147 &cstore,
148 ast_map,
149 &arenas,
150 &id,
151 control.make_glob_map,
152 |tcx, mir_map, analysis| {
153
154 {
155 let state =
156 CompileState::state_after_analysis(input,
157 &tcx.sess,
158 outdir,
159 &expanded_crate,
160 tcx.map.krate(),
161 &analysis,
162 &mir_map,
163 tcx,
164 &lcx,
165 &id);
166 (control.after_analysis.callback)(state);
167
168 tcx.sess.abort_if_errors();
169 if control.after_analysis.stop == Compilation::Stop {
170 return Err(());
171 }
172 }
173
174 if log_enabled!(::log::INFO) {
175 println!("Pre-trans");
176 tcx.print_debug_stats();
177 }
178 let trans = phase_4_translate_to_llvm(tcx,
179 mir_map,
180 analysis);
181
182 if log_enabled!(::log::INFO) {
183 println!("Post-trans");
184 tcx.print_debug_stats();
185 }
186
187 // Discard interned strings as they are no longer required.
188 token::get_ident_interner().clear();
189
190 Ok((outputs, trans))
191 })
192 };
193
194 let (outputs, trans) = if let Ok(out) = result {
195 out
196 } else {
197 return;
198 };
199
200 phase_5_run_llvm_passes(&sess, &trans, &outputs);
201
202 controller_entry_point!(after_llvm,
203 sess,
204 CompileState::state_after_llvm(input, &sess, outdir, &trans));
205
206 phase_6_link_output(&sess, &trans, &outputs);
207 }
208
209 /// The name used for source code that doesn't originate in a file
210 /// (e.g. source from stdin or a string)
211 pub fn anon_src() -> String {
212 "<anon>".to_string()
213 }
214
215 pub fn source_name(input: &Input) -> String {
216 match *input {
217 // FIXME (#9639): This needs to handle non-utf8 paths
218 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
219 Input::Str(_) => anon_src(),
220 }
221 }
222
223 /// CompileController is used to customise compilation, it allows compilation to
224 /// be stopped and/or to call arbitrary code at various points in compilation.
225 /// It also allows for various flags to be set to influence what information gets
226 /// collected during compilation.
227 ///
228 /// This is a somewhat higher level controller than a Session - the Session
229 /// controls what happens in each phase, whereas the CompileController controls
230 /// whether a phase is run at all and whether other code (from outside the
231 /// the compiler) is run between phases.
232 ///
233 /// Note that if compilation is set to stop and a callback is provided for a
234 /// given entry point, the callback is called before compilation is stopped.
235 ///
236 /// Expect more entry points to be added in the future.
237 pub struct CompileController<'a> {
238 pub after_parse: PhaseController<'a>,
239 pub after_expand: PhaseController<'a>,
240 pub after_write_deps: PhaseController<'a>,
241 pub after_analysis: PhaseController<'a>,
242 pub after_llvm: PhaseController<'a>,
243
244 pub make_glob_map: resolve::MakeGlobMap,
245 }
246
247 impl<'a> CompileController<'a> {
248 pub fn basic() -> CompileController<'a> {
249 CompileController {
250 after_parse: PhaseController::basic(),
251 after_expand: PhaseController::basic(),
252 after_write_deps: PhaseController::basic(),
253 after_analysis: PhaseController::basic(),
254 after_llvm: PhaseController::basic(),
255 make_glob_map: resolve::MakeGlobMap::No,
256 }
257 }
258 }
259
260 pub struct PhaseController<'a> {
261 pub stop: Compilation,
262 pub callback: Box<Fn(CompileState) -> () + 'a>,
263 }
264
265 impl<'a> PhaseController<'a> {
266 pub fn basic() -> PhaseController<'a> {
267 PhaseController {
268 stop: Compilation::Continue,
269 callback: box |_| {},
270 }
271 }
272 }
273
274 /// State that is passed to a callback. What state is available depends on when
275 /// during compilation the callback is made. See the various constructor methods
276 /// (`state_*`) in the impl to see which data is provided for any given entry point.
277 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
278 pub input: &'a Input,
279 pub session: &'a Session,
280 pub cfg: Option<&'a ast::CrateConfig>,
281 pub krate: Option<&'a ast::Crate>,
282 pub crate_name: Option<&'a str>,
283 pub output_filenames: Option<&'a OutputFilenames>,
284 pub out_dir: Option<&'a Path>,
285 pub expanded_crate: Option<&'a ast::Crate>,
286 pub hir_crate: Option<&'a hir::Crate>,
287 pub ast_map: Option<&'a hir_map::Map<'ast>>,
288 pub mir_map: Option<&'a MirMap<'tcx>>,
289 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
290 pub tcx: Option<&'a ty::ctxt<'tcx>>,
291 pub lcx: Option<&'a LoweringContext<'a>>,
292 pub trans: Option<&'a trans::CrateTranslation>,
293 }
294
295 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
296 fn empty(input: &'a Input,
297 session: &'a Session,
298 out_dir: &'a Option<PathBuf>)
299 -> CompileState<'a, 'ast, 'tcx> {
300 CompileState {
301 input: input,
302 session: session,
303 out_dir: out_dir.as_ref().map(|s| &**s),
304 cfg: None,
305 krate: None,
306 crate_name: None,
307 output_filenames: None,
308 expanded_crate: None,
309 hir_crate: None,
310 ast_map: None,
311 analysis: None,
312 mir_map: None,
313 tcx: None,
314 lcx: None,
315 trans: None,
316 }
317 }
318
319 fn state_after_parse(input: &'a Input,
320 session: &'a Session,
321 out_dir: &'a Option<PathBuf>,
322 krate: &'a ast::Crate)
323 -> CompileState<'a, 'ast, 'tcx> {
324 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
325 }
326
327 fn state_after_expand(input: &'a Input,
328 session: &'a Session,
329 out_dir: &'a Option<PathBuf>,
330 expanded_crate: &'a ast::Crate,
331 crate_name: &'a str)
332 -> CompileState<'a, 'ast, 'tcx> {
333 CompileState {
334 crate_name: Some(crate_name),
335 expanded_crate: Some(expanded_crate),
336 ..CompileState::empty(input, session, out_dir)
337 }
338 }
339
340 fn state_after_write_deps(input: &'a Input,
341 session: &'a Session,
342 out_dir: &'a Option<PathBuf>,
343 ast_map: &'a hir_map::Map<'ast>,
344 krate: &'a ast::Crate,
345 hir_crate: &'a hir::Crate,
346 crate_name: &'a str,
347 lcx: &'a LoweringContext<'a>)
348 -> CompileState<'a, 'ast, 'tcx> {
349 CompileState {
350 crate_name: Some(crate_name),
351 ast_map: Some(ast_map),
352 krate: Some(krate),
353 hir_crate: Some(hir_crate),
354 lcx: Some(lcx),
355 ..CompileState::empty(input, session, out_dir)
356 }
357 }
358
359 fn state_after_analysis(input: &'a Input,
360 session: &'a Session,
361 out_dir: &'a Option<PathBuf>,
362 krate: &'a ast::Crate,
363 hir_crate: &'a hir::Crate,
364 analysis: &'a ty::CrateAnalysis,
365 mir_map: &'a MirMap<'tcx>,
366 tcx: &'a ty::ctxt<'tcx>,
367 lcx: &'a LoweringContext<'a>,
368 crate_name: &'a str)
369 -> CompileState<'a, 'ast, 'tcx> {
370 CompileState {
371 analysis: Some(analysis),
372 mir_map: Some(mir_map),
373 tcx: Some(tcx),
374 krate: Some(krate),
375 hir_crate: Some(hir_crate),
376 lcx: Some(lcx),
377 crate_name: Some(crate_name),
378 ..CompileState::empty(input, session, out_dir)
379 }
380 }
381
382
383 fn state_after_llvm(input: &'a Input,
384 session: &'a Session,
385 out_dir: &'a Option<PathBuf>,
386 trans: &'a trans::CrateTranslation)
387 -> CompileState<'a, 'ast, 'tcx> {
388 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
389 }
390 }
391
392 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate {
393 // These may be left in an incoherent state after a previous compile.
394 // `clear_tables` and `get_ident_interner().clear()` can be used to free
395 // memory, but they do not restore the initial state.
396 syntax::ext::mtwt::reset_tables();
397 token::reset_ident_interner();
398
399 let krate = time(sess.time_passes(), "parsing", || {
400 match *input {
401 Input::File(ref file) => {
402 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
403 }
404 Input::Str(ref src) => {
405 parse::parse_crate_from_source_str(anon_src().to_string(),
406 src.to_string(),
407 cfg.clone(),
408 &sess.parse_sess)
409 }
410 }
411 });
412
413 if sess.opts.debugging_opts.ast_json_noexpand {
414 println!("{}", json::as_json(&krate));
415 }
416
417 if sess.opts.debugging_opts.input_stats {
418 println!("Lines of code: {}", sess.codemap().count_lines());
419 println!("Pre-expansion node count: {}", count_nodes(&krate));
420 }
421
422 if let Some(ref s) = sess.opts.show_span {
423 syntax::show_span::run(sess.diagnostic(), s, &krate);
424 }
425
426 krate
427 }
428
429 fn count_nodes(krate: &ast::Crate) -> usize {
430 let mut counter = NodeCounter::new();
431 visit::walk_crate(&mut counter, krate);
432 counter.count
433 }
434
435 // For continuing compilation after a parsed crate has been
436 // modified
437
438 /// Run the "early phases" of the compiler: initial `cfg` processing,
439 /// loading compiler plugins (including those from `addl_plugins`),
440 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
441 /// harness if one is to be provided and injection of a dependency on the
442 /// standard library and prelude.
443 ///
444 /// Returns `None` if we're aborting after handling -W help.
445 pub fn phase_2_configure_and_expand(sess: &Session,
446 cstore: &CStore,
447 mut krate: ast::Crate,
448 crate_name: &str,
449 addl_plugins: Option<Vec<String>>)
450 -> Option<ast::Crate> {
451 let time_passes = sess.time_passes();
452
453 // strip before anything else because crate metadata may use #[cfg_attr]
454 // and so macros can depend on configuration variables, such as
455 //
456 // #[macro_use] #[cfg(foo)]
457 // mod bar { macro_rules! baz!(() => {{}}) }
458 //
459 // baz! should not use this definition unless foo is enabled.
460
461 let mut feature_gated_cfgs = vec![];
462 krate = time(time_passes, "configuration 1", || {
463 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs)
464 });
465
466 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
467 *sess.crate_metadata.borrow_mut() = collect_crate_metadata(sess, &krate.attrs);
468
469 time(time_passes, "recursion limit", || {
470 middle::recursion_limit::update_recursion_limit(sess, &krate);
471 });
472
473 time(time_passes, "gated macro checking", || {
474 let features = syntax::feature_gate::check_crate_macros(sess.codemap(),
475 &sess.parse_sess.span_diagnostic,
476 &krate);
477
478 // these need to be set "early" so that expansion sees `quote` if enabled.
479 *sess.features.borrow_mut() = features;
480 sess.abort_if_errors();
481 });
482
483
484 krate = time(time_passes, "crate injection", || {
485 syntax::std_inject::maybe_inject_crates_ref(krate, sess.opts.alt_std_name.clone())
486 });
487
488 let macros = time(time_passes,
489 "macro loading",
490 || macro_import::read_macro_defs(sess, &cstore, &krate));
491
492 let mut addl_plugins = Some(addl_plugins);
493 let registrars = time(time_passes, "plugin loading", || {
494 plugin::load::load_plugins(sess, &cstore, &krate, addl_plugins.take().unwrap())
495 });
496
497 let mut registry = Registry::new(sess, &krate);
498
499 time(time_passes, "plugin registration", || {
500 if sess.features.borrow().rustc_diagnostic_macros {
501 registry.register_macro("__diagnostic_used",
502 diagnostics::plugin::expand_diagnostic_used);
503 registry.register_macro("__register_diagnostic",
504 diagnostics::plugin::expand_register_diagnostic);
505 registry.register_macro("__build_diagnostic_array",
506 diagnostics::plugin::expand_build_diagnostic_array);
507 }
508
509 for registrar in registrars {
510 registry.args_hidden = Some(registrar.args);
511 (registrar.fun)(&mut registry);
512 }
513 });
514
515 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
516 llvm_passes, attributes, .. } = registry;
517
518 {
519 let mut ls = sess.lint_store.borrow_mut();
520 for pass in early_lint_passes {
521 ls.register_early_pass(Some(sess), true, pass);
522 }
523 for pass in late_lint_passes {
524 ls.register_late_pass(Some(sess), true, pass);
525 }
526
527 for (name, to) in lint_groups {
528 ls.register_group(Some(sess), true, name, to);
529 }
530
531 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
532 *sess.plugin_attributes.borrow_mut() = attributes.clone();
533 }
534
535 // Lint plugins are registered; now we can process command line flags.
536 if sess.opts.describe_lints {
537 super::describe_lints(&*sess.lint_store.borrow(), true);
538 return None;
539 }
540 sess.lint_store.borrow_mut().process_command_line(sess);
541
542 // Abort if there are errors from lint processing or a plugin registrar.
543 sess.abort_if_errors();
544
545 krate = time(time_passes, "expansion", || {
546 // Windows dlls do not have rpaths, so they don't know how to find their
547 // dependencies. It's up to us to tell the system where to find all the
548 // dependent dlls. Note that this uses cfg!(windows) as opposed to
549 // targ_cfg because syntax extensions are always loaded for the host
550 // compiler, not for the target.
551 let mut _old_path = OsString::new();
552 if cfg!(windows) {
553 _old_path = env::var_os("PATH").unwrap_or(_old_path);
554 let mut new_path = sess.host_filesearch(PathKind::All)
555 .get_dylib_search_paths();
556 new_path.extend(env::split_paths(&_old_path));
557 env::set_var("PATH", &env::join_paths(new_path).unwrap());
558 }
559 let features = sess.features.borrow();
560 let cfg = syntax::ext::expand::ExpansionConfig {
561 crate_name: crate_name.to_string(),
562 features: Some(&features),
563 recursion_limit: sess.recursion_limit.get(),
564 trace_mac: sess.opts.debugging_opts.trace_macros,
565 };
566 let (ret, macro_names) = syntax::ext::expand::expand_crate(&sess.parse_sess,
567 cfg,
568 macros,
569 syntax_exts,
570 &mut feature_gated_cfgs,
571 krate);
572 if cfg!(windows) {
573 env::set_var("PATH", &_old_path);
574 }
575 *sess.available_macros.borrow_mut() = macro_names;
576 ret
577 });
578
579 // Needs to go *after* expansion to be able to check the results
580 // of macro expansion. This runs before #[cfg] to try to catch as
581 // much as possible (e.g. help the programmer avoid platform
582 // specific differences)
583 time(time_passes, "complete gated feature checking 1", || {
584 let features = syntax::feature_gate::check_crate(sess.codemap(),
585 &sess.parse_sess.span_diagnostic,
586 &krate,
587 &attributes,
588 sess.opts.unstable_features);
589 *sess.features.borrow_mut() = features;
590 sess.abort_if_errors();
591 });
592
593 // JBC: make CFG processing part of expansion to avoid this problem:
594
595 // strip again, in case expansion added anything with a #[cfg].
596 krate = time(time_passes, "configuration 2", || {
597 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs)
598 });
599
600 time(time_passes, "gated configuration checking", || {
601 let features = sess.features.borrow();
602 feature_gated_cfgs.sort();
603 feature_gated_cfgs.dedup();
604 for cfg in &feature_gated_cfgs {
605 cfg.check_and_emit(sess.diagnostic(), &features);
606 }
607 });
608
609 krate = time(time_passes, "maybe building test harness", || {
610 syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
611 });
612
613 krate = time(time_passes,
614 "prelude injection",
615 || syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
616
617 time(time_passes,
618 "checking that all macro invocations are gone",
619 || syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
620
621 time(time_passes,
622 "checking for inline asm in case the target doesn't support it",
623 || middle::check_no_asm::check_crate(sess, &krate));
624
625 // One final feature gating of the true AST that gets compiled
626 // later, to make sure we've got everything (e.g. configuration
627 // can insert new attributes via `cfg_attr`)
628 time(time_passes, "complete gated feature checking 2", || {
629 let features = syntax::feature_gate::check_crate(sess.codemap(),
630 &sess.parse_sess.span_diagnostic,
631 &krate,
632 &attributes,
633 sess.opts.unstable_features);
634 *sess.features.borrow_mut() = features;
635 sess.abort_if_errors();
636 });
637
638 if sess.opts.debugging_opts.input_stats {
639 println!("Post-expansion node count: {}", count_nodes(&krate));
640 }
641
642 Some(krate)
643 }
644
645 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
646 struct NodeIdAssigner<'a> {
647 sess: &'a Session,
648 }
649
650 impl<'a> Folder for NodeIdAssigner<'a> {
651 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
652 assert_eq!(old_id, ast::DUMMY_NODE_ID);
653 self.sess.next_node_id()
654 }
655 }
656
657 let krate = time(sess.time_passes(),
658 "assigning node ids",
659 || NodeIdAssigner { sess: sess }.fold_crate(krate));
660
661 if sess.opts.debugging_opts.ast_json {
662 println!("{}", json::as_json(&krate));
663 }
664
665 krate
666 }
667
668 pub fn make_map<'ast>(sess: &Session,
669 forest: &'ast mut front::map::Forest)
670 -> front::map::Map<'ast> {
671 // Construct the 'ast'-map
672 let map = time(sess.time_passes(),
673 "indexing hir",
674 move || front::map::map_crate(forest));
675
676 map
677 }
678
679 /// Run the resolution, typechecking, region checking and other
680 /// miscellaneous analysis passes on the crate. Return various
681 /// structures carrying the results of the analysis.
682 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
683 cstore: &CStore,
684 ast_map: front::map::Map<'tcx>,
685 arenas: &'tcx ty::CtxtArenas<'tcx>,
686 name: &str,
687 make_glob_map: resolve::MakeGlobMap,
688 f: F)
689 -> R
690 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>, MirMap<'tcx>, ty::CrateAnalysis) -> R
691 {
692 let time_passes = sess.time_passes();
693 let krate = ast_map.krate();
694
695 time(time_passes,
696 "external crate/lib resolution",
697 || LocalCrateReader::new(sess, cstore, &ast_map).read_crates(krate));
698
699 let lang_items = time(time_passes,
700 "language item collection",
701 || middle::lang_items::collect_language_items(&sess, &ast_map));
702
703 let resolve::CrateMap {
704 def_map,
705 freevars,
706 export_map,
707 trait_map,
708 external_exports,
709 glob_map,
710 } = time(time_passes,
711 "resolution",
712 || resolve::resolve_crate(sess, &ast_map, make_glob_map));
713
714 let named_region_map = time(time_passes,
715 "lifetime resolution",
716 || middle::resolve_lifetime::krate(sess, krate, &def_map.borrow()));
717
718 time(time_passes,
719 "looking for entry point",
720 || middle::entry::find_entry_point(sess, &ast_map));
721
722 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
723 plugin::build::find_plugin_registrar(sess.diagnostic(), krate)
724 }));
725
726 let region_map = time(time_passes,
727 "region resolution",
728 || middle::region::resolve_crate(sess, krate));
729
730 time(time_passes,
731 "loop checking",
732 || middle::check_loop::check_crate(sess, krate));
733
734 time(time_passes,
735 "static item recursion checking",
736 || middle::check_static_recursion::check_crate(sess, krate, &def_map.borrow(), &ast_map));
737
738 ty::ctxt::create_and_enter(sess,
739 arenas,
740 def_map,
741 named_region_map,
742 ast_map,
743 freevars,
744 region_map,
745 lang_items,
746 stability::Index::new(krate),
747 |tcx| {
748 // passes are timed inside typeck
749 typeck::check_crate(tcx, trait_map);
750
751 time(time_passes,
752 "const checking",
753 || middle::check_const::check_crate(tcx));
754
755 let access_levels =
756 time(time_passes, "privacy checking", || {
757 rustc_privacy::check_crate(tcx,
758 &export_map,
759 external_exports)
760 });
761
762 // Do not move this check past lint
763 time(time_passes, "stability index", || {
764 tcx.stability.borrow_mut().build(tcx, krate, &access_levels)
765 });
766
767 time(time_passes,
768 "intrinsic checking",
769 || middle::intrinsicck::check_crate(tcx));
770
771 time(time_passes,
772 "effect checking",
773 || middle::effect::check_crate(tcx));
774
775 time(time_passes,
776 "match checking",
777 || middle::check_match::check_crate(tcx));
778
779 let mir_map =
780 time(time_passes,
781 "MIR dump",
782 || mir::mir_map::build_mir_for_crate(tcx));
783
784 time(time_passes,
785 "liveness checking",
786 || middle::liveness::check_crate(tcx));
787
788 time(time_passes,
789 "borrow checking",
790 || borrowck::check_crate(tcx));
791
792 time(time_passes,
793 "rvalue checking",
794 || middle::check_rvalues::check_crate(tcx, krate));
795
796 // Avoid overwhelming user with errors if type checking failed.
797 // I'm not sure how helpful this is, to be honest, but it avoids
798 // a
799 // lot of annoying errors in the compile-fail tests (basically,
800 // lint warnings and so on -- kindck used to do this abort, but
801 // kindck is gone now). -nmatsakis
802 tcx.sess.abort_if_errors();
803
804 let reachable_map =
805 time(time_passes,
806 "reachability checking",
807 || reachable::find_reachable(tcx, &access_levels));
808
809 time(time_passes, "death checking", || {
810 middle::dead::check_crate(tcx, &access_levels);
811 });
812
813 let ref lib_features_used =
814 time(time_passes,
815 "stability checking",
816 || stability::check_unstable_api_usage(tcx));
817
818 time(time_passes, "unused lib feature checking", || {
819 stability::check_unused_or_stable_features(&tcx.sess,
820 lib_features_used)
821 });
822
823 time(time_passes,
824 "lint checking",
825 || lint::check_crate(tcx, &access_levels));
826
827 // The above three passes generate errors w/o aborting
828 tcx.sess.abort_if_errors();
829
830 f(tcx,
831 mir_map,
832 ty::CrateAnalysis {
833 export_map: export_map,
834 access_levels: access_levels,
835 reachable: reachable_map,
836 name: name,
837 glob_map: glob_map,
838 })
839 })
840 }
841
842 /// Run the translation phase to LLVM, after which the AST and analysis can
843 /// be discarded.
844 pub fn phase_4_translate_to_llvm<'tcx>(tcx: &ty::ctxt<'tcx>,
845 mut mir_map: MirMap<'tcx>,
846 analysis: ty::CrateAnalysis)
847 -> trans::CrateTranslation {
848 let time_passes = tcx.sess.time_passes();
849
850 time(time_passes,
851 "resolving dependency formats",
852 || dependency_format::calculate(&tcx.sess));
853
854 time(time_passes,
855 "erasing regions from MIR",
856 || mir::transform::erase_regions::erase_regions(tcx, &mut mir_map));
857
858 // Option dance to work around the lack of stack once closures.
859 time(time_passes,
860 "translation",
861 move || trans::trans_crate(tcx, &mir_map, analysis))
862 }
863
864 /// Run LLVM itself, producing a bitcode file, assembly file or object file
865 /// as a side effect.
866 pub fn phase_5_run_llvm_passes(sess: &Session,
867 trans: &trans::CrateTranslation,
868 outputs: &OutputFilenames) {
869 if sess.opts.cg.no_integrated_as {
870 let mut map = HashMap::new();
871 map.insert(OutputType::Assembly, None);
872 time(sess.time_passes(),
873 "LLVM passes",
874 || write::run_passes(sess, trans, &map, outputs));
875
876 write::run_assembler(sess, outputs);
877
878 // Remove assembly source, unless --save-temps was specified
879 if !sess.opts.cg.save_temps {
880 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
881 }
882 } else {
883 time(sess.time_passes(),
884 "LLVM passes",
885 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
886 }
887
888 sess.abort_if_errors();
889 }
890
891 /// Run the linker on any artifacts that resulted from the LLVM run.
892 /// This should produce either a finished executable or library.
893 pub fn phase_6_link_output(sess: &Session,
894 trans: &trans::CrateTranslation,
895 outputs: &OutputFilenames) {
896 time(sess.time_passes(),
897 "linking",
898 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
899 }
900
901 fn escape_dep_filename(filename: &str) -> String {
902 // Apparently clang and gcc *only* escape spaces:
903 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
904 filename.replace(" ", "\\ ")
905 }
906
907 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
908 let mut out_filenames = Vec::new();
909 for output_type in sess.opts.output_types.keys() {
910 let file = outputs.path(*output_type);
911 match *output_type {
912 OutputType::Exe => {
913 for output in sess.crate_types.borrow().iter() {
914 let p = link::filename_for_input(sess, *output, id, outputs);
915 out_filenames.push(p);
916 }
917 }
918 _ => {
919 out_filenames.push(file);
920 }
921 }
922 }
923
924 // Write out dependency rules to the dep-info file if requested
925 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
926 return;
927 }
928 let deps_filename = outputs.path(OutputType::DepInfo);
929
930 let result =
931 (|| -> io::Result<()> {
932 // Build a list of files used to compile the output and
933 // write Makefile-compatible dependency rules
934 let files: Vec<String> = sess.codemap()
935 .files
936 .borrow()
937 .iter()
938 .filter(|fmap| fmap.is_real_file())
939 .filter(|fmap| !fmap.is_imported())
940 .map(|fmap| escape_dep_filename(&fmap.name))
941 .collect();
942 let mut file = try!(fs::File::create(&deps_filename));
943 for path in &out_filenames {
944 try!(write!(file, "{}: {}\n\n", path.display(), files.join(" ")));
945 }
946
947 // Emit a fake target for each input file to the compilation. This
948 // prevents `make` from spitting out an error if a file is later
949 // deleted. For more info see #28735
950 for path in files {
951 try!(writeln!(file, "{}:", path));
952 }
953 Ok(())
954 })();
955
956 match result {
957 Ok(()) => {}
958 Err(e) => {
959 sess.fatal(&format!("error writing dependencies to `{}`: {}",
960 deps_filename.display(),
961 e));
962 }
963 }
964 }
965
966 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
967 // Unconditionally collect crate types from attributes to make them used
968 let attr_types: Vec<config::CrateType> =
969 attrs.iter()
970 .filter_map(|a| {
971 if a.check_name("crate_type") {
972 match a.value_str() {
973 Some(ref n) if *n == "rlib" => {
974 Some(config::CrateTypeRlib)
975 }
976 Some(ref n) if *n == "dylib" => {
977 Some(config::CrateTypeDylib)
978 }
979 Some(ref n) if *n == "lib" => {
980 Some(config::default_lib_output())
981 }
982 Some(ref n) if *n == "staticlib" => {
983 Some(config::CrateTypeStaticlib)
984 }
985 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
986 Some(_) => {
987 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
988 ast::CRATE_NODE_ID,
989 a.span,
990 "invalid `crate_type` value".to_string());
991 None
992 }
993 _ => {
994 session.span_err(a.span, "`crate_type` requires a value");
995 session.note("for example: `#![crate_type=\"lib\"]`");
996 None
997 }
998 }
999 } else {
1000 None
1001 }
1002 })
1003 .collect();
1004
1005 // If we're generating a test executable, then ignore all other output
1006 // styles at all other locations
1007 if session.opts.test {
1008 return vec![config::CrateTypeExecutable];
1009 }
1010
1011 // Only check command line flags if present. If no types are specified by
1012 // command line, then reuse the empty `base` Vec to hold the types that
1013 // will be found in crate attributes.
1014 let mut base = session.opts.crate_types.clone();
1015 if base.is_empty() {
1016 base.extend(attr_types);
1017 if base.is_empty() {
1018 base.push(link::default_output_for_target(session));
1019 }
1020 base.sort();
1021 base.dedup();
1022 }
1023
1024 base.into_iter()
1025 .filter(|crate_type| {
1026 let res = !link::invalid_output_for_target(session, *crate_type);
1027
1028 if !res {
1029 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1030 *crate_type,
1031 session.opts.target_triple));
1032 }
1033
1034 res
1035 })
1036 .collect()
1037 }
1038
1039 pub fn collect_crate_metadata(session: &Session, _attrs: &[ast::Attribute]) -> Vec<String> {
1040 session.opts.cg.metadata.clone()
1041 }
1042
1043 pub fn build_output_filenames(input: &Input,
1044 odir: &Option<PathBuf>,
1045 ofile: &Option<PathBuf>,
1046 attrs: &[ast::Attribute],
1047 sess: &Session)
1048 -> OutputFilenames {
1049 match *ofile {
1050 None => {
1051 // "-" as input file will cause the parser to read from stdin so we
1052 // have to make up a name
1053 // We want to toss everything after the final '.'
1054 let dirpath = match *odir {
1055 Some(ref d) => d.clone(),
1056 None => PathBuf::new(),
1057 };
1058
1059 // If a crate name is present, we use it as the link name
1060 let stem = sess.opts
1061 .crate_name
1062 .clone()
1063 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1064 .unwrap_or(input.filestem());
1065
1066 OutputFilenames {
1067 out_directory: dirpath,
1068 out_filestem: stem,
1069 single_output_file: None,
1070 extra: sess.opts.cg.extra_filename.clone(),
1071 outputs: sess.opts.output_types.clone(),
1072 }
1073 }
1074
1075 Some(ref out_file) => {
1076 let unnamed_output_types = sess.opts
1077 .output_types
1078 .values()
1079 .filter(|a| a.is_none())
1080 .count();
1081 let ofile = if unnamed_output_types > 1 {
1082 sess.warn("ignoring specified output filename because multiple outputs were \
1083 requested");
1084 None
1085 } else {
1086 Some(out_file.clone())
1087 };
1088 if *odir != None {
1089 sess.warn("ignoring --out-dir flag due to -o flag.");
1090 }
1091
1092 let cur_dir = Path::new("");
1093
1094 OutputFilenames {
1095 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1096 out_filestem: out_file.file_stem()
1097 .unwrap_or(OsStr::new(""))
1098 .to_str()
1099 .unwrap()
1100 .to_string(),
1101 single_output_file: ofile,
1102 extra: sess.opts.cg.extra_filename.clone(),
1103 outputs: sess.opts.output_types.clone(),
1104 }
1105 }
1106 }
1107 }