driver.rs 53.2 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::dep_graph::DepGraph;
12
use rustc::hir::{self, map as hir_map};
13
use rustc::hir::lowering::lower_crate;
14
use rustc::ich::Fingerprint;
A
Ariel Ben-Yehuda 已提交
15
use rustc_data_structures::stable_hasher::StableHasher;
16
use rustc_mir as mir;
17
use rustc::session::{Session, CompileResult, CrateDisambiguator};
18
use rustc::session::CompileIncomplete;
19
use rustc::session::config::{self, Input, OutputFilenames, OutputType};
20
use rustc::session::search_paths::PathKind;
21
use rustc::lint;
22
use rustc::middle::{self, stability, reachable};
23
use rustc::middle::cstore::CrateStore;
24
use rustc::middle::privacy::AccessLevels;
25
use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
26
use rustc::traits;
27
use rustc::util::common::{ErrorReported, time};
28
use rustc_allocator as allocator;
29
use rustc_borrowck as borrowck;
30
use rustc_incremental;
31
use rustc_resolve::{MakeGlobMap, Resolver};
32
use rustc_metadata::creader::CrateLoader;
33
use rustc_metadata::cstore::{self, CStore};
34
use rustc_trans as trans;
35
use rustc_trans_utils::trans_crate::TransCrate;
N
Niko Matsakis 已提交
36
use rustc_typeck as typeck;
37
use rustc_privacy;
38 39
use rustc_plugin::registry::Registry;
use rustc_plugin as plugin;
40
use rustc_passes::{self, ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
41
use rustc_const_eval::{self, check_match};
N
Nick Cameron 已提交
42
use super::Compilation;
B
bjorn3 已提交
43
use ::DefaultTransCrate;
44

45
use serialize::json;
46

47
use std::any::Any;
A
Alex Crichton 已提交
48
use std::env;
49
use std::ffi::{OsString, OsStr};
A
Alex Crichton 已提交
50 51
use std::fs;
use std::io::{self, Write};
G
Guillaume Gomez 已提交
52
use std::iter;
A
Alex Crichton 已提交
53
use std::path::{Path, PathBuf};
54
use std::rc::Rc;
55
use std::sync::mpsc;
56
use syntax::{ast, diagnostics, visit};
57
use syntax::attr;
58
use syntax::ext::base::ExtCtxt;
59
use syntax::fold::Folder;
60
use syntax::parse::{self, PResult};
N
Nick Cameron 已提交
61
use syntax::util::node_count::NodeCounter;
62
use syntax;
63
use syntax_ext;
64
use arena::DroplessArena;
H
Haitao Li 已提交
65

66
use derive_registrar;
67
use pretty::ReplaceBodyWithLoop;
68

69 70
use profile;

71
pub fn compile_input(sess: &Session,
A
Ariel Ben-Yehuda 已提交
72
                     cstore: &CStore,
N
Nick Cameron 已提交
73
                     input: &Input,
A
Alex Crichton 已提交
74 75
                     outdir: &Option<PathBuf>,
                     output: &Option<PathBuf>,
76
                     addl_plugins: Option<Vec<String>>,
77
                     control: &CompileController) -> CompileResult {
B
bjorn3 已提交
78 79
    use rustc::session::config::CrateType;

80 81
    macro_rules! controller_entry_point {
        ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
82
            let state = &mut $make_state;
83 84 85 86
            let phase_result: &CompileResult = &$phase_result;
            if phase_result.is_ok() || control.$point.run_callback_on_error {
                (control.$point.callback)(state);
            }
87

88
            if control.$point.stop == Compilation::Stop {
89 90 91
                // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
                // if there are no errors?
                return $tsess.compile_status();
92 93 94
            }
        }}
    }
95

B
bjorn3 已提交
96
    if cfg!(not(feature="llvm")) {
97
        for cty in sess.opts.crate_types.iter() {
98
            match *cty {
99 100 101
                CrateType::CrateTypeRlib | CrateType::CrateTypeDylib |
                CrateType::CrateTypeExecutable => {},
                _ => {
102
                    sess.parse_sess.span_diagnostic.warn(
103
                        &format!("LLVM unsupported, so output type {} is not supported", cty)
104 105 106
                    );
                },
            }
B
bjorn3 已提交
107 108 109 110 111
        }

        sess.abort_if_errors();
    }

112
    if sess.profile_queries() {
113 114 115
        profile::begin();
    }

N
Nick Cameron 已提交
116 117 118
    // 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
B
bjorn3 已提交
119
    let (outputs, trans, dep_graph) = {
120
        let krate = match phase_1_parse_input(control, sess, input) {
121 122 123
            Ok(krate) => krate,
            Err(mut parse_error) => {
                parse_error.emit();
124
                return Err(CompileIncomplete::Errored(ErrorReported));
125 126
            }
        };
127

128
        let (krate, registry) = {
129 130 131 132 133 134
            let mut compile_state = CompileState::state_after_parse(input,
                                                                    sess,
                                                                    outdir,
                                                                    output,
                                                                    krate,
                                                                    &cstore);
135
            controller_entry_point!(after_parse,
136
                                    sess,
137
                                    compile_state,
138
                                    Ok(()));
139

140
            (compile_state.krate.unwrap(), compile_state.registry)
141
        };
142

143
        let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
144 145
        let crate_name =
            ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
146
        let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
147
            phase_2_configure_and_expand(
148 149 150 151 152 153 154
                sess,
                &cstore,
                krate,
                registry,
                &crate_name,
                addl_plugins,
                control.make_glob_map,
155 156
                |expanded_crate| {
                    let mut state = CompileState::state_after_expand(
N
Niko Matsakis 已提交
157
                        input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
158 159 160 161 162
                    );
                    controller_entry_point!(after_expand, sess, state, Ok(()));
                    Ok(())
                }
            )?
N
Nick Cameron 已提交
163
        };
164

N
Niko Matsakis 已提交
165
        write_out_deps(sess, &outputs, &crate_name);
166 167 168 169
        if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
            sess.opts.output_types.keys().count() == 1 {
            return Ok(())
        }
170

171 172
        let arena = DroplessArena::new();
        let arenas = GlobalArenas::new();
173 174 175 176

        // Construct the HIR map
        let hir_map = time(sess.time_passes(),
                           "indexing hir",
177
                           || hir_map::map_crate(sess, cstore, &mut hir_forest, &defs));
178

