driver.rs 28.4 KB
Newer Older
S
Steven Fackler 已提交
1
// Copyright 2012-2013 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 12 13 14 15 16 17 18 19 20 21
use rustc::session::Session;
use rustc::session::config::{mod, Input, OutputFilenames};
use rustc::lint;
use rustc::metadata::creader;
use rustc::middle::{stability, ty, reachable};
use rustc::middle::dependency_format;
use rustc::middle;
use rustc::plugin::load::Plugins;
use rustc::plugin::registry::Registry;
use rustc::plugin;
use rustc::util::common::time;
22
use rustc_borrowck as borrowck;
23 24 25 26
use rustc_trans::back::link;
use rustc_trans::back::write;
use rustc_trans::save;
use rustc_trans::trans;
N
Niko Matsakis 已提交
27
use rustc_typeck as typeck;
28

A
Alex Crichton 已提交
29
use serialize::{json, Encodable};
30

A
Alex Crichton 已提交
31 32
use std::io;
use std::io::fs;
33
use std::os;
34
use arena::TypedArena;
35
use syntax::ast;
36
use syntax::ast_map;
37
use syntax::attr;
38
use syntax::attr::{AttrMetaMethods};
39
use syntax::diagnostics;
40
use syntax::parse;
J
John Clements 已提交
41
use syntax::parse::token;
42
use syntax;
H
Haitao Li 已提交
43

N
Nick Cameron 已提交
44 45 46 47
pub fn compile_input(sess: Session,
                     cfg: ast::CrateConfig,
                     input: &Input,
                     outdir: &Option<Path>,
48 49
                     output: &Option<Path>,
                     addl_plugins: Option<Plugins>) {
N
Nick Cameron 已提交
50 51 52 53
    // 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
    let (outputs, trans, sess) = {
54
        let (outputs, expanded_crate, id) = {
N
Nick Cameron 已提交
55 56 57 58 59 60 61
            let krate = phase_1_parse_input(&sess, cfg, input);
            if stop_after_phase_1(&sess) { return; }
            let outputs = build_output_filenames(input,
                                                 outdir,
                                                 output,
                                                 krate.attrs.as_slice(),
                                                 &sess);
62
            let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(),
63
                                           input);
64
            let expanded_crate
65 66
                = match phase_2_configure_and_expand(&sess, krate, id.as_slice(),
                                                     addl_plugins) {
67
                    None => return,
68
                    Some(k) => k
69 70
                };

71
            (outputs, expanded_crate, id)
N
Nick Cameron 已提交
72
        };
73 74 75 76

        let mut forest = ast_map::Forest::new(expanded_crate);
        let ast_map = assign_node_ids_and_map(&sess, &mut forest);

77
        write_out_deps(&sess, input, &outputs, id.as_slice());
N
Nick Cameron 已提交
78 79 80

        if stop_after_phase_2(&sess) { return; }

81
        let type_arena = TypedArena::new();
82 83
        let analysis = phase_3_run_analysis_passes(sess, ast_map, &type_arena, id);
        phase_save_analysis(&analysis.ty_cx.sess, analysis.ty_cx.map.krate(), &analysis, outdir);
N
Nick Cameron 已提交
84
        if stop_after_phase_3(&analysis.ty_cx.sess) { return; }
85
        let (tcx, trans) = phase_4_translate_to_llvm(analysis);
N
Nick Cameron 已提交
86 87 88 89 90 91 92 93 94

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

        (outputs, trans, tcx.sess)
    };
    phase_5_run_llvm_passes(&sess, &trans, &outputs);
    if stop_after_phase_5(&sess) { return; }
    phase_6_link_output(&sess, &trans, &outputs);
95
}
H
Haitao Li 已提交
96

S
Steve Klabnik 已提交
97 98
/// The name used for source code that doesn't originate in a file
/// (e.g. source from stdin or a string)
99
pub fn anon_src() -> String {
100
    "<anon>".to_string()
P
Patrick Walton 已提交
101
}
102

