driver.rs 37.5 KB
Newer Older
N
Nick Cameron 已提交
1
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

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;
K
Keegan McAllister 已提交
17
use rustc::metadata::creader::CrateReader;
18
use rustc::middle::{stability, ty, reachable};
19 20 21 22 23
use rustc::middle::dependency_format;
use rustc::middle;
use rustc::plugin::registry::Registry;
use rustc::plugin;
use rustc::util::common::time;
24
use rustc_borrowck as borrowck;
25
use rustc_resolve as resolve;
26 27 28
use rustc_trans::back::link;
use rustc_trans::back::write;
use rustc_trans::trans;
N
Niko Matsakis 已提交
29
use rustc_typeck as typeck;
30
use rustc_privacy;
N
Nick Cameron 已提交
31
use super::Compilation;
32

33
use serialize::json;
34

A
Alex Crichton 已提交
35
use std::env;
36
use std::ffi::{OsString, OsStr};
A
Alex Crichton 已提交
37 38 39
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
40 41
use syntax::ast;
use syntax::attr;
42
use syntax::attr::AttrMetaMethods;
43
use syntax::diagnostics;
44
use syntax::parse;
J
John Clements 已提交
45
use syntax::parse::token;
46
use syntax;
H
Haitao Li 已提交
47

N
Nick Cameron 已提交
48 49 50
pub fn compile_input(sess: Session,
                     cfg: ast::CrateConfig,
                     input: &Input,
A
Alex Crichton 已提交
51 52
                     outdir: &Option<PathBuf>,
                     output: &Option<PathBuf>,
53 54
                     addl_plugins: Option<Vec<String>>,
                     control: CompileController) {
55 56 57 58 59
    macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
        let state = $make_state;
        (control.$point.callback)(state);

        $tsess.abort_if_errors();
N
Nick Cameron 已提交
60
        if control.$point.stop == Compilation::Stop {
61 62 63 64
            return;
        }
    })}

N
Nick Cameron 已提交
65 66 67
    // We need nested scopes here, because the intermediate results can keep
    // large chunks of memory alive and we want to free them as soon as
    // possible to keep the peak memory usage low
68
    let (sess, result) = {
69
        let (outputs, expanded_crate, id) = {
N
Nick Cameron 已提交
70
            let krate = phase_1_parse_input(&sess, cfg, input);
71 72

            controller_entry_point!(after_parse,
73
                                    sess,
74 75 76 77 78
                                    CompileState::state_after_parse(input,
                                                                    &sess,
                                                                    outdir,
                                                                    &krate));

N
Nick Cameron 已提交
79 80 81
            let outputs = build_output_filenames(input,
                                                 outdir,
                                                 output,
82
                                                 &krate.attrs,
N
Nick Cameron 已提交
83
                                                 &sess);
84
            let id = link::find_crate_name(Some(&sess),
85
                                           &krate.attrs,
86
                                           input);
87
            let expanded_crate
88 89
                = match phase_2_configure_and_expand(&sess,
                                                     krate,
90
                                                     &id[..],
91
                                                     addl_plugins) {
92
                    None => return,
93
                    Some(k) => k
94 95
                };

96
            (outputs, expanded_crate, id)
N
Nick Cameron 已提交
97
        };
98

99
        controller_entry_point!(after_expand,
100
                                sess,
101 102 103 104
                                CompileState::state_after_expand(input,
                                                                 &sess,
                                                                 outdir,
                                                                 &expanded_crate,
105
                                                                 &id[..]));
106

107
        let mut forest = ast_map::Forest::new(expanded_crate);
108
        let arenas = ty::CtxtArenas::new();
109 110
        let ast_map = assign_node_ids_and_map(&sess, &mut forest);

111
        write_out_deps(&sess, input, &outputs, &id[..]);
N
Nick Cameron 已提交
112

113
        controller_entry_point!(after_write_deps,
114
                                sess,
115 116 117 118
                                CompileState::state_after_write_deps(input,
                                                                     &sess,
                                                                     outdir,
                                                                     &ast_map,
119
                                                                     &ast_map.krate(),
120
                                                                     &id[..]));
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        phase_3_run_analysis_passes(sess,
                                    ast_map,
                                    &arenas,
                                    id,
                                    control.make_glob_map,
                                    |tcx, analysis| {

            {
                let state = CompileState::state_after_analysis(input,
                                                               &tcx.sess,
                                                               outdir,
                                                               tcx.map.krate(),
                                                               &analysis,
                                                               tcx);
                (control.after_analysis.callback)(state);

                tcx.sess.abort_if_errors();
                if control.after_analysis.stop == Compilation::Stop {
                    return Err(());
                }
            }
N
Nick Cameron 已提交
143

144 145 146 147 148 149 150 151 152 153 154 155 156
            if log_enabled!(::log::INFO) {
                println!("Pre-trans");
                tcx.print_debug_stats();
            }
            let trans = phase_4_translate_to_llvm(tcx, analysis);

            if log_enabled!(::log::INFO) {
                println!("Post-trans");
                tcx.print_debug_stats();
            }

            // Discard interned strings as they are no longer required.
            token::get_ident_interner().clear();
157

158 159 160
            Ok((outputs, trans))
        })
    };
