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