103
pub fn source_name(input: &Input) -> String {
104
    match *input {
E
Eduard Burtescu 已提交
105
        // FIXME (#9639): This needs to handle non-utf8 paths
106 107
        Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
        Input::Str(_) => anon_src()
108 109 110
    }
}

E
Eduard Burtescu 已提交
111
pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
A
Alex Crichton 已提交
112
    -> ast::Crate {
M
Murarth 已提交
113 114 115 116 117 118
    // 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();

119
    let krate = time(sess.time_passes(), "parsing", (), |_| {
120
        match *input {
121
            Input::File(ref file) => {
E
Eduard Burtescu 已提交
122
                parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
123
            }
124
            Input::Str(ref src) => {
125 126
                parse::parse_crate_from_source_str(anon_src().to_string(),
                                                   src.to_string(),
127
                                                   cfg.clone(),
E
Eduard Burtescu 已提交
128
                                                   &sess.parse_sess)
129 130
            }
        }
131 132
    });

N
Nick Cameron 已提交
133
    if sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0 {
134
        let mut stdout = io::BufferedWriter::new(io::stdout());
135
        let mut json = json::PrettyEncoder::new(&mut stdout);
S
Sean McArthur 已提交
136
        // unwrapping so IoError isn't ignored
F
Flavio Percoco 已提交
137
        krate.encode(&mut json).unwrap();
138 139
    }

140
    if sess.show_span() {
N
Nick Cameron 已提交
141
        syntax::show_span::run(sess.diagnostic(), &krate);
142 143
    }

144
    krate
145
}
H
Haitao Li 已提交
146

147 148
// For continuing compilation after a parsed crate has been
// modified
149

150
/// Run the "early phases" of the compiler: initial `cfg` processing,
B
Brian Anderson 已提交
151
/// loading compiler plugins (including those from `addl_plugins`),
152 153 154
/// 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.
155 156
///
/// Returns `None` if we're aborting after handling -W help.
E
Eduard Burtescu 已提交
157
pub fn phase_2_configure_and_expand(sess: &Session,
158
                                    mut krate: ast::Crate,
159 160
                                    crate_name: &str,
                                    addl_plugins: Option<Plugins>)