N
Nick Cameron 已提交
161

162 163 164 165
    let (outputs, trans) = if let Ok(out) = result {
        out
    } else {
        return;
N
Nick Cameron 已提交
166
    };
167

N
Nick Cameron 已提交
168
    phase_5_run_llvm_passes(&sess, &trans, &outputs);
169 170

    controller_entry_point!(after_llvm,
171
                            sess,
172 173 174 175 176
                            CompileState::state_after_llvm(input,
                                                           &sess,
                                                           outdir,
                                                           &trans));

N
Nick Cameron 已提交
177
    phase_6_link_output(&sess, &trans, &outputs);
178
}
H
Haitao Li 已提交
179

S
Steve Klabnik 已提交
180 181
/// The name used for source code that doesn't originate in a file
/// (e.g. source from stdin or a string)
182
pub fn anon_src() -> String {
183
    "<anon>".to_string()
P
Patrick Walton 已提交
184
}
185

186
pub fn source_name(input: &Input) -> String {
187
    match *input {
E
Eduard Burtescu 已提交
188
        // FIXME (#9639): This needs to handle non-utf8 paths
A
Alex Crichton 已提交
189
        Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
190
        Input::Str(_) => anon_src()
191 192 193
    }
}

194 195 196
/// CompileController is used to customise compilation, it allows compilation to
/// be stopped and/or to call arbitrary code at various points in compilation.
/// It also allows for various flags to be set to influence what information gets
J
Joseph Crail 已提交
197
/// collected during compilation.
198 199 200 201 202 203 204 205 206 207 208 209 210
///
/// This is a somewhat higher level controller than a Session - the Session
/// controls what happens in each phase, whereas the CompileController controls
/// whether a phase is run at all and whether other code (from outside the
/// the compiler) is run between phases.
///
/// Note that if compilation is set to stop and a callback is provided for a
/// given entry point, the callback is called before compilation is stopped.
///
/// Expect more entry points to be added in the future.
pub struct CompileController<'a> {
    pub after_parse: PhaseController<'a>,
    pub after_expand: PhaseController<'a>,
211
    pub after_write_deps: PhaseController<'a>,
212 213 214 215 216 217 218 219 220 221 222
    pub after_analysis: PhaseController<'a>,
    pub after_llvm: PhaseController<'a>,

    pub make_glob_map: resolve::MakeGlobMap,
}

impl<'a> CompileController<'a> {
    pub fn basic() -> CompileController<'a> {
        CompileController {
            after_parse: PhaseController::basic(),
            after_expand: PhaseController::basic(),
223
            after_write_deps:  PhaseController::basic(),
224 225 226 227 228 229 230 231
            after_analysis: PhaseController::basic(),
            after_llvm: PhaseController::basic(),
            make_glob_map: resolve::MakeGlobMap::No,
        }
    }
}

pub struct PhaseController<'a> {
N
Nick Cameron 已提交
232
    pub stop: Compilation,
233 234 235 236 237 238
    pub callback: Box<Fn(CompileState) -> () + 'a>,
}

impl<'a> PhaseController<'a> {
    pub fn basic() -> PhaseController<'a> {
        PhaseController {
N
Nick Cameron 已提交
239
            stop: Compilation::Continue,
240
            callback: box |_| {},
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        }
    }
}

