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