179 180
        {
            let _ignore = hir_map.dep_graph.in_ignore();
181
            controller_entry_point!(after_hir_lowering,
182
                                    sess,
183
                                    CompileState::state_after_hir_lowering(input,
184 185 186
                                                                  sess,
                                                                  outdir,
                                                                  output,
187
                                                                  &arena,
188 189 190 191 192 193 194
                                                                  &arenas,
                                                                  &cstore,
                                                                  &hir_map,
                                                                  &analysis,
                                                                  &resolutions,
                                                                  &expanded_crate,
                                                                  &hir_map.krate(),
A
Alex Crichton 已提交
195
                                                                  &outputs,
N
Niko Matsakis 已提交
196
                                                                  &crate_name),
197 198
                                    Ok(()));
        }
199

S
Seo Sanghyeon 已提交
200
        time(sess.time_passes(), "attribute checking", || {
201
            hir::check_attr::check_crate(sess, &expanded_crate);
S
Seo Sanghyeon 已提交
202 203
        });

204
        let opt_crate = if control.keep_ast {
J
Jonas Schievink 已提交
205 206 207 208 209 210
            Some(&expanded_crate)
        } else {
            drop(expanded_crate);
            None
        };

211 212
        phase_3_run_analysis_passes(control,
                                    sess,
213
                                    cstore,
J
Jorge Aparicio 已提交
214
                                    hir_map,
215 216
                                    analysis,
                                    resolutions,
217
                                    &arena,
J
Jorge Aparicio 已提交
218
                                    &arenas,
N
Niko Matsakis 已提交
219
                                    &crate_name,
A
Alex Crichton 已提交
220
                                    &outputs,
221
                                    |tcx, analysis, rx, result| {
222
            {
223 224 225
                // Eventually, we will want to track plugins.
                let _ignore = tcx.dep_graph.in_ignore();

226
                let mut state = CompileState::state_after_analysis(input,
227
                                                                   sess,
228
                                                                   outdir,
229
                                                                   output,
230
                                                                   opt_crate,
231
                                                                   tcx.hir.krate(),
232 233
                                                                   &analysis,
                                                                   tcx,
N
Niko Matsakis 已提交
234
                                                                   &crate_name);
235
                (control.after_analysis.callback)(&mut state);
236 237

                if control.after_analysis.stop == Compilation::Stop {
238
                    return result.and_then(|_| Err(CompileIncomplete::Stopped));
239 240
                }
            }
N
Nick Cameron 已提交
241

J
Jorge Aparicio 已提交
242
            result?;
243

A
Alex Crichton 已提交
244
            if log_enabled!(::log::LogLevel::Info) {
245 246 247
                println!("Pre-trans");
                tcx.print_debug_stats();
            }
248

B
bjorn3 已提交
249
            let trans = phase_4_translate_to_llvm::<DefaultTransCrate>(tcx, rx);
250

A
Alex Crichton 已提交
251
            if log_enabled!(::log::LogLevel::Info) {
252 253 254 255
                println!("Post-trans");
                tcx.print_debug_stats();
            }

J
Jake Goulding 已提交
256 257 258 259 260 261 262
            if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
                if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
                    sess.err(&format!("could not emit MIR: {}", e));
                    sess.abort_if_errors();
                }
            }

A
Alex Crichton 已提交
263
            Ok((outputs.clone(), trans, tcx.dep_graph.clone()))
J
Jorge Aparicio 已提交
264
        })??
N
Nick Cameron 已提交
265
    };
266

267 268
    if sess.opts.debugging_opts.print_type_sizes {
        sess.code_stats.borrow().print_type_sizes();
269 270
    }

B
bjorn3 已提交
271 272
    let (phase5_result, trans) =
        phase_5_run_llvm_passes::<DefaultTransCrate>(sess, &dep_graph, trans);
273

274 275 276 277 278
    controller_entry_point!(after_llvm,
                            sess,
                            CompileState::state_after_llvm(input, sess, outdir, output, &trans),
                            phase5_result);
    phase5_result?;
279

B
bjorn3 已提交
280 281 282 283 284
    // Run the linker on any artifacts that resulted from the LLVM run.
    // This should produce either a finished executable or library.
    time(sess.time_passes(), "linking", || {
        DefaultTransCrate::link_binary(sess, &trans, &outputs)
    });
285

286 287 288 289
    // Now that we won't touch anything in the incremental compilation directory
    // any more, we can finalize it (which involves renaming it)
    #[cfg(feature="llvm")]
    rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
290

291 292
    if sess.opts.debugging_opts.perf_stats {
        sess.print_perf_stats();
293
    }
294

295 296 297 298
    controller_entry_point!(
        compilation_done,
        sess,
        CompileState::state_when_compilation_done(input, sess, outdir, output),
299
        Ok(())
300 301
    );

302
    Ok(())
303
}
H
Haitao Li 已提交
304

J
Jeffrey Seyfried 已提交
305 306
fn keep_hygiene_data(sess: &Session) -> bool {
    sess.opts.debugging_opts.keep_hygiene_data
307 308 309
}


S
Steve Klabnik 已提交
310 311
/// The name used for source code that doesn't originate in a file
/// (e.g. source from stdin or a string)
312
pub fn anon_src() -> String {
313
    "<anon>".to_string()
P
Patrick Walton 已提交
314
}
315

316
pub fn source_name(input: &Input) -> String {
317
    match *input {
E
Eduard Burtescu 已提交
318
        // FIXME (#9639): This needs to handle non-utf8 paths
A
Alex Crichton 已提交
319
        Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
320
        Input::Str { ref name, .. } => name.clone(),
321 322 323
    }
}

F
Fourchaux 已提交
324
/// CompileController is used to customize compilation, it allows compilation to
325 326
/// 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 已提交
327
/// collected during compilation.
328 329 330 331
///
/// 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
332
/// compiler) is run between phases.
333 334 335 336 337 338 339
///
/// 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>,
340
    pub after_expand: PhaseController<'a>,
341
    pub after_hir_lowering: PhaseController<'a>,
342 343
    pub after_analysis: PhaseController<'a>,
    pub after_llvm: PhaseController<'a>,
344
    pub compilation_done: PhaseController<'a>,
345

346 347
    // FIXME we probably want to group the below options together and offer a
    // better API, rather than this ad-hoc approach.
348
    pub make_glob_map: MakeGlobMap,
349 350
    // Whether the compiler should keep the ast beyond parsing.
    pub keep_ast: bool,
351 352
    // -Zcontinue-parse-after-error
    pub continue_parse_after_error: bool,
353 354 355 356 357 358 359

    /// Allows overriding default rustc query providers,
    /// after `default_provide` has installed them.
    pub provide: Box<Fn(&mut ty::maps::Providers) + 'a>,
    /// Same as `provide`, but only for non-local crates,
    /// applied after `default_provide_extern`.
    pub provide_extern: Box<Fn(&mut ty::maps::Providers) + 'a>,
360 361 362 363 364 365
}