161
                                    -> Option<ast::Crate> {
162
    let time_passes = sess.time_passes();
H
Haitao Li 已提交
163

164 165
    *sess.crate_types.borrow_mut() =
        collect_crate_types(sess, krate.attrs.as_slice());
166 167
    *sess.crate_metadata.borrow_mut() =
        collect_crate_metadata(sess, krate.attrs.as_slice());
168

N
Nick Cameron 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
    time(time_passes, "gated feature checking", (), |_| {
        let (features, unknown_features) =
            syntax::feature_gate::check_crate(&sess.parse_sess.span_diagnostic, &krate);

        for uf in unknown_features.iter() {
            sess.add_lint(lint::builtin::UNKNOWN_FEATURES,
                          ast::CRATE_NODE_ID,
                          *uf,
                          "unknown feature".to_string());
        }

        sess.abort_if_errors();
        *sess.features.borrow_mut() = features;
    });
B
Brian Anderson 已提交
183

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

188 189 190 191 192 193 194
    // strip before expansion to allow macros to depend on
    // configuration variables e.g/ in
    //
    //   #[macro_escape] #[cfg(foo)]
    //   mod bar { macro_rules! baz!(() => {{}}) }
    //
    // baz! should not use this definition unless foo is enabled.
195

196
    krate = time(time_passes, "configuration 1", krate, |krate|
197
                 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
198

199 200
    krate = time(time_passes, "crate injection", krate, |krate|
                 syntax::std_inject::maybe_inject_crates_ref(krate,
A
Aaron Turon 已提交
201
                                                             sess.opts.alt_std_name.clone()));
202

203
    let mut addl_plugins = Some(addl_plugins);
204 205
    let Plugins { macros, registrars }
        = time(time_passes, "plugin loading", (), |_|
206
               plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
207 208 209 210

    let mut registry = Registry::new(&krate);

    time(time_passes, "plugin registration", (), |_| {
N
Nick Cameron 已提交
211
        if sess.features.borrow().rustc_diagnostic_macros {
212 213 214 215 216 217 218 219
            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);
        }

220 221
        for &registrar in registrars.iter() {
            registrar(&mut registry);
222
        }
223
    });
224

225
    let Registry { syntax_exts, lint_passes, lint_groups, .. } = registry;
226

K
Keegan McAllister 已提交
227 228
    {
        let mut ls = sess.lint_store.borrow_mut();
A
Aaron Turon 已提交
229
        for pass in lint_passes.into_iter() {
K
Keegan McAllister 已提交
230 231
            ls.register_pass(Some(sess), true, pass);
        }
232

A
Aaron Turon 已提交
233
        for (name, to) in lint_groups.into_iter() {
234 235
            ls.register_group(Some(sess), true, name, to);
        }
K
Keegan McAllister 已提交
236 237 238
    }

    // Lint plugins are registered; now we can process command line flags.
239
    if sess.opts.describe_lints {
K
Keegan McAllister 已提交
240
        super::describe_lints(&*sess.lint_store.borrow(), true);
241 242 243 244 245 246 247
        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();

248 249 250 251 252 253 254
    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.
255
            let mut _old_path = String::new();
256
            if cfg!(windows) {
257 258
                _old_path = os::getenv("PATH").unwrap_or(_old_path);
                let mut new_path = sess.host_filesearch().get_dylib_search_paths();
259
                new_path.extend(os::split_paths(_old_path.as_slice()).into_iter());
260
                os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
261 262
            }
            let cfg = syntax::ext::expand::ExpansionConfig {
263
                crate_name: crate_name.to_string(),
264 265
                deriving_hash_type_parameter: sess.features.borrow().default_type_params,
                enable_quotes: sess.features.borrow().quote,
266
                recursion_limit: sess.recursion_limit.get(),
267
            };
268
            let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
269 270 271
                                              cfg,
                                              macros,
                                              syntax_exts,
272 273 274 275 276
                                              krate);
            if cfg!(windows) {
                os::setenv("PATH", _old_path);
            }
            ret
277 278 279
        }
    );

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

282
    // strip again, in case expansion added anything with a #[cfg].
283
    krate = time(time_passes, "configuration 2", krate, |krate|
284
                 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
285

286
    krate = time(time_passes, "maybe building test harness", krate, |krate|
N
Nick Cameron 已提交
287 288 289 290
                 syntax::test::modify_for_testing(&sess.parse_sess,
                                                  &sess.opts.cfg,
                                                  krate,
                                                  sess.diagnostic()));
291

292
    krate = time(time_passes, "prelude injection", krate, |krate|
N
Nick Cameron 已提交
293
                 syntax::std_inject::maybe_inject_prelude(krate));
B
Brian Anderson 已提交
294

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
         syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));

    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 }));
317

N
Nick Cameron 已提交
318
    if sess.opts.debugging_opts & config::AST_JSON != 0 {
319
        let mut stdout = io::BufferedWriter::new(io::stdout());
320
        let mut json = json::PrettyEncoder::new(&mut stdout);
S
Sean McArthur 已提交
321
        // unwrapping so IoError isn't ignored
322
        map.krate().encode(&mut json).unwrap();
323 324
    }

325
    map
326
}
327

328 329 330
/// Run the resolution, typechecking, region checking and other
/// miscellaneous analysis passes on the crate. Return various
/// structures carrying the results of the analysis.
331
pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
332
                                         ast_map: ast_map::Map<'tcx>,
333
                                         type_arena: &'tcx TypedArena<ty::TyS<'tcx>>,