/// State that is passed to a callback. What state is available depends on when
/// during compilation the callback is made. See the various constructor methods
/// (`state_*`) in the impl to see which data is provided for any given entry point.
pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
    pub input: &'a Input,
    pub session: &'a Session,
    pub cfg: Option<&'a ast::CrateConfig>,
    pub krate: Option<&'a ast::Crate>,
    pub crate_name: Option<&'a str>,
    pub output_filenames: Option<&'a OutputFilenames>,
    pub out_dir: Option<&'a Path>,
    pub expanded_crate: Option<&'a ast::Crate>,
    pub ast_map: Option<&'a ast_map::Map<'ast>>,
258
    pub analysis: Option<&'a ty::CrateAnalysis>,
259 260 261 262 263 264 265
    pub tcx: Option<&'a ty::ctxt<'tcx>>,
    pub trans: Option<&'a trans::CrateTranslation>,
}

impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
    fn empty(input: &'a Input,
             session: &'a Session,
A
Alex Crichton 已提交
266
             out_dir: &'a Option<PathBuf>)
267 268 269 270
             -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            input: input,
            session: session,
A
Alex Crichton 已提交
271
            out_dir: out_dir.as_ref().map(|s| &**s),
272 273 274 275 276 277 278 279 280 281 282 283 284 285
            cfg: None,
            krate: None,
            crate_name: None,
            output_filenames: None,
            expanded_crate: None,
            ast_map: None,
            analysis: None,
            tcx: None,
            trans: None,
        }
    }

    fn state_after_parse(input: &'a Input,
                         session: &'a Session,
A
Alex Crichton 已提交
286
                         out_dir: &'a Option<PathBuf>,
287 288 289 290 291 292 293 294 295 296
                         krate: &'a ast::Crate)
                         -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            krate: Some(krate),
            .. CompileState::empty(input, session, out_dir)
        }
    }

    fn state_after_expand(input: &'a Input,
                          session: &'a Session,
A
Alex Crichton 已提交
297
                          out_dir: &'a Option<PathBuf>,
298 299 300 301 302 303 304 305 306 307
                          expanded_crate: &'a ast::Crate,
                          crate_name: &'a str)
                          -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            crate_name: Some(crate_name),
            expanded_crate: Some(expanded_crate),
            .. CompileState::empty(input, session, out_dir)
        }
    }

308 309
    fn state_after_write_deps(input: &'a Input,
                              session: &'a Session,
A
Alex Crichton 已提交
310
                              out_dir: &'a Option<PathBuf>,
311
                              ast_map: &'a ast_map::Map<'ast>,
312
                              expanded_crate: &'a ast::Crate,
313 314 315 316 317
                              crate_name: &'a str)
                              -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            crate_name: Some(crate_name),
            ast_map: Some(ast_map),
318
            expanded_crate: Some(expanded_crate),
319 320 321 322
            .. CompileState::empty(input, session, out_dir)
        }
    }

323 324
    fn state_after_analysis(input: &'a Input,
                            session: &'a Session,
A
Alex Crichton 已提交
325
                            out_dir: &'a Option<PathBuf>,
326
                            expanded_crate: &'a ast::Crate,
327
                            analysis: &'a ty::CrateAnalysis,
328 329 330 331 332
                            tcx: &'a ty::ctxt<'tcx>)
                            -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            analysis: Some(analysis),
            tcx: Some(tcx),
333
            expanded_crate: Some(expanded_crate),
334 335 336 337 338 339 340
            .. CompileState::empty(input, session, out_dir)
        }
    }


    fn state_after_llvm(input: &'a Input,
                        session: &'a Session,
A
Alex Crichton 已提交
341
                        out_dir: &'a Option<PathBuf>,
342 343 344 345 346 347 348 349 350
                        trans: &'a trans::CrateTranslation)
                        -> CompileState<'a, 'ast, 'tcx> {
        CompileState {
            trans: Some(trans),
            .. CompileState::empty(input, session, out_dir)
        }
    }
}