impl<'a> CompileController<'a> {
    pub fn basic() -> CompileController<'a> {
        CompileController {
            after_parse: PhaseController::basic(),
366
            after_expand: PhaseController::basic(),
367
            after_hir_lowering: PhaseController::basic(),
368 369
            after_analysis: PhaseController::basic(),
            after_llvm: PhaseController::basic(),
370
            compilation_done: PhaseController::basic(),
371
            make_glob_map: MakeGlobMap::No,
372
            keep_ast: false,
373
            continue_parse_after_error: false,
374 375
            provide: box |_| {},
            provide_extern: box |_| {},
376 377 378 379 380
        }
    }
}

pub struct PhaseController<'a> {
N
Nick Cameron 已提交
381
    pub stop: Compilation,
382 383 384
    // If true then the compiler will try to run the callback even if the phase
    // ends with an error. Note that this is not always possible.
    pub run_callback_on_error: bool,
385
    pub callback: Box<Fn(&mut CompileState) + 'a>,
386 387 388 389 390
}

impl<'a> PhaseController<'a> {
    pub fn basic() -> PhaseController<'a> {
        PhaseController {
N
Nick Cameron 已提交
391
            stop: Compilation::Continue,
392
            run_callback_on_error: false,
393
            callback: box |_| {},
394 395 396 397 398 399 400
        }
    }
}

/// 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.
401
pub struct CompileState<'a, 'tcx: 'a> {
402
    pub input: &'a Input,
403
    pub session: &'tcx Session,
404
    pub krate: Option<ast::Crate>,
405
    pub registry: Option<Registry<'a>>,
406
    pub cstore: Option<&'tcx CStore>,
407 408 409
    pub crate_name: Option<&'a str>,
    pub output_filenames: Option<&'a OutputFilenames>,
    pub out_dir: Option<&'a Path>,
410
    pub out_file: Option<&'a Path>,
411 412
    pub arena: Option<&'tcx DroplessArena>,
    pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
413
    pub expanded_crate: Option<&'a ast::Crate>,
414
    pub hir_crate: Option<&'a hir::Crate>,
415
    pub hir_map: Option<&'a hir_map::Map<'tcx>>,
J
Jeffrey Seyfried 已提交
416
    pub resolutions: Option<&'a Resolutions>,
417
    pub analysis: Option<&'a ty::CrateAnalysis>,
418
    pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
419 420 421
    pub trans: Option<&'a trans::CrateTranslation>,
}