334
                                         name: String) -> ty::CrateAnalysis<'tcx> {
335
    let time_passes = sess.time_passes();
336
    let krate = ast_map.krate();
337

338
    time(time_passes, "external crate/lib resolution", (), |_|
339
         creader::read_crates(&sess, krate));
B
Brian Anderson 已提交
340

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

344
    let middle::resolve::CrateMap {
345 346 347
        def_map,
        freevars,
        capture_mode_map,
348
        export_map,
349 350 351
        trait_map,
        external_exports,
        last_private_map
352
    } =
353
        time(time_passes, "resolution", (), |_|
E
Eduard Burtescu 已提交
354
             middle::resolve::resolve_crate(&sess, &lang_items, krate));
B
Brian Anderson 已提交
355

356 357 358
    // Discard MTWT tables that aren't required past resolution.
    syntax::ext::mtwt::clear_tables();

359
    let named_region_map = time(time_passes, "lifetime resolution", (),
360
                                |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
361

362
    time(time_passes, "looking for entry point", (),
363
         |_| middle::entry::find_entry_point(&sess, &ast_map));
B
Brian Anderson 已提交
364

365 366 367
    sess.plugin_registrar_fn.set(
        time(time_passes, "looking for plugin registrar", (), |_|
            plugin::build::find_plugin_registrar(
368
                sess.diagnostic(), krate)));
369

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

373 374 375
    time(time_passes, "loop checking", (), |_|
         middle::check_loop::check_crate(&sess, krate));

A
Aaron Turon 已提交
376 377 378
    let stability_index = time(time_passes, "stability index", (), |_|
                               stability::Index::build(krate));

379 380 381
    time(time_passes, "static item recursion checking", (), |_|
         middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));

382
    let ty_cx = ty::mk_ctxt(sess,
383
                            type_arena,
384 385 386 387
                            def_map,
                            named_region_map,
                            ast_map,
                            freevars,
388
                            capture_mode_map,
389 390 391
                            region_map,
                            lang_items,
                            stability_index);
392

393
    // passes are timed inside typeck
394
    typeck::check_crate(&ty_cx, trait_map);
B
Brian Anderson 已提交
395

396
    time(time_passes, "check static items", (), |_|
397
         middle::check_static::check_crate(&ty_cx));
398

399
    // These next two const passes can probably be merged
400
    time(time_passes, "const marking", (), |_|
401
         middle::const_eval::process_crate(&ty_cx));
B
Brian Anderson 已提交
402

403
    time(time_passes, "const checking", (), |_|
404
         middle::check_const::check_crate(&ty_cx));
B
Brian Anderson 已提交
405

406
    let maps = (external_exports, last_private_map);
A
Alex Crichton 已提交
407 408
    let (exported_items, public_items) =
            time(time_passes, "privacy checking", maps, |(a, b)|
409
                 middle::privacy::check_crate(&ty_cx, &export_map, a, b));
B
Brian Anderson 已提交
410

411
    time(time_passes, "intrinsic checking", (), |_|
412
         middle::intrinsicck::check_crate(&ty_cx));
413

414
    time(time_passes, "effect checking", (), |_|
415
         middle::effect::check_crate(&ty_cx));
416

417
    time(time_passes, "match checking", (), |_|
418
         middle::check_match::check_crate(&ty_cx));
419

420
    time(time_passes, "liveness checking", (), |_|
421
         middle::liveness::check_crate(&ty_cx));
422

423
    time(time_passes, "borrow checking", (), |_|
424
         borrowck::check_crate(&ty_cx));
425

N
Nick Cameron 已提交
426 427 428
    time(time_passes, "rvalue checking", (), |_|
         middle::check_rvalues::check_crate(&ty_cx, krate));

429 430 431 432 433 434
    // 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
    ty_cx.sess.abort_if_errors();
J
James Miller 已提交
435

436
    let reachable_map =