E
Eduard Burtescu 已提交
351
pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
A
Alex Crichton 已提交
352
    -> ast::Crate {
M
Murarth 已提交
353 354 355 356 357 358
    // These may be left in an incoherent state after a previous compile.
    // `clear_tables` and `get_ident_interner().clear()` can be used to free
    // memory, but they do not restore the initial state.
    syntax::ext::mtwt::reset_tables();
    token::reset_ident_interner();

359
    let krate = time(sess.time_passes(), "parsing", (), |_| {
360
        match *input {
361
            Input::File(ref file) => {
E
Eduard Burtescu 已提交
362
                parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
363
            }
364
            Input::Str(ref src) => {
365 366
                parse::parse_crate_from_source_str(anon_src().to_string(),
                                                   src.to_string(),
367
                                                   cfg.clone(),
E
Eduard Burtescu 已提交
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
    }

S
Seo Sanghyeon 已提交
377
    if let Some(ref s) = sess.opts.show_span {
378
        syntax::show_span::run(sess.diagnostic(), s, &krate);
379 380
    }

381
    krate
382
}
H
Haitao Li 已提交
383

384 385
// For continuing compilation after a parsed crate has been
// modified
386

387
/// Run the "early phases" of the compiler: initial `cfg` processing,
B
Brian Anderson 已提交
388
/// loading compiler plugins (including those from `addl_plugins`),
389 390 391
/// syntax expansion, secondary `cfg` expansion, synthesis of a test
/// harness if one is to be provided and injection of a dependency on the
/// standard library and prelude.
392 393
///
/// Returns `None` if we're aborting after handling -W help.
E
Eduard Burtescu 已提交
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();
H
Haitao Li 已提交
400

401 402
    // strip before anything else because crate metadata may use #[cfg_attr]
    // and so macros can depend on configuration variables, such as
403
    //
404
    //   #[macro_use] #[cfg(foo)]
405 406 407
    //   mod bar { macro_rules! baz!(() => {{}}) }
    //
    // baz! should not use this definition unless foo is enabled.
408

409 410 411
    krate = time(time_passes, "configuration 1", krate, |krate|
                 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));

412 413 414 415 416 417 418 419 420
    *sess.crate_types.borrow_mut() =
        collect_crate_types(sess, &krate.attrs);
    *sess.crate_metadata.borrow_mut() =
        collect_crate_metadata(sess, &krate.attrs);

    time(time_passes, "recursion limit", (), |_| {
        middle::recursion_limit::update_recursion_limit(sess, &krate);
    });

C
Corey Richardson 已提交
421
    time(time_passes, "gated macro checking", (), |_| {
422
        let features =
C
Corey Richardson 已提交
423 424 425 426 427 428 429 430 431
            syntax::feature_gate::check_crate_macros(sess.codemap(),
                                                     &sess.parse_sess.span_diagnostic,
                                                     &krate);

        // these need to be set "early" so that expansion sees `quote` if enabled.
        *sess.features.borrow_mut() = features;
        sess.abort_if_errors();
    });

432

433 434
    krate = time(time_passes, "crate injection", krate, |krate|
                 syntax::std_inject::maybe_inject_crates_ref(krate,
A
Aaron Turon 已提交
435
                                                             sess.opts.alt_std_name.clone()));
436

437 438 439
    let macros = time(time_passes, "macro loading", (), |_|
        metadata::macro_import::read_macro_defs(sess, &krate));

440
    let mut addl_plugins = Some(addl_plugins);
441 442
    let registrars = time(time_passes, "plugin loading", (), |_|
        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| {
N
Nick Cameron 已提交
447
        if sess.features.borrow().rustc_diagnostic_macros {
448 449 450 451 452 453 454 455
            registry.register_macro("__diagnostic_used",
                diagnostics::plugin::expand_diagnostic_used);
            registry.register_macro("__register_diagnostic",
                diagnostics::plugin::expand_register_diagnostic);
            registry.register_macro("__build_diagnostic_array",
                diagnostics::plugin::expand_build_diagnostic_array);
        }

456
        for registrar in registrars {
457 458
            registry.args_hidden = Some(registrar.args);
            (registrar.fun)(&mut registry);
459
        }
460
    });
461

462 463
    let Registry { syntax_exts, lint_passes, lint_groups,
                   llvm_passes, attributes, .. } = registry;
464

K
Keegan McAllister 已提交
465 466
    {
        let mut ls = sess.lint_store.borrow_mut();
467
        for pass in lint_passes {
K
Keegan McAllister 已提交
468 469
            ls.register_pass(Some(sess), true, pass);
        }
470

471
        for (name, to) in lint_groups {
472 473
            ls.register_group(Some(sess), true, name, to);
        }
474 475

        *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
476
        *sess.plugin_attributes.borrow_mut() = attributes.clone();
K
Keegan McAllister 已提交
477 478 479
    }

    // Lint plugins are registered; now we can process command line flags.
480
    if sess.opts.describe_lints {
K
Keegan McAllister 已提交
481
        super::describe_lints(&*sess.lint_store.borrow(), true);
482 483 484 485 486 487 488
        return None;
    }
    sess.lint_store.borrow_mut().process_command_line(sess);

    // Abort if there are errors from lint processing or a plugin registrar.
    sess.abort_if_errors();

489 490 491 492 493 494 495
    krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
        |(krate, macros, syntax_exts)| {
            // Windows dlls do not have rpaths, so they don't know how to find their
            // dependencies. It's up to us to tell the system where to find all the
            // dependent dlls. Note that this uses cfg!(windows) as opposed to
            // targ_cfg because syntax extensions are always loaded for the host
            // compiler, not for the target.
A
Aaron Turon 已提交
496
            let mut _old_path = OsString::new();
497
            if cfg!(windows) {
498
                _old_path = env::var_os("PATH").unwrap_or(_old_path);
499 500
                let mut new_path = sess.host_filesearch(PathKind::All)
                                       .get_dylib_search_paths();
A
Alex Crichton 已提交
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 513 514
                                              cfg,
                                              macros,
                                              syntax_exts,
515 516
                                              krate);
            if cfg!(windows) {
A
Alex Crichton 已提交
517
                env::set_var("PATH", &_old_path);
518 519
            }
            ret
520 521 522
        }
    );

523 524 525 526 527
    // Needs to go *after* expansion to be able to check the results
    // of macro expansion.  This runs before #[cfg] to try to catch as
    // much as possible (e.g. help the programmer avoid platform
    // specific differences)
    time(time_passes, "complete gated feature checking 1", (), |_| {
B
Brian Anderson 已提交
528
        let features =
529
            syntax::feature_gate::check_crate(sess.codemap(),
530
                                              &sess.parse_sess.span_diagnostic,
531 532
                                              &krate, &attributes,
                                              sess.opts.unstable_features);
533
        *sess.features.borrow_mut() = features;
C
Corey Richardson 已提交
534 535 536
        sess.abort_if_errors();
    });

J
John Clements 已提交
537 538
    // JBC: make CFG processing part of expansion to avoid this problem:

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|
N
Nick Cameron 已提交
544 545 546 547
                 syntax::test::modify_for_testing(&sess.parse_sess,
                                                  &sess.opts.cfg,
                                                  krate,
                                                  sess.diagnostic()));
548

549
    krate = time(time_passes, "prelude injection", krate, |krate|
550
                 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
B
Brian Anderson 已提交
551

552 553 554
    time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
         syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));