422
impl<'a, 'tcx> CompileState<'a, 'tcx> {
423
    fn empty(input: &'a Input,
424
             session: &'tcx Session,
A
Alex Crichton 已提交
425
             out_dir: &'a Option<PathBuf>)
426
             -> Self {
427
        CompileState {
428 429
            input,
            session,
A
Alex Crichton 已提交
430
            out_dir: out_dir.as_ref().map(|s| &**s),
431
            out_file: None,
432
            arena: None,
433
            arenas: None,
434
            krate: None,
435
            registry: None,
436
            cstore: None,
437 438 439
            crate_name: None,
            output_filenames: None,
            expanded_crate: None,
440
            hir_crate: None,
441
            hir_map: None,
J
Jeffrey Seyfried 已提交
442
            resolutions: None,
443 444 445 446 447 448 449
            analysis: None,
            tcx: None,
            trans: None,
        }
    }

    fn state_after_parse(input: &'a Input,
450
                         session: &'tcx Session,
A
Alex Crichton 已提交
451
                         out_dir: &'a Option<PathBuf>,
452 453
                         out_file: &'a Option<PathBuf>,
                         krate: ast::Crate,
454
                         cstore: &'tcx CStore)
455
                         -> Self {
456
        CompileState {
457 458
            // Initialize the registry before moving `krate`
            registry: Some(Registry::new(&session, krate.span)),
459 460 461 462 463
            krate: Some(krate),
            cstore: Some(cstore),
            out_file: out_file.as_ref().map(|s| &**s),
            ..CompileState::empty(input, session, out_dir)
        }
464 465
    }

466
    fn state_after_expand(input: &'a Input,
467
                          session: &'tcx Session,
468 469
                          out_dir: &'a Option<PathBuf>,
                          out_file: &'a Option<PathBuf>,
470
                          cstore: &'tcx CStore,
471 472
                          expanded_crate: &'a ast::Crate,
                          crate_name: &'a str)
473
                          -> Self {
474 475 476 477 478 479 480 481 482
        CompileState {
            crate_name: Some(crate_name),
            cstore: Some(cstore),
            expanded_crate: Some(expanded_crate),
            out_file: out_file.as_ref().map(|s| &**s),
            ..CompileState::empty(input, session, out_dir)
        }
    }

483
    fn state_after_hir_lowering(input: &'a Input,
484
                                session: &'tcx Session,
485 486
                                out_dir: &'a Option<PathBuf>,
                                out_file: &'a Option<PathBuf>,
487 488
                                arena: &'tcx DroplessArena,
                                arenas: &'tcx GlobalArenas<'tcx>,
489
                                cstore: &'tcx CStore,
490
                                hir_map: &'a hir_map::Map<'tcx>,
491
                                analysis: &'a ty::CrateAnalysis,
492 493 494
                                resolutions: &'a Resolutions,
                                krate: &'a ast::Crate,
                                hir_crate: &'a hir::Crate,
A
Alex Crichton 已提交
495
                                output_filenames: &'a OutputFilenames,
496
                                crate_name: &'a str)
497
                                -> Self {
498 499
        CompileState {
            crate_name: Some(crate_name),
500
            arena: Some(arena),
501 502
            arenas: Some(arenas),
            cstore: Some(cstore),
503
            hir_map: Some(hir_map),
J
Jeffrey Seyfried 已提交
504 505
            analysis: Some(analysis),
            resolutions: Some(resolutions),
506
            expanded_crate: Some(krate),
507
            hir_crate: Some(hir_crate),
A
Alex Crichton 已提交
508
            output_filenames: Some(output_filenames),
509
            out_file: out_file.as_ref().map(|s| &**s),
J
Jose Narvaez 已提交
510
            ..CompileState::empty(input, session, out_dir)
511 512 513
        }
    }

514
    fn state_after_analysis(input: &'a Input,
515
                            session: &'tcx Session,
A
Alex Crichton 已提交
516
                            out_dir: &'a Option<PathBuf>,
517
                            out_file: &'a Option<PathBuf>,
J
Jonas Schievink 已提交
518
                            krate: Option<&'a ast::Crate>,
519
                            hir_crate: &'a hir::Crate,
520
                            analysis: &'a ty::CrateAnalysis,
521
                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
522
                            crate_name: &'a str)
523
                            -> Self {
524 525 526
        CompileState {
            analysis: Some(analysis),
            tcx: Some(tcx),
527
            expanded_crate: krate,
528
            hir_crate: Some(hir_crate),
529
            crate_name: Some(crate_name),
530
            out_file: out_file.as_ref().map(|s| &**s),
J
Jose Narvaez 已提交
531
            ..CompileState::empty(input, session, out_dir)
532 533 534 535
        }
    }

    fn state_after_llvm(input: &'a Input,
536
                        session: &'tcx Session,
A
Alex Crichton 已提交
537
                        out_dir: &'a Option<PathBuf>,
538
                        out_file: &'a Option<PathBuf>,
539
                        trans: &'a trans::CrateTranslation)
540
                        -> Self {
541 542 543 544 545
        CompileState {
            trans: Some(trans),
            out_file: out_file.as_ref().map(|s| &**s),
            ..CompileState::empty(input, session, out_dir)
        }
546
    }
547

548
    fn state_when_compilation_done(input: &'a Input,
549 550 551 552
                                   session: &'tcx Session,
                                   out_dir: &'a Option<PathBuf>,
                                   out_file: &'a Option<PathBuf>)
                                   -> Self {
553 554 555 556 557
        CompileState {
            out_file: out_file.as_ref().map(|s| &**s),
            ..CompileState::empty(input, session, out_dir)
        }
    }
558 559
}

560 561 562 563 564
pub fn phase_1_parse_input<'a>(control: &CompileController,
                               sess: &'a Session,
                               input: &Input)
                               -> PResult<'a, ast::Crate> {
    sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
M
Murarth 已提交
565

566
    if sess.profile_queries() {
567 568 569
        profile::begin();
    }

J
Jorge Aparicio 已提交
570
    let krate = time(sess.time_passes(), "parsing", || {
571
        match *input {
572
            Input::File(ref file) => {
573
                parse::parse_crate_from_file(file, &sess.parse_sess)
574
            }
575
            Input::Str { ref input, ref name } => {
576
                parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
577 578
            }
        }
J
Jorge Aparicio 已提交
579
    })?;
580

581 582
    sess.diagnostic().set_continue_after_error(true);

583
    if sess.opts.debugging_opts.ast_json_noexpand {
584
        println!("{}", json::as_json(&krate));
585 586
    }

N
Nick Cameron 已提交
587 588 589 590 591
    if sess.opts.debugging_opts.input_stats {
        println!("Lines of code:             {}", sess.codemap().count_lines());
        println!("Pre-expansion node count:  {}", count_nodes(&krate));
    }

592
    if let Some(ref s) = sess.opts.debugging_opts.show_span {
593
        syntax::show_span::run(sess.diagnostic(), s, &krate);
594 595
    }

596 597 598 599
    if sess.opts.debugging_opts.hir_stats {
        hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
    }

600
    Ok(krate)
601
}
H
Haitao Li 已提交
602

N
Nick Cameron 已提交
603 604 605 606 607 608
fn count_nodes(krate: &ast::Crate) -> usize {
    let mut counter = NodeCounter::new();
    visit::walk_crate(&mut counter, krate);
    counter.count
}

609 610
// For continuing compilation after a parsed crate has been
// modified
611

612
pub struct ExpansionResult {
613 614
    pub expanded_crate: ast::Crate,
    pub defs: hir_map::Definitions,
615
    pub analysis: ty::CrateAnalysis,
616 617 618 619
    pub resolutions: Resolutions,
    pub hir_forest: hir_map::Forest,
}

620
/// Run the "early phases" of the compiler: initial `cfg` processing,
B
Brian Anderson 已提交
621
/// loading compiler plugins (including those from `addl_plugins`),
622
/// syntax expansion, secondary `cfg` expansion, synthesis of a test
623 624
/// harness if one is to be provided, injection of a dependency on the
/// standard library and prelude, and name resolution.
625 626
///
/// Returns `None` if we're aborting after handling -W help.
627 628 629 630 631 632 633 634
pub fn phase_2_configure_and_expand<F>(sess: &Session,
                                       cstore: &CStore,
                                       krate: ast::Crate,
                                       registry: Option<Registry>,
                                       crate_name: &str,
                                       addl_plugins: Option<Vec<String>>,
                                       make_glob_map: MakeGlobMap,
                                       after_expand: F)
635
                                       -> Result<ExpansionResult, CompileIncomplete>
636 637
    where F: FnOnce(&ast::Crate) -> CompileResult,
{
638
    let time_passes = sess.time_passes();
H
Haitao Li 已提交
639

640 641 642
    let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
    // these need to be set "early" so that expansion sees `quote` if enabled.
    *sess.features.borrow_mut() = features;
643

J
Jose Narvaez 已提交
644
    *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
645

646
    let disambiguator = compute_crate_disambiguator(sess);
647 648 649 650
    *sess.crate_disambiguator.borrow_mut() = Some(disambiguator);
    rustc_incremental::prepare_session_directory(
        sess,
        &crate_name,
651
        disambiguator,
652
    );
653 654

    let dep_graph = if sess.opts.build_dep_graph() {
655 656
        let prev_dep_graph = time(time_passes, "load prev dep-graph", || {
            rustc_incremental::load_dep_graph(sess)
657 658 659 660 661 662
        });

        DepGraph::new(prev_dep_graph)
    } else {
        DepGraph::new_disabled()
    };
663

664
    time(time_passes, "recursion limit", || {
665
        middle::recursion_limit::update_limits(sess, &krate);
666 667
    });

J
Jose Narvaez 已提交
668
    krate = time(time_passes, "crate injection", || {
669
        let alt_std_name = sess.opts.alt_std_name.clone();
670
        syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
J
Jose Narvaez 已提交
671
    });
672

673
    let mut addl_plugins = Some(addl_plugins);
J
Jose Narvaez 已提交
674
    let registrars = time(time_passes, "plugin loading", || {
675 676 677 678 679
        plugin::load::load_plugins(sess,
                                   &cstore,
                                   &krate,
                                   crate_name,
                                   addl_plugins.take().unwrap())
J
Jose Narvaez 已提交
680
    });
681

682
    let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
683

684
    time(time_passes, "plugin registration", || {
N
Nick Cameron 已提交
685
        if sess.features.borrow().rustc_diagnostic_macros {
686
            registry.register_macro("__diagnostic_used",
J
Jose Narvaez 已提交
687
                                    diagnostics::plugin::expand_diagnostic_used);
688
            registry.register_macro("__register_diagnostic",
J
Jose Narvaez 已提交
689
                                    diagnostics::plugin::expand_register_diagnostic);
690
            registry.register_macro("__build_diagnostic_array",
J
Jose Narvaez 已提交
691
                                    diagnostics::plugin::expand_build_diagnostic_array);
692 693
        }

694
        for registrar in registrars {
695 696
            registry.args_hidden = Some(registrar.args);
            (registrar.fun)(&mut registry);
697
        }
698
    });
699

700
    let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
N
Nick Cameron 已提交
701
    let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
702
                   llvm_passes, attributes, .. } = registry;
703

J
Jorge Aparicio 已提交
704
    sess.track_errors(|| {
K
Keegan McAllister 已提交
705
        let mut ls = sess.lint_store.borrow_mut();
N
Nick Cameron 已提交
706 707 708 709 710
        for pass in early_lint_passes {
            ls.register_early_pass(Some(sess), true, pass);
        }
        for pass in late_lint_passes {
            ls.register_late_pass(Some(sess), true, pass);
K
Keegan McAllister 已提交
711
        }
712

713
        for (name, to) in lint_groups {
714 715
            ls.register_group(Some(sess), true, name, to);
        }
716 717

        *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
718
        *sess.plugin_attributes.borrow_mut() = attributes.clone();
J
Jorge Aparicio 已提交
719
    })?;
K
Keegan McAllister 已提交
720 721

    // Lint plugins are registered; now we can process command line flags.
722
    if sess.opts.describe_lints {
723
        super::describe_lints(&sess.lint_store.borrow(), true);
724
        return Err(CompileIncomplete::Stopped);
725 726
    }

727 728 729 730 731
    // Currently, we ignore the name resolution data structures for the purposes of dependency
    // tracking. Instead we will run name resolution and include its output in the hash of each
    // item, much like we do for macro expansion. In other words, the hash reflects not just
    // its contents but the results of name resolution on those contents. Hopefully we'll push
    // this back at some point.
732
    let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
733
    let resolver_arenas = Resolver::arenas();
734
    let mut resolver = Resolver::new(sess,
735
                                     cstore,
736 737 738 739 740
                                     &krate,
                                     crate_name,
                                     make_glob_map,
                                     &mut crate_loader,
                                     &resolver_arenas);
741
    resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
742
    syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
743

744 745 746 747 748 749
    krate = time(time_passes, "expansion", || {
        // 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.
750 751 752 753 754 755 756 757 758
        //
        // This is somewhat of an inherently racy operation, however, as
        // multiple threads calling this function could possibly continue
        // extending PATH far beyond what it should. To solve this for now we
        // just don't add any new elements to PATH which are already there
        // within PATH. This is basically a targeted fix at #17360 for rustdoc
        // which runs rustc in parallel but has been seen (#33844) to cause
        // problems with PATH becoming too long.
        let mut old_path = OsString::new();
759
        if cfg!(windows) {
760
            old_path = env::var_os("PATH").unwrap_or(old_path);
761 762
            let mut new_path = sess.host_filesearch(PathKind::All)
                                   .get_dylib_search_paths();
763 764 765 766 767
            for path in env::split_paths(&old_path) {
                if !new_path.contains(&path) {
                    new_path.push(path);
                }
            }
G
Guillaume Gomez 已提交
768 769 770 771
            env::set_var("PATH",
                &env::join_paths(new_path.iter()
                                         .filter(|p| env::join_paths(iter::once(p)).is_ok()))
                     .unwrap());
772
        }
773 774 775 776 777
        let features = sess.features.borrow();
        let cfg = syntax::ext::expand::ExpansionConfig {
            features: Some(&features),
            recursion_limit: sess.recursion_limit.get(),
            trace_mac: sess.opts.debugging_opts.trace_macros,
778
            should_test: sess.opts.test,
779
            ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
780
        };
781

782
        let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
783 784 785 786
        let err_count = ecx.parse_sess.span_diagnostic.err_count();

        let krate = ecx.monotonic_expander().expand_crate(krate);

E
est31 已提交
787 788
        ecx.check_unused_macros();

J
Jeffrey Seyfried 已提交
789 790 791 792 793
        let mut missing_fragment_specifiers: Vec<_> =
            ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
        missing_fragment_specifiers.sort();
        for span in missing_fragment_specifiers {
            let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
794 795
            let msg = "missing fragment specifier";
            sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
J
Jeffrey Seyfried 已提交
796
        }
797 798 799
        if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
            ecx.parse_sess.span_diagnostic.abort_if_errors();
        }
800
        if cfg!(windows) {
801
            env::set_var("PATH", &old_path);
802
        }
803
        krate
804
    });
805

J
Jose Narvaez 已提交
806
    krate = time(time_passes, "maybe building test harness", || {
807
        syntax::test::modify_for_testing(&sess.parse_sess,
808
                                         &mut resolver,
809 810 811
                                         sess.opts.test,
                                         krate,
                                         sess.diagnostic())
J
Jose Narvaez 已提交
812
    });
813

814 815 816 817 818 819
    // If we're actually rustdoc then there's no need to actually compile
    // anything, so switch everything to just looping
    if sess.opts.actually_rustdoc {
        krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
    }

820 821 822 823 824 825 826
    // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
    // bunch of checks in the `modify` function below. For now just skip this
    // step entirely if we're rustdoc as it's not too useful anyway.
    if !sess.opts.actually_rustdoc {
        krate = time(time_passes, "maybe creating a macro crate", || {
            let crate_types = sess.crate_types.borrow();
            let num_crate_types = crate_types.len();
827
            let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
828
            let is_test_crate = sess.opts.test;
829 830 831 832
            syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
                                                     &mut resolver,
                                                     krate,
                                                     is_proc_macro_crate,
833
                                                     is_test_crate,
834
                                                     num_crate_types,
835
                                                     sess.diagnostic())
836 837
        });
    }
838

839 840 841 842 843 844 845
    krate = time(time_passes, "creating allocators", || {
        allocator::expand::modify(&sess.parse_sess,
                                  &mut resolver,
                                  krate,
                                  sess.diagnostic())
    });

846 847
    after_expand(&krate)?;

848 849 850 851
    if sess.opts.debugging_opts.input_stats {
        println!("Post-expansion node count: {}", count_nodes(&krate));
    }

852 853 854 855
    if sess.opts.debugging_opts.hir_stats {
        hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
    }

856 857 858 859
    if sess.opts.debugging_opts.ast_json {
        println!("{}", json::as_json(&krate));
    }

J
Jose Narvaez 已提交
860 861
    time(time_passes,
         "checking for inline asm in case the target doesn't support it",
862
         || no_asm::check_crate(sess, &krate));
863

K
king6cong 已提交
864
    time(time_passes,
865 866 867
         "AST validation",
         || ast_validation::check_crate(sess, &krate));

K
king6cong 已提交
868
    time(time_passes, "name resolution", || -> CompileResult {
869
        resolver.resolve_crate(&krate);
870 871
        Ok(())
    })?;
872

873 874 875 876
    if resolver.found_unresolved_macro {
        sess.parse_sess.span_diagnostic.abort_if_errors();
    }

877 878 879 880 881 882 883 884 885 886 887
    // Needs to go *after* expansion to be able to check the results of macro expansion.
    time(time_passes, "complete gated feature checking", || {
        sess.track_errors(|| {
            syntax::feature_gate::check_crate(&krate,
                                              &sess.parse_sess,
                                              &sess.features.borrow(),
                                              &attributes,
                                              sess.opts.unstable_features);
        })
    })?;

888
    // Lower ast -> hir.
K
king6cong 已提交
889
    let hir_forest = time(time_passes, "lowering ast -> hir", || {
890
        let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
891 892 893 894 895

        if sess.opts.debugging_opts.hir_stats {
            hir_stats::print_hir_stats(&hir_crate);
        }

896
        hir_map::Forest::new(hir_crate, &dep_graph)
897
    });
898

899 900 901 902
    time(time_passes,
         "early lint checks",
         || lint::check_ast_crate(sess, &krate));

K
king6cong 已提交
903
    // Discard hygiene data, which isn't required after lowering to HIR.
J
Jeffrey Seyfried 已提交
904
    if !keep_hygiene_data(sess) {
905
        syntax::ext::hygiene::clear_markings();
906 907 908 909
    }

    Ok(ExpansionResult {
        expanded_crate: krate,
910 911
        defs: resolver.definitions,
        analysis: ty::CrateAnalysis {
912
            access_levels: Rc::new(AccessLevels::default()),
913
            name: crate_name.to_string(),
914 915 916 917
            glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
        },
        resolutions: Resolutions {
            freevars: resolver.freevars,
N
Niko Matsakis 已提交
918
            export_map: resolver.export_map,
919 920
            trait_map: resolver.trait_map,
            maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
921
            maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
922
        },
923
        hir_forest,
924
    })
925 926
}

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
pub fn default_provide(providers: &mut ty::maps::Providers) {
    borrowck::provide(providers);
    mir::provide(providers);
    reachable::provide(providers);
    rustc_privacy::provide(providers);
    DefaultTransCrate::provide(providers);
    typeck::provide(providers);
    ty::provide(providers);
    traits::provide(providers);
    reachable::provide(providers);
    rustc_const_eval::provide(providers);
    rustc_passes::provide(providers);
    middle::region::provide(providers);
    cstore::provide(providers);
    lint::provide(providers);
}

pub fn default_provide_extern(providers: &mut ty::maps::Providers) {
    cstore::provide_extern(providers);
    DefaultTransCrate::provide_extern(providers);
}

949 950 951
/// Run the resolution, typechecking, region checking and other
/// miscellaneous analysis passes on the crate. Return various
/// structures carrying the results of the analysis.
952 953
pub fn phase_3_run_analysis_passes<'tcx, F, R>(control: &CompileController,
                                               sess: &'tcx Session,
954
                                               cstore: &'tcx CrateStore,
J
Jonas Schievink 已提交
955
                                               hir_map: hir_map::Map<'tcx>,
956
                                               mut analysis: ty::CrateAnalysis,
957
                                               resolutions: Resolutions,
958 959
                                               arena: &'tcx DroplessArena,
                                               arenas: &'tcx GlobalArenas<'tcx>,
960
                                               name: &str,
A
Alex Crichton 已提交
961
                                               output_filenames: &OutputFilenames,
962
                                               f: F)
963
                                               -> Result<R, CompileIncomplete>
964
    where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
965
                            ty::CrateAnalysis,
966
                            mpsc::Receiver<Box<Any + Send>>,
967
                            CompileResult) -> R