437
        time(time_passes, "reachability checking", (), |_|
438
             reachable::find_reachable(&ty_cx, &exported_items));
J
James Miller 已提交
439

E
Eduard Burtescu 已提交
440 441 442
    time(time_passes, "death checking", (), |_| {
        middle::dead::check_crate(&ty_cx,
                                  &exported_items,
443
                                  &reachable_map)
E
Eduard Burtescu 已提交
444
    });
K
Kiet Tran 已提交
445

446
    time(time_passes, "lint checking", (), |_|
447
         lint::check_crate(&ty_cx, &exported_items));
448

449
    ty::CrateAnalysis {
450
        export_map: export_map,
451
        ty_cx: ty_cx,
452
        exported_items: exported_items,
A
Alex Crichton 已提交
453
        public_items: public_items,
454
        reachable: reachable_map,
455
        name: name,
456 457
    }
}
J
James Miller 已提交
458

459 460
pub fn phase_save_analysis(sess: &Session,
                           krate: &ast::Crate,
461
                           analysis: &ty::CrateAnalysis,
462 463 464 465 466
                           odir: &Option<Path>) {
    if (sess.opts.debugging_opts & config::SAVE_ANALYSIS) == 0 {
        return;
    }
    time(sess.time_passes(), "save analysis", krate, |krate|
467
         save::process_crate(sess, krate, analysis, odir));
468 469
}

470 471
/// Run the translation phase to LLVM, after which the AST and analysis can
/// be discarded.
472 473
pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
                                       -> (ty::ctxt<'tcx>, trans::CrateTranslation) {
474
    let time_passes = analysis.ty_cx.sess.time_passes();
475 476 477 478 479

    time(time_passes, "resolving dependency formats", (), |_|
         dependency_format::calculate(&analysis.ty_cx));

    // Option dance to work around the lack of stack once closures.
480
    time(time_passes, "translation", analysis, |analysis|
481
         trans::trans_crate(analysis))
482 483 484 485
}

/// Run LLVM itself, producing a bitcode file, assembly file or object file
/// as a side effect.
E
Eduard Burtescu 已提交
486
pub fn phase_5_run_llvm_passes(sess: &Session,
487
                               trans: &trans::CrateTranslation,
488
                               outputs: &OutputFilenames) {
489
    if sess.opts.cg.no_integrated_as {
490
        let output_type = config::OutputTypeAssembly;
491

492
        time(sess.time_passes(), "LLVM passes", (), |_|
N
Nick Cameron 已提交
493
            write::run_passes(sess, trans, &[output_type], outputs));
494

495
        write::run_assembler(sess, outputs);
V
Vadim Chugunov 已提交
496

497
        // Remove assembly source, unless --save-temps was specified
498
        if !sess.opts.cg.save_temps {
499
            fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
V
Vadim Chugunov 已提交
500
        }
501
    } else {
502
        time(sess.time_passes(), "LLVM passes", (), |_|
503 504 505 506
            write::run_passes(sess,
                              trans,
                              sess.opts.output_types.as_slice(),
                              outputs));
507
    }
508 509

    sess.abort_if_errors();
510
}
H
Haitao Li 已提交
511

512 513
/// Run the linker on any artifacts that resulted from the LLVM run.
/// This should produce either a finished executable or library.
E
Eduard Burtescu 已提交
514
pub fn phase_6_link_output(sess: &Session,
515
                           trans: &trans::CrateTranslation,
516
                           outputs: &OutputFilenames) {
517
    let old_path = os::getenv("PATH").unwrap_or_else(||String::new());
V
Vadim Chugunov 已提交
518 519
    let mut new_path = sess.host_filesearch().get_tools_search_paths();
    new_path.extend(os::split_paths(old_path.as_slice()).into_iter());
520 521
    os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());

522
    time(sess.time_passes(), "linking", (), |_|
523
         link::link_binary(sess,
524
                           trans,
A
Alex Crichton 已提交
525
                           outputs,
526
                           trans.link.crate_name.as_slice()));