555 556 557 558 559 560 561
    // One final feature gating of the true AST that gets compiled
    // later, to make sure we've got everything (e.g. configuration
    // can insert new attributes via `cfg_attr`)
    time(time_passes, "complete gated feature checking 2", (), |_| {
        let features =
            syntax::feature_gate::check_crate(sess.codemap(),
                                              &sess.parse_sess.span_diagnostic,
562 563
                                              &krate, &attributes,
                                              sess.opts.unstable_features);
564 565 566 567
        *sess.features.borrow_mut() = features;
        sess.abort_if_errors();
    });

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    Some(krate)
}

pub fn assign_node_ids_and_map<'ast>(sess: &Session,
                                     forest: &'ast mut ast_map::Forest)
                                     -> ast_map::Map<'ast> {
    struct NodeIdAssigner<'a> {
        sess: &'a Session
    }

    impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
        fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
            assert_eq!(old_id, ast::DUMMY_NODE_ID);
            self.sess.next_node_id()
        }
    }

    let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
                   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 596 597
/// Run the resolution, typechecking, region checking and other
/// miscellaneous analysis passes on the crate. Return various
/// structures carrying the results of the analysis.
598 599 600 601 602 603 604
pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
                                               ast_map: ast_map::Map<'tcx>,
                                               arenas: &'tcx ty::CtxtArenas<'tcx>,
                                               name: String,
                                               make_glob_map: resolve::MakeGlobMap,
                                               f: F)
                                               -> (Session, R)
J
Jared Roesch 已提交
605
                                               where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