968
{
969
    macro_rules! try_with_f {
A
Alex Crichton 已提交
970
        ($e: expr, ($($t:tt)*)) => {
971 972 973
            match $e {
                Ok(x) => x,
                Err(x) => {
A
Alex Crichton 已提交
974
                    f($($t)*, Err(x));
975 976 977 978 979 980
                    return Err(x);
                }
            }
        }
    }

981
    let time_passes = sess.time_passes();
982

983 984 985 986
    let query_result_on_disk_cache = time(time_passes,
        "load query result cache",
        || rustc_incremental::load_query_result_cache(sess));

J
Jorge Aparicio 已提交
987
    let named_region_map = time(time_passes,
J
Jorge Aparicio 已提交
988
                                "lifetime resolution",
989
                                || middle::resolve_lifetime::krate(sess, cstore, &hir_map))?;
990

J
Jose Narvaez 已提交
991 992
    time(time_passes,
         "looking for entry point",
J
Jonas Schievink 已提交
993
         || middle::entry::find_entry_point(sess, &hir_map));
B
Brian Anderson 已提交
994

J
Jose Narvaez 已提交
995
    sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
996
        plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
J
Jose Narvaez 已提交
997
    }));
998
    sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
999

J
Jose Narvaez 已提交
1000 1001
    time(time_passes,
         "loop checking",
1002
         || loops::check_crate(sess, &hir_map));