527 528

    os::setenv("PATH", old_path);
529 530
}

E
Eduard Burtescu 已提交
531
pub fn stop_after_phase_3(sess: &Session) -> bool {
532 533 534 535 536 537 538
   if sess.opts.no_trans {
        debug!("invoked with --no-trans, returning early from compile_input");
        return true;
    }
    return false;
}

E
Eduard Burtescu 已提交
539
pub fn stop_after_phase_1(sess: &Session) -> bool {
540 541 542 543
    if sess.opts.parse_only {
        debug!("invoked with --parse-only, returning early from compile_input");
        return true;
    }
544 545 546
    if sess.show_span() {
        return true;
    }
N
Nick Cameron 已提交
547
    return sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0;
548 549
}

E
Eduard Burtescu 已提交
550
pub fn stop_after_phase_2(sess: &Session) -> bool {
551 552 553 554
    if sess.opts.no_analysis {
        debug!("invoked with --no-analysis, returning early from compile_input");
        return true;
    }
N
Nick Cameron 已提交
555
    return sess.opts.debugging_opts & config::AST_JSON != 0;
556 557
}

E
Eduard Burtescu 已提交
558
pub fn stop_after_phase_5(sess: &Session) -> bool {
559
    if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
560 561 562 563 564 565
        debug!("not building executable, returning early from compile_input");
        return true;
    }
    return false;
}

566 567 568 569 570 571
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 已提交
572
fn write_out_deps(sess: &Session,
A
Alex Crichton 已提交
573 574
                  input: &Input,
                  outputs: &OutputFilenames,
575
                  id: &str) {
576

577
    let mut out_filenames = Vec::new();
A
Alex Crichton 已提交
578 579 580
    for output_type in sess.opts.output_types.iter() {
        let file = outputs.path(*output_type);
        match *output_type {
581
            config::OutputTypeExe => {
582
                for output in sess.crate_types.borrow().iter() {
583 584
                    let p = link::filename_for_input(sess, *output,
                                                     id, &file);
A
Alex Crichton 已提交
585 586 587 588 589 590
                    out_filenames.push(p);
                }
            }
            _ => { out_filenames.push(file); }
        }
    }
591

A
Alex Crichton 已提交
592 593
    // Write out dependency rules to the dep-info file if requested with
    // --dep-info
594 595 596
    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 已提交
597 598
        // Use default filename: crate source filename with extension replaced
        // by ".d"
599
        (true, None) => match *input {
600 601
            Input::File(..) => outputs.with_extension("d"),
            Input::Str(..) => {
A
Alex Crichton 已提交
602 603
                sess.warn("can not write --dep-info without a filename \
                           when compiling stdin.");
604
                return
605 606
            },
        },
607
        _ => return,
608
    };
609

610
    let result = (|| -> io::IoResult<()> {
611 612
        // Build a list of files used to compile the output and
        // write Makefile-compatible dependency rules
613
        let files: Vec<String> = sess.codemap().files.borrow()
614
                                   .iter().filter(|fmap| fmap.is_real_file())
615
                                   .map(|fmap| escape_dep_filename(fmap.name.as_slice()))
616 617 618 619 620 621 622 623 624 625 626 627 628
                                   .collect();
        let mut file = try!(io::File::create(&deps_filename));
        for path in out_filenames.iter() {
            try!(write!(&mut file as &mut Writer,
                          "{}: {}\n\n", path.display(), files.connect(" ")));
        }
        Ok(())
    })();

    match result {
        Ok(()) => {}
        Err(e) => {
            sess.fatal(format!("error writing dependencies to `{}`: {}",
629
                               deps_filename.display(), e).as_slice());
630
        }
631
    }
632 633
}