606 607
                                                               ty::CrateAnalysis) -> R
{
608
    let time_passes = sess.time_passes();
609
    let krate = ast_map.krate();
610

611
    time(time_passes, "external crate/lib resolution", (), |_|
K
Keegan McAllister 已提交
612
         CrateReader::new(&sess).read_crates(krate));
B
Brian Anderson 已提交
613

614
    let lang_items = time(time_passes, "language item collection", (), |_|
E
Eduard Burtescu 已提交
615
                          middle::lang_items::collect_language_items(krate, &sess));
616

N
Nick Cameron 已提交
617
    let resolve::CrateMap {
618 619
        def_map,
        freevars,
620
        export_map,
621 622
        trait_map,
        external_exports,
623
        glob_map,
624
    } =
625
        time(time_passes, "resolution", (),
626
             |_| resolve::resolve_crate(&sess, &ast_map, make_glob_map));
B
Brian Anderson 已提交
627

628 629 630
    // Discard MTWT tables that aren't required past resolution.
    syntax::ext::mtwt::clear_tables();

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));
B
Brian Anderson 已提交
636

637 638 639
    sess.plugin_registrar_fn.set(
        time(time_passes, "looking for plugin registrar", (), |_|
            plugin::build::find_plugin_registrar(
640
                sess.diagnostic(), krate)));
641

642
    let region_map = time(time_passes, "region resolution", (), |_|
E
Eduard Burtescu 已提交
643
                          middle::region::resolve_crate(&sess, krate));
644

645 646 647
    time(time_passes, "loop checking", (), |_|
         middle::check_loop::check_crate(&sess, krate));

648 649 650
    time(time_passes, "static item recursion checking", (), |_|
         middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));

651 652 653 654 655 656 657 658 659 660
    ty::ctxt::create_and_enter(sess,
                               arenas,
                               def_map,
                               named_region_map,
                               ast_map,
                               freevars,
                               region_map,
                               lang_items,
                               stability::Index::new(krate),
                               |tcx| {
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

        // passes are timed inside typeck
        typeck::check_crate(tcx, trait_map);

        time(time_passes, "const checking", (), |_|
            middle::check_const::check_crate(tcx));

        let (exported_items, public_items) =
                time(time_passes, "privacy checking", (), |_|
                    rustc_privacy::check_crate(tcx, &export_map, external_exports));

        // Do not move this check past lint
        time(time_passes, "stability index", (), |_|
            tcx.stability.borrow_mut().build(tcx, krate, &public_items));

        time(time_passes, "intrinsic checking", (), |_|
            middle::intrinsicck::check_crate(tcx));

        time(time_passes, "effect checking", (), |_|
            middle::effect::check_crate(tcx));

        time(time_passes, "match checking", (), |_|
            middle::check_match::check_crate(tcx));

        time(time_passes, "liveness checking", (), |_|
            middle::liveness::check_crate(tcx));

        time(time_passes, "borrow checking", (), |_|
            borrowck::check_crate(tcx));

        time(time_passes, "rvalue checking", (), |_|
            middle::check_rvalues::check_crate(tcx, krate));

        // Avoid overwhelming user with errors if type checking failed.
        // I'm not sure how helpful this is, to be honest, but it avoids a
        // lot of annoying errors in the compile-fail tests (basically,
        // lint warnings and so on -- kindck used to do this abort, but
        // kindck is gone now). -nmatsakis
        tcx.sess.abort_if_errors();

        let reachable_map =
            time(time_passes, "reachability checking", (), |_|
                reachable::find_reachable(tcx, &exported_items));

        time(time_passes, "death checking", (), |_| {
            middle::dead::check_crate(tcx,
                                      &exported_items,
                                      &reachable_map)
        });

        let ref lib_features_used =
            time(time_passes, "stability checking", (), |_|
                stability::check_unstable_api_usage(tcx));

        time(time_passes, "unused lib feature checking", (), |_|
            stability::check_unused_or_stable_features(
                &tcx.sess, lib_features_used));

        time(time_passes, "lint checking", (), |_|
            lint::check_crate(tcx, &exported_items));

        // The above three passes generate errors w/o aborting
        tcx.sess.abort_if_errors();

        f(tcx, ty::CrateAnalysis {
            export_map: export_map,
            exported_items: exported_items,
            public_items: public_items,
            reachable: reachable_map,
            name: name,
            glob_map: glob_map,
        })
733
    })
734
}
J
James Miller 已提交
735