1003

J
Jorge Aparicio 已提交
1004
    time(time_passes,
N
Nick Cameron 已提交
1005
              "static item recursion checking",
1006
              || static_recursion::check_crate(sess, &hir_map))?;
1007

1008
    let mut local_providers = ty::maps::Providers::default();
1009 1010
    default_provide(&mut local_providers);
    (control.provide)(&mut local_providers);
1011

1012
    let mut extern_providers = local_providers;
1013 1014
    default_provide_extern(&mut extern_providers);
    (control.provide_extern)(&mut extern_providers);
1015

1016 1017
    let (tx, rx) = mpsc::channel();

1018
    TyCtxt::create_and_enter(sess,
1019
                             cstore,
1020 1021
                             local_providers,
                             extern_providers,
1022
                             arenas,
1023
                             arena,
1024
                             resolutions,
1025 1026
                             named_region_map,
                             hir_map,
1027
                             query_result_on_disk_cache,
1028
                             name,
1029
                             tx,
A
Alex Crichton 已提交
1030
                             output_filenames,
1031
                             |tcx| {
1032 1033 1034
        // Do some initialization of the DepGraph that can only be done with the
        // tcx available.
        rustc_incremental::dep_graph_tcx_init(tcx);
1035

1036 1037 1038 1039
        time(time_passes,
             "stability checking",
             || stability::check_unstable_api_usage(tcx));

1040
        // passes are timed inside typeck
1041
        try_with_f!(typeck::check_crate(tcx), (tcx, analysis, rx));
1042 1043 1044

        time(time_passes,
             "const checking",
N
Nick Cameron 已提交
1045
             || consts::check_crate(tcx));
1046

1047
        analysis.access_levels =
1048
            time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1049 1050 1051 1052 1053 1054 1055

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

        time(time_passes,
             "match checking",
1056
             || check_match::check_crate(tcx));
1057

1058 1059 1060 1061 1062 1063 1064 1065
        // this must run before MIR dump, because
        // "not all control paths return a value" is reported here.
        //
        // maybe move the check to a MIR pass?
        time(time_passes,
             "liveness checking",
             || middle::liveness::check_crate(tcx));

1066 1067
        time(time_passes,
             "borrow checking",
1068
             || borrowck::check_crate(tcx));
1069

1070 1071
        time(time_passes,
             "MIR borrow checking",
1072
             || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id); });