N
Nick Cameron 已提交
634 635
pub fn collect_crate_types(session: &Session,
                           attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
636 637 638 639
    // 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() {
640
                Some(ref n) if *n == "rlib" => {
641 642
                    Some(config::CrateTypeRlib)
                }
643
                Some(ref n) if *n == "dylib" => {
644 645
                    Some(config::CrateTypeDylib)
                }
646
                Some(ref n) if *n == "lib" => {
647 648
                    Some(config::default_lib_output())
                }
649
                Some(ref n) if *n == "staticlib" => {
650 651
                    Some(config::CrateTypeStaticlib)
                }
652
                Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
653
                Some(_) => {
A
Aaron Turon 已提交
654
                    session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
655 656 657
                                     ast::CRATE_NODE_ID,
                                     a.span,
                                     "invalid `crate_type` \
658
                                      value".to_string());
659 660 661
                    None
                }
                _ => {
A
Aaron Turon 已提交
662
                    session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
663 664 665
                                     ast::CRATE_NODE_ID,
                                     a.span,
                                     "`crate_type` requires a \
666
                                      value".to_string());
667 668 669 670 671 672 673 674
                    None
                }
            }
        } else {
            None
        }
    }).collect();

N
Nick Cameron 已提交
675 676 677 678
    // 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 已提交
679
    }
H
Haitao Li 已提交
680

N
Nick Cameron 已提交
681 682 683 684
    // 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();
685
    if base.len() == 0 {
A
Aaron Turon 已提交
686
        base.extend(attr_types.into_iter());
N
Nick Cameron 已提交
687
        if base.len() == 0 {
688
            base.push(link::default_output_for_target(session));
689
        }
690
        base.sort();
N
Nick Cameron 已提交
691
        base.dedup();
692
    }
693

A
Aaron Turon 已提交
694
    base.into_iter().filter(|crate_type| {
695 696 697 698
        let res = !link::invalid_output_for_target(session, *crate_type);

        if !res {
            session.warn(format!("dropping unsupported crate type `{}` \
699 700
                                   for target `{}`",
                                 *crate_type, session.opts.target_triple).as_slice());
701 702 703 704
        }

        res
    }).collect()
H
Haitao Li 已提交
705 706
}

707 708 709 710 711
pub fn collect_crate_metadata(session: &Session,
                              _attrs: &[ast::Attribute]) -> Vec<String> {
    session.opts.cg.metadata.clone()
}

712
pub fn build_output_filenames(input: &Input,
713 714
                              odir: &Option<Path>,
                              ofile: &Option<Path>,
715
                              attrs: &[ast::Attribute],
E
Eduard Burtescu 已提交
716
                              sess: &Session)
A
Alex Crichton 已提交
717
                           -> OutputFilenames {
718
    match *ofile {
A
Alex Crichton 已提交
719 720 721 722 723 724
        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(),
725
                None => Path::new(".")
A
Alex Crichton 已提交
726 727
            };

728
            // If a crate name is present, we use it as the link name
729 730 731 732
            let stem = sess.opts.crate_name.clone().or_else(|| {
                attr::find_crate_name(attrs).map(|n| n.get().to_string())
            }).unwrap_or(input.filestem());

A
Alex Crichton 已提交
733 734 735 736
            OutputFilenames {
                out_directory: dirpath,
                out_filestem: stem,
                single_output_file: None,
737
                extra: sess.opts.cg.extra_filename.clone(),
A
Alex Crichton 已提交
738
            }
H
Haitao Li 已提交
739 740
        }

A
Alex Crichton 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753
        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.");
            }
            OutputFilenames {
                out_directory: out_file.dir_path(),
754
                out_filestem: out_file.filestem_str().unwrap().to_string(),
A
Alex Crichton 已提交
755
                single_output_file: ofile,
756
                extra: sess.opts.cg.extra_filename.clone(),
A
Alex Crichton 已提交
757
            }
H
Haitao Li 已提交
758
        }
759
    }
H
Haitao Li 已提交
760
}