736 737
/// Run the translation phase to LLVM, after which the AST and analysis can
/// be discarded.
738 739 740
pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis)
                                 -> trans::CrateTranslation {
    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 751
}

/// Run LLVM itself, producing a bitcode file, assembly file or object file
/// as a side effect.
E
Eduard Burtescu 已提交
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", (), |_|
N
Nick Cameron 已提交
759
            write::run_passes(sess, trans, &[output_type], outputs));
760

761
        write::run_assembler(sess, outputs);
V
Vadim Chugunov 已提交
762

763
        // Remove assembly source, unless --save-temps was specified
764
        if !sess.opts.cg.save_temps {
A
Alex Crichton 已提交
765
            fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
V
Vadim Chugunov 已提交
766
        }
767
    } else {
768
        time(sess.time_passes(), "LLVM passes", (), |_|
769 770
            write::run_passes(sess,
                              trans,
771
                              &sess.opts.output_types,
772
                              outputs));
773
    }
774 775

    sess.abort_if_errors();
776
}
H
Haitao Li 已提交
777

778 779
/// Run the linker on any artifacts that resulted from the LLVM run.
/// This should produce either a finished executable or library.
E
Eduard Burtescu 已提交
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,
A
Alex Crichton 已提交
786
                           outputs,
787
                           &trans.link.crate_name));
788 789
}

790 791 792 793 794 795
fn escape_dep_filename(filename: &str) -> String {
    // Apparently clang and gcc *only* escape spaces:
    // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
    filename.replace(" ", "\\ ")
}

E
Eduard Burtescu 已提交
796
fn write_out_deps(sess: &Session,
A
Alex Crichton 已提交
797 798
                  input: &Input,
                  outputs: &OutputFilenames,
799
                  id: &str) {
800

801
    let mut out_filenames = Vec::new();
802
    for output_type in &sess.opts.output_types {
A
Alex Crichton 已提交
803 804
        let file = outputs.path(*output_type);
        match *output_type {
805
            config::OutputTypeExe => {
806
                for output in sess.crate_types.borrow().iter() {
807 808
                    let p = link::filename_for_input(sess, *output,
                                                     id, &file);
A
Alex Crichton 已提交
809 810 811 812 813 814
                    out_filenames.push(p);
                }
            }
            _ => { out_filenames.push(file); }
        }
    }
815

A
Alex Crichton 已提交
816 817
    // Write out dependency rules to the dep-info file if requested with
    // --dep-info
818 819 820
    let deps_filename = match sess.opts.write_dependency_info {
        // Use filename from --dep-file argument if given
        (true, Some(ref filename)) => filename.clone(),
A
Alex Crichton 已提交
821 822
        // Use default filename: crate source filename with extension replaced
        // by ".d"
823
        (true, None) => match *input {
824 825
            Input::File(..) => outputs.with_extension("d"),
            Input::Str(..) => {
A
Alex Crichton 已提交
826 827
                sess.warn("can not write --dep-info without a filename \
                           when compiling stdin.");
828
                return
829 830
            },
        },
831
        _ => return,
832
    };
833

A
Alex Crichton 已提交
834
    let result = (|| -> io::Result<()> {
835 836
        // Build a list of files used to compile the output and
        // write Makefile-compatible dependency rules
837
        let files: Vec<String> = sess.codemap().files.borrow()
838 839 840
                                   .iter()
                                   .filter(|fmap| fmap.is_real_file())
                                   .filter(|fmap| !fmap.is_imported())
841
                                   .map(|fmap| escape_dep_filename(&fmap.name))
842
                                   .collect();
A
Alex Crichton 已提交
843
        let mut file = try!(fs::File::create(&deps_filename));
844
        for path in &out_filenames {
A
Alex Crichton 已提交
845 846
            try!(write!(&mut file,
                        "{}: {}\n\n", path.display(), files.connect(" ")));
847 848 849 850 851 852 853
        }
        Ok(())
    })();

    match result {
        Ok(()) => {}
        Err(e) => {
J
Jorge Aparicio 已提交
854
            sess.fatal(&format!("error writing dependencies to `{}`: {}",
855
                               deps_filename.display(), e));
856
        }
857
    }
858 859
}