1073

A
Ariel Ben-Yehuda 已提交
1074 1075 1076 1077 1078
        time(time_passes,
             "MIR effect checking",
             || for def_id in tcx.body_owners() {
                 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
             });
1079 1080 1081 1082 1083 1084
        // 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
1085
        if sess.err_count() > 0 {
1086
            return Ok(f(tcx, analysis, rx, sess.compile_status()));
1087
        }
1088

1089
        time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1090 1091

        time(time_passes, "unused lib feature checking", || {
1092
            stability::check_unused_or_stable_features(tcx)
1093 1094
        });

1095
        time(time_passes, "lint checking", || lint::check_crate(tcx));
1096

1097
        return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1098
    })
1099
}
J
James Miller 已提交
1100

1101
/// Run the translation phase to LLVM, after which the AST and analysis can
1102
/// be discarded.
B
bjorn3 已提交
1103
pub fn phase_4_translate_to_llvm<'a, 'tcx, Trans: TransCrate>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
A
Alex Crichton 已提交
1104
                                           rx: mpsc::Receiver<Box<Any + Send>>)
B
bjorn3 已提交
1105
                                           -> <Trans as TransCrate>::OngoingCrateTranslation {
1106
    let time_passes = tcx.sess.time_passes();
1107

J
Jose Narvaez 已提交
1108 1109
    time(time_passes,
         "resolving dependency formats",
B
bjorn3 已提交
1110
         || ::rustc::middle::dependency_format::calculate(tcx));
1111

N
Niko Matsakis 已提交
1112
    let translation =
1113
        time(time_passes, "translation", move || {
B
bjorn3 已提交
1114
            Trans::trans_crate(tcx, rx)
1115
        });
1116
    if tcx.sess.profile_queries() {
1117 1118 1119
        profile::dump("profile_queries".to_string())
    }

N
Niko Matsakis 已提交
1120
    translation
1121 1122 1123 1124
}

/// Run LLVM itself, producing a bitcode file, assembly file or object file
/// as a side effect.
B
bjorn3 已提交
1125
pub fn phase_5_run_llvm_passes<Trans: TransCrate>(sess: &Session,
1126
                               dep_graph: &DepGraph,
B
bjorn3 已提交
1127 1128 1129
                               trans: <Trans as TransCrate>::OngoingCrateTranslation)
                               -> (CompileResult, <Trans as TransCrate>::TranslatedCrate) {
    let trans = Trans::join_trans(trans, sess, dep_graph);
J
Jorge Aparicio 已提交
1130

1131
    if sess.opts.debugging_opts.incremental_info {
B
bjorn3 已提交
1132
        Trans::dump_incremental_data(&trans);
1133
    }
1134

1135 1136
    time(sess.time_passes(),
         "serialize work products",
1137
         move || rustc_incremental::save_work_products(sess, dep_graph));
1138

1139
    (sess.compile_status(), trans)
1140
}
H
Haitao Li 已提交
1141

1142 1143 1144
fn escape_dep_filename(filename: &str) -> String {
    // Apparently clang and gcc *only* escape spaces:
    // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
J
Jose Narvaez 已提交
1145
    filename.replace(" ", "\\ ")
1146 1147
}

N
Niko Matsakis 已提交
1148
fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1149
    let mut out_filenames = Vec::new();
1150
    for output_type in sess.opts.output_types.keys() {
A
Alex Crichton 已提交
1151 1152
        let file = outputs.path(*output_type);
        match *output_type {
1153
            OutputType::Exe => {
1154
                for output in sess.crate_types.borrow().iter() {
1155 1156 1157 1158 1159 1160
                    let p = ::rustc_trans_utils::link::filename_for_input(
                        sess,
                        *output,
                        crate_name,
                        outputs
                    );
A
Alex Crichton 已提交
1161 1162 1163
                    out_filenames.push(p);
                }
            }
J
Jose Narvaez 已提交
1164 1165 1166
            _ => {
                out_filenames.push(file);
            }
A
Alex Crichton 已提交
1167 1168
        }
    }
1169

1170 1171
    // Write out dependency rules to the dep-info file if requested
    if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
J
Jose Narvaez 已提交
1172
        return;
1173 1174
    }
    let deps_filename = outputs.path(OutputType::DepInfo);
1175

J
Jose Narvaez 已提交
1176 1177 1178 1179 1180
    let result =
        (|| -> io::Result<()> {
            // Build a list of files used to compile the output and
            // write Makefile-compatible dependency rules
            let files: Vec<String> = sess.codemap()
1181
                                         .files()
J
Jose Narvaez 已提交
1182 1183 1184 1185 1186
                                         .iter()
                                         .filter(|fmap| fmap.is_real_file())
                                         .filter(|fmap| !fmap.is_imported())
                                         .map(|fmap| escape_dep_filename(&fmap.name))
                                         .collect();
J
Jorge Aparicio 已提交
1187
            let mut file = fs::File::create(&deps_filename)?;
J
Jose Narvaez 已提交
1188
            for path in &out_filenames {
J
Jorge Aparicio 已提交
1189
                write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
J
Jose Narvaez 已提交
1190
            }
1191

J
Jose Narvaez 已提交
1192 1193 1194 1195
            // Emit a fake target for each input file to the compilation. This
            // prevents `make` from spitting out an error if a file is later
            // deleted. For more info see #28735
            for path in files {
J
Jorge Aparicio 已提交
1196
                writeln!(file, "{}:", path)?;
J
Jose Narvaez 已提交
1197 1198 1199
            }
            Ok(())
        })();
1200 1201 1202 1203

    match result {
        Ok(()) => {}
        Err(e) => {
J
Jorge Aparicio 已提交
1204
            sess.fatal(&format!("error writing dependencies to `{}`: {}",
J
Jose Narvaez 已提交
1205 1206
                                deps_filename.display(),
                                e));
1207
        }
1208
    }
1209 1210
}

J
Jose Narvaez 已提交
1211
pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1212
    // Unconditionally collect crate types from attributes to make them used
