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