N
Nick Cameron 已提交
860 861
pub fn collect_crate_types(session: &Session,
                           attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
862 863 864 865
    // Unconditionally collect crate types from attributes to make them used
    let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
        if a.check_name("crate_type") {
            match a.value_str() {
866
                Some(ref n) if *n == "rlib" => {
867 868
                    Some(config::CrateTypeRlib)
                }
869
                Some(ref n) if *n == "dylib" => {
870 871
                    Some(config::CrateTypeDylib)
                }
872
                Some(ref n) if *n == "lib" => {
873 874
                    Some(config::default_lib_output())
                }
875
                Some(ref n) if *n == "staticlib" => {
876 877
                    Some(config::CrateTypeStaticlib)
                }
878
                Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
879
                Some(_) => {
A
Aaron Turon 已提交
880
                    session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
881 882 883
                                     ast::CRATE_NODE_ID,
                                     a.span,
                                     "invalid `crate_type` \
884
                                      value".to_string());
885 886 887
                    None
                }
                _ => {
888 889
                    session.span_err(a.span, "`crate_type` requires a value");
                    session.note("for example: `#![crate_type=\"lib\"]`");
890 891 892 893 894 895 896 897
                    None
                }
            }
        } else {
            None
        }
    }).collect();

N
Nick Cameron 已提交
898 899 900 901
    // If we're generating a test executable, then ignore all other output
    // styles at all other locations
    if session.opts.test {
        return vec!(config::CrateTypeExecutable)
S
Steven Stewart-Gallus 已提交
902
    }
H
Haitao Li 已提交
903

N
Nick Cameron 已提交
904 905 906 907
    // Only check command line flags if present. If no types are specified by
    // command line, then reuse the empty `base` Vec to hold the types that
    // will be found in crate attributes.
    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();
N
Nick Cameron 已提交
914
        base.dedup();
915
    }
916

A
Aaron Turon 已提交
917
    base.into_iter().filter(|crate_type| {
918 919 920
        let res = !link::invalid_output_for_target(session, *crate_type);

        if !res {
921
            session.warn(&format!("dropping unsupported crate type `{}` \
922
                                   for target `{}`",
923
                                 *crate_type, session.opts.target_triple));
924 925 926 927
        }

        res
    }).collect()
H
Haitao Li 已提交
928 929
}

930 931 932 933 934
pub fn collect_crate_metadata(session: &Session,
                              _attrs: &[ast::Attribute]) -> Vec<String> {
    session.opts.cg.metadata.clone()
}

935
pub fn build_output_filenames(input: &Input,
A
Alex Crichton 已提交
936 937
                              odir: &Option<PathBuf>,
                              ofile: &Option<PathBuf>,
938
                              attrs: &[ast::Attribute],
E
Eduard Burtescu 已提交
939
                              sess: &Session)
A
Alex Crichton 已提交
940
                           -> OutputFilenames {
941
    match *ofile {
A
Alex Crichton 已提交
942 943 944 945 946 947
        None => {
            // "-" as input file will cause the parser to read from stdin so we
            // have to make up a name
            // We want to toss everything after the final '.'
            let dirpath = match *odir {
                Some(ref d) => d.clone(),
A
Aaron Turon 已提交
948
                None => PathBuf::new()
A
Alex Crichton 已提交
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 955
            }).unwrap_or(input.filestem());

A
Alex Crichton 已提交
956 957 958 959
            OutputFilenames {
                out_directory: dirpath,
                out_filestem: stem,
                single_output_file: None,
960
                extra: sess.opts.cg.extra_filename.clone(),
A
Alex Crichton 已提交
961
            }
H
Haitao Li 已提交
962 963
        }

A
Alex Crichton 已提交
964 965 966 967 968 969 970 971 972 973 974
        Some(ref out_file) => {
            let ofile = if sess.opts.output_types.len() > 1 {
                sess.warn("ignoring specified output filename because multiple \
                           outputs were requested");
                None
            } else {
                Some(out_file.clone())
            };
            if *odir != None {
                sess.warn("ignoring --out-dir flag due to -o flag.");
            }
975 976 977

            let cur_dir = Path::new("");

A
Alex Crichton 已提交
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(""))
A
Alex Crichton 已提交
981
                                      .to_str().unwrap().to_string(),
A
Alex Crichton 已提交
982
                single_output_file: ofile,
983
                extra: sess.opts.cg.extra_filename.clone(),
A
Alex Crichton 已提交
984
            }
H
Haitao Li 已提交
985
        }
986
    }
H
Haitao Li 已提交
987
}