J
Jose Narvaez 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    let attr_types: Vec<config::CrateType> =
        attrs.iter()
             .filter_map(|a| {
                 if a.check_name("crate_type") {
                     match a.value_str() {
                         Some(ref n) if *n == "rlib" => {
                             Some(config::CrateTypeRlib)
                         }
                         Some(ref n) if *n == "dylib" => {
                             Some(config::CrateTypeDylib)
                         }
1224 1225 1226
                         Some(ref n) if *n == "cdylib" => {
                             Some(config::CrateTypeCdylib)
                         }
J
Jose Narvaez 已提交
1227 1228 1229 1230 1231 1232
                         Some(ref n) if *n == "lib" => {
                             Some(config::default_lib_output())
                         }
                         Some(ref n) if *n == "staticlib" => {
                             Some(config::CrateTypeStaticlib)
                         }
1233 1234
                         Some(ref n) if *n == "proc-macro" => {
                             Some(config::CrateTypeProcMacro)
1235
                         }
J
Jose Narvaez 已提交
1236 1237
                         Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
                         Some(_) => {
1238 1239 1240 1241
                             session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
                                                 ast::CRATE_NODE_ID,
                                                 a.span,
                                                 "invalid `crate_type` value");
J
Jose Narvaez 已提交
1242 1243 1244
                             None
                         }
                         _ => {
N
Nick Cameron 已提交
1245 1246 1247
                             session.struct_span_err(a.span, "`crate_type` requires a value")
                                 .note("for example: `#![crate_type=\"lib\"]`")
                                 .emit();
J
Jose Narvaez 已提交
1248 1249 1250 1251 1252 1253 1254 1255
                             None
                         }
                     }
                 } else {
                     None
                 }
             })
             .collect();
1256

N
Nick Cameron 已提交
1257 1258 1259
    // If we're generating a test executable, then ignore all other output
    // styles at all other locations
    if session.opts.test {
J
Jose Narvaez 已提交
1260
        return vec![config::CrateTypeExecutable];
S
Steven Stewart-Gallus 已提交
1261
    }
H
Haitao Li 已提交
1262

N
Nick Cameron 已提交
1263 1264 1265 1266
    // 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();
1267
    if base.is_empty() {
1268
        base.extend(attr_types);
1269
        if base.is_empty() {
1270
            base.push(::rustc_trans_utils::link::default_output_for_target(session));
1271
        }
1272
        base.sort();
N
Nick Cameron 已提交
1273
        base.dedup();
1274
    }
1275

J
Jose Narvaez 已提交
1276 1277
    base.into_iter()
        .filter(|crate_type| {
1278
            let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1279

J
Jose Narvaez 已提交
1280 1281 1282 1283 1284
            if !res {
                session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
                                      *crate_type,
                                      session.opts.target_triple));
            }
1285

J
Jose Narvaez 已提交
1286 1287 1288
            res
        })
        .collect()
H
Haitao Li 已提交
1289 1290
}

1291
pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1292 1293
    use std::hash::Hasher;

1294 1295 1296 1297
    // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
    // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
    // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
    // should still be safe enough to avoid collisions in practice.
A
Ariel Ben-Yehuda 已提交
1298
    let mut hasher = StableHasher::<Fingerprint>::new();
1299 1300 1301 1302 1303 1304 1305 1306

    let mut metadata = session.opts.cg.metadata.clone();
    // We don't want the crate_disambiguator to dependent on the order
    // -C metadata arguments, so sort them:
    metadata.sort();
    // Every distinct -C metadata value is only incorporated once:
    metadata.dedup();

1307
    hasher.write(b"metadata");
1308 1309 1310 1311
    for s in &metadata {
        // Also incorporate the length of a metadata string, so that we generate
        // different values for `-Cmetadata=ab -Cmetadata=c` and
        // `-Cmetadata=a -Cmetadata=bc`
1312 1313
        hasher.write_usize(s.len());
        hasher.write(s.as_bytes());
1314 1315
    }

1316 1317
    // Also incorporate crate type, so that we don't get symbol conflicts when
    // linking against a library of the same name, if this is an executable.
1318
    let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1319 1320
    hasher.write(if is_exe { b"exe" } else { b"lib" });

1321
    CrateDisambiguator::from(hasher.finish())
1322

1323 1324
}

1325
pub fn build_output_filenames(input: &Input,
A
Alex Crichton 已提交
1326 1327
                              odir: &Option<PathBuf>,
                              ofile: &Option<PathBuf>,
1328
                              attrs: &[ast::Attribute],
E
Eduard Burtescu 已提交
1329
                              sess: &Session)
J
Jose Narvaez 已提交
1330
                              -> OutputFilenames {
1331
    match *ofile {
A
Alex Crichton 已提交
1332 1333 1334 1335 1336 1337
        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(),
J
Jose Narvaez 已提交
1338
                None => PathBuf::new(),
A
Alex Crichton 已提交
1339 1340
            };

1341
            // If a crate name is present, we use it as the link name
J
Jose Narvaez 已提交
1342 1343 1344 1345 1346
            let stem = sess.opts
                           .crate_name
                           .clone()
                           .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
                           .unwrap_or(input.filestem());
1347

A
Alex Crichton 已提交
1348 1349 1350 1351
            OutputFilenames {
                out_directory: dirpath,
                out_filestem: stem,
                single_output_file: None,
1352
                extra: sess.opts.cg.extra_filename.clone(),
1353
                outputs: sess.opts.output_types.clone(),
A
Alex Crichton 已提交
1354
            }
H
Haitao Li 已提交
1355 1356
        }

A
Alex Crichton 已提交
1357
        Some(ref out_file) => {
J
Jose Narvaez 已提交
1358 1359 1360
            let unnamed_output_types = sess.opts
                                           .output_types
                                           .values()
1361 1362
                                           .filter(|a| a.is_none())
                                           .count();
1363 1364 1365
            let ofile = if unnamed_output_types > 1 {
                sess.warn("due to multiple output types requested, the explicitly specified \
                           output file name will be adapted for each output type");
A
Alex Crichton 已提交
1366 1367 1368 1369 1370 1371 1372
                None
            } else {
                Some(out_file.clone())
            };
            if *odir != None {
                sess.warn("ignoring --out-dir flag due to -o flag.");
            }
1373 1374 1375

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

A
Alex Crichton 已提交
1376
            OutputFilenames {
1377
                out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
J
Jose Narvaez 已提交
1378 1379 1380 1381 1382
                out_filestem: out_file.file_stem()
                                      .unwrap_or(OsStr::new(""))
                                      .to_str()
                                      .unwrap()
                                      .to_string(),
A
Alex Crichton 已提交
1383
                single_output_file: ofile,
1384
                extra: sess.opts.cg.extra_filename.clone(),
1385
                outputs: sess.opts.output_types.clone(),
A
Alex Crichton 已提交
1386
            }
H
Haitao Li 已提交
1387
        }
1388
    }
H
Haitao Li 已提交
1389
}