]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/driver.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[rust.git] / src / librustc_driver / driver.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![cfg_attr(not(feature="llvm"), allow(dead_code))]
12
13 use rustc::hir::{self, map as hir_map};
14 use rustc::hir::lowering::lower_crate;
15 use rustc::ich::Fingerprint;
16 use rustc_data_structures::stable_hasher::StableHasher;
17 use rustc_mir as mir;
18 use rustc::session::{Session, CompileResult};
19 use rustc::session::CompileIncomplete;
20 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
21 use rustc::session::search_paths::PathKind;
22 use rustc::lint;
23 use rustc::middle::{self, stability, reachable};
24 use rustc::middle::privacy::AccessLevels;
25 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
26 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
27 use rustc::traits;
28 use rustc::util::common::{ErrorReported, time};
29 use rustc::util::nodemap::NodeSet;
30 use rustc_allocator as allocator;
31 use rustc_borrowck as borrowck;
32 use rustc_incremental::{self, IncrementalHashesMap};
33 use rustc_resolve::{MakeGlobMap, Resolver};
34 use rustc_metadata::creader::CrateLoader;
35 use rustc_metadata::cstore::{self, CStore};
36 use rustc_trans::back::write;
37 use rustc_trans as trans;
38 use rustc_typeck as typeck;
39 use rustc_privacy;
40 use rustc_plugin::registry::Registry;
41 use rustc_plugin as plugin;
42 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
43 use rustc_const_eval::{self, check_match};
44 use super::Compilation;
45
46 use serialize::json;
47
48 use std::env;
49 use std::ffi::{OsString, OsStr};
50 use std::fs;
51 use std::io::{self, Write};
52 use std::iter;
53 use std::path::{Path, PathBuf};
54 use std::rc::Rc;
55 use syntax::{ast, diagnostics, visit};
56 use syntax::attr;
57 use syntax::ext::base::ExtCtxt;
58 use syntax::parse::{self, PResult};
59 use syntax::symbol::Symbol;
60 use syntax::util::node_count::NodeCounter;
61 use syntax;
62 use syntax_ext;
63 use arena::DroplessArena;
64
65 use derive_registrar;
66
67 pub fn compile_input(sess: &Session,
68                      cstore: &CStore,
69                      input: &Input,
70                      outdir: &Option<PathBuf>,
71                      output: &Option<PathBuf>,
72                      addl_plugins: Option<Vec<String>>,
73                      control: &CompileController) -> CompileResult {
74     use rustc_trans::back::write::OngoingCrateTranslation;
75     macro_rules! controller_entry_point {
76         ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
77             let state = &mut $make_state;
78             let phase_result: &CompileResult = &$phase_result;
79             if phase_result.is_ok() || control.$point.run_callback_on_error {
80                 (control.$point.callback)(state);
81             }
82
83             if control.$point.stop == Compilation::Stop {
84                 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
85                 // if there are no errors?
86                 return $tsess.compile_status();
87             }
88         }}
89     }
90
91     if cfg!(not(feature="llvm")) {
92         use rustc::session::config::CrateType;
93         if !sess.opts.debugging_opts.no_trans && sess.opts.output_types.should_trans() {
94             sess.err("LLVM is not supported by this rustc. Please use -Z no-trans to compile")
95         }
96
97         if sess.opts.crate_types.iter().all(|&t|{
98             t != CrateType::CrateTypeRlib && t != CrateType::CrateTypeExecutable
99         }) && !sess.opts.crate_types.is_empty() {
100             sess.err(
101                 "LLVM is not supported by this rustc, so non rlib libraries are not supported"
102             );
103         }
104
105         sess.abort_if_errors();
106     }
107
108     // We need nested scopes here, because the intermediate results can keep
109     // large chunks of memory alive and we want to free them as soon as
110     // possible to keep the peak memory usage low
111     let (outputs, trans): (OutputFilenames, OngoingCrateTranslation) = {
112         let krate = match phase_1_parse_input(control, sess, input) {
113             Ok(krate) => krate,
114             Err(mut parse_error) => {
115                 parse_error.emit();
116                 return Err(CompileIncomplete::Errored(ErrorReported));
117             }
118         };
119
120         let (krate, registry) = {
121             let mut compile_state = CompileState::state_after_parse(input,
122                                                                     sess,
123                                                                     outdir,
124                                                                     output,
125                                                                     krate,
126                                                                     &cstore);
127             controller_entry_point!(after_parse,
128                                     sess,
129                                     compile_state,
130                                     Ok(()));
131
132             (compile_state.krate.unwrap(), compile_state.registry)
133         };
134
135         let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
136         let crate_name =
137             ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
138         let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
139             phase_2_configure_and_expand(
140                 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
141                 |expanded_crate| {
142                     let mut state = CompileState::state_after_expand(
143                         input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
144                     );
145                     controller_entry_point!(after_expand, sess, state, Ok(()));
146                     Ok(())
147                 }
148             )?
149         };
150
151         write_out_deps(sess, &outputs, &crate_name);
152         if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
153             sess.opts.output_types.keys().count() == 1 {
154             return Ok(())
155         }
156
157         let arena = DroplessArena::new();
158         let arenas = GlobalArenas::new();
159
160         // Construct the HIR map
161         let hir_map = time(sess.time_passes(),
162                            "indexing hir",
163                            || hir_map::map_crate(&mut hir_forest, defs));
164
165         {
166             let _ignore = hir_map.dep_graph.in_ignore();
167             controller_entry_point!(after_hir_lowering,
168                                     sess,
169                                     CompileState::state_after_hir_lowering(input,
170                                                                   sess,
171                                                                   outdir,
172                                                                   output,
173                                                                   &arena,
174                                                                   &arenas,
175                                                                   &cstore,
176                                                                   &hir_map,
177                                                                   &analysis,
178                                                                   &resolutions,
179                                                                   &expanded_crate,
180                                                                   &hir_map.krate(),
181                                                                   &crate_name),
182                                     Ok(()));
183         }
184
185         time(sess.time_passes(), "attribute checking", || {
186             hir::check_attr::check_crate(sess, &expanded_crate);
187         });
188
189         let opt_crate = if control.keep_ast {
190             Some(&expanded_crate)
191         } else {
192             drop(expanded_crate);
193             None
194         };
195
196         phase_3_run_analysis_passes(sess,
197                                     hir_map,
198                                     analysis,
199                                     resolutions,
200                                     &arena,
201                                     &arenas,
202                                     &crate_name,
203                                     |tcx, analysis, incremental_hashes_map, result| {
204             {
205                 // Eventually, we will want to track plugins.
206                 let _ignore = tcx.dep_graph.in_ignore();
207
208                 let mut state = CompileState::state_after_analysis(input,
209                                                                    sess,
210                                                                    outdir,
211                                                                    output,
212                                                                    opt_crate,
213                                                                    tcx.hir.krate(),
214                                                                    &analysis,
215                                                                    tcx,
216                                                                    &crate_name);
217                 (control.after_analysis.callback)(&mut state);
218
219                 if control.after_analysis.stop == Compilation::Stop {
220                     return result.and_then(|_| Err(CompileIncomplete::Stopped));
221                 }
222             }
223
224             result?;
225
226             if log_enabled!(::log::LogLevel::Info) {
227                 println!("Pre-trans");
228                 tcx.print_debug_stats();
229             }
230
231             let trans = phase_4_translate_to_llvm(tcx, analysis, incremental_hashes_map,
232                                                   &outputs);
233
234             if log_enabled!(::log::LogLevel::Info) {
235                 println!("Post-trans");
236                 tcx.print_debug_stats();
237             }
238
239             if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
240                 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
241                     sess.err(&format!("could not emit MIR: {}", e));
242                     sess.abort_if_errors();
243                 }
244             }
245
246             Ok((outputs, trans))
247         })??
248     };
249
250     if cfg!(not(feature="llvm")) {
251         let (_, _) = (outputs, trans);
252         sess.fatal("LLVM is not supported by this rustc");
253     }
254
255     #[cfg(feature="llvm")]
256     {
257         if sess.opts.debugging_opts.print_type_sizes {
258             sess.code_stats.borrow().print_type_sizes();
259         }
260
261         let (phase5_result, trans) = phase_5_run_llvm_passes(sess, trans);
262
263         controller_entry_point!(after_llvm,
264                                 sess,
265                                 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
266                                 phase5_result);
267         phase5_result?;
268
269         phase_6_link_output(sess, &trans, &outputs);
270
271         // Now that we won't touch anything in the incremental compilation directory
272         // any more, we can finalize it (which involves renaming it)
273         rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
274
275         if sess.opts.debugging_opts.perf_stats {
276             sess.print_perf_stats();
277         }
278
279         controller_entry_point!(
280             compilation_done,
281             sess,
282             CompileState::state_when_compilation_done(input, sess, outdir, output),
283             Ok(())
284         );
285
286         Ok(())
287     }
288 }
289
290 fn keep_hygiene_data(sess: &Session) -> bool {
291     sess.opts.debugging_opts.keep_hygiene_data
292 }
293
294
295 /// The name used for source code that doesn't originate in a file
296 /// (e.g. source from stdin or a string)
297 pub fn anon_src() -> String {
298     "<anon>".to_string()
299 }
300
301 pub fn source_name(input: &Input) -> String {
302     match *input {
303         // FIXME (#9639): This needs to handle non-utf8 paths
304         Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
305         Input::Str { ref name, .. } => name.clone(),
306     }
307 }
308
309 /// CompileController is used to customise compilation, it allows compilation to
310 /// be stopped and/or to call arbitrary code at various points in compilation.
311 /// It also allows for various flags to be set to influence what information gets
312 /// collected during compilation.
313 ///
314 /// This is a somewhat higher level controller than a Session - the Session
315 /// controls what happens in each phase, whereas the CompileController controls
316 /// whether a phase is run at all and whether other code (from outside the
317 /// compiler) is run between phases.
318 ///
319 /// Note that if compilation is set to stop and a callback is provided for a
320 /// given entry point, the callback is called before compilation is stopped.
321 ///
322 /// Expect more entry points to be added in the future.
323 pub struct CompileController<'a> {
324     pub after_parse: PhaseController<'a>,
325     pub after_expand: PhaseController<'a>,
326     pub after_hir_lowering: PhaseController<'a>,
327     pub after_analysis: PhaseController<'a>,
328     pub after_llvm: PhaseController<'a>,
329     pub compilation_done: PhaseController<'a>,
330
331     // FIXME we probably want to group the below options together and offer a
332     // better API, rather than this ad-hoc approach.
333     pub make_glob_map: MakeGlobMap,
334     // Whether the compiler should keep the ast beyond parsing.
335     pub keep_ast: bool,
336     // -Zcontinue-parse-after-error
337     pub continue_parse_after_error: bool,
338 }
339
340 impl<'a> CompileController<'a> {
341     pub fn basic() -> CompileController<'a> {
342         CompileController {
343             after_parse: PhaseController::basic(),
344             after_expand: PhaseController::basic(),
345             after_hir_lowering: PhaseController::basic(),
346             after_analysis: PhaseController::basic(),
347             after_llvm: PhaseController::basic(),
348             compilation_done: PhaseController::basic(),
349             make_glob_map: MakeGlobMap::No,
350             keep_ast: false,
351             continue_parse_after_error: false,
352         }
353     }
354 }
355
356 pub struct PhaseController<'a> {
357     pub stop: Compilation,
358     // If true then the compiler will try to run the callback even if the phase
359     // ends with an error. Note that this is not always possible.
360     pub run_callback_on_error: bool,
361     pub callback: Box<Fn(&mut CompileState) + 'a>,
362 }
363
364 impl<'a> PhaseController<'a> {
365     pub fn basic() -> PhaseController<'a> {
366         PhaseController {
367             stop: Compilation::Continue,
368             run_callback_on_error: false,
369             callback: box |_| {},
370         }
371     }
372 }
373
374 /// State that is passed to a callback. What state is available depends on when
375 /// during compilation the callback is made. See the various constructor methods
376 /// (`state_*`) in the impl to see which data is provided for any given entry point.
377 pub struct CompileState<'a, 'tcx: 'a> {
378     pub input: &'a Input,
379     pub session: &'tcx Session,
380     pub krate: Option<ast::Crate>,
381     pub registry: Option<Registry<'a>>,
382     pub cstore: Option<&'a CStore>,
383     pub crate_name: Option<&'a str>,
384     pub output_filenames: Option<&'a OutputFilenames>,
385     pub out_dir: Option<&'a Path>,
386     pub out_file: Option<&'a Path>,
387     pub arena: Option<&'tcx DroplessArena>,
388     pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
389     pub expanded_crate: Option<&'a ast::Crate>,
390     pub hir_crate: Option<&'a hir::Crate>,
391     pub hir_map: Option<&'a hir_map::Map<'tcx>>,
392     pub resolutions: Option<&'a Resolutions>,
393     pub analysis: Option<&'a ty::CrateAnalysis>,
394     pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
395     pub trans: Option<&'a trans::CrateTranslation>,
396 }
397
398 impl<'a, 'tcx> CompileState<'a, 'tcx> {
399     fn empty(input: &'a Input,
400              session: &'tcx Session,
401              out_dir: &'a Option<PathBuf>)
402              -> Self {
403         CompileState {
404             input: input,
405             session: session,
406             out_dir: out_dir.as_ref().map(|s| &**s),
407             out_file: None,
408             arena: None,
409             arenas: None,
410             krate: None,
411             registry: None,
412             cstore: None,
413             crate_name: None,
414             output_filenames: None,
415             expanded_crate: None,
416             hir_crate: None,
417             hir_map: None,
418             resolutions: None,
419             analysis: None,
420             tcx: None,
421             trans: None,
422         }
423     }
424
425     fn state_after_parse(input: &'a Input,
426                          session: &'tcx Session,
427                          out_dir: &'a Option<PathBuf>,
428                          out_file: &'a Option<PathBuf>,
429                          krate: ast::Crate,
430                          cstore: &'a CStore)
431                          -> Self {
432         CompileState {
433             // Initialize the registry before moving `krate`
434             registry: Some(Registry::new(&session, krate.span)),
435             krate: Some(krate),
436             cstore: Some(cstore),
437             out_file: out_file.as_ref().map(|s| &**s),
438             ..CompileState::empty(input, session, out_dir)
439         }
440     }
441
442     fn state_after_expand(input: &'a Input,
443                           session: &'tcx Session,
444                           out_dir: &'a Option<PathBuf>,
445                           out_file: &'a Option<PathBuf>,
446                           cstore: &'a CStore,
447                           expanded_crate: &'a ast::Crate,
448                           crate_name: &'a str)
449                           -> Self {
450         CompileState {
451             crate_name: Some(crate_name),
452             cstore: Some(cstore),
453             expanded_crate: Some(expanded_crate),
454             out_file: out_file.as_ref().map(|s| &**s),
455             ..CompileState::empty(input, session, out_dir)
456         }
457     }
458
459     fn state_after_hir_lowering(input: &'a Input,
460                                 session: &'tcx Session,
461                                 out_dir: &'a Option<PathBuf>,
462                                 out_file: &'a Option<PathBuf>,
463                                 arena: &'tcx DroplessArena,
464                                 arenas: &'tcx GlobalArenas<'tcx>,
465                                 cstore: &'a CStore,
466                                 hir_map: &'a hir_map::Map<'tcx>,
467                                 analysis: &'a ty::CrateAnalysis,
468                                 resolutions: &'a Resolutions,
469                                 krate: &'a ast::Crate,
470                                 hir_crate: &'a hir::Crate,
471                                 crate_name: &'a str)
472                                 -> Self {
473         CompileState {
474             crate_name: Some(crate_name),
475             arena: Some(arena),
476             arenas: Some(arenas),
477             cstore: Some(cstore),
478             hir_map: Some(hir_map),
479             analysis: Some(analysis),
480             resolutions: Some(resolutions),
481             expanded_crate: Some(krate),
482             hir_crate: Some(hir_crate),
483             out_file: out_file.as_ref().map(|s| &**s),
484             ..CompileState::empty(input, session, out_dir)
485         }
486     }
487
488     fn state_after_analysis(input: &'a Input,
489                             session: &'tcx Session,
490                             out_dir: &'a Option<PathBuf>,
491                             out_file: &'a Option<PathBuf>,
492                             krate: Option<&'a ast::Crate>,
493                             hir_crate: &'a hir::Crate,
494                             analysis: &'a ty::CrateAnalysis,
495                             tcx: TyCtxt<'a, 'tcx, 'tcx>,
496                             crate_name: &'a str)
497                             -> Self {
498         CompileState {
499             analysis: Some(analysis),
500             tcx: Some(tcx),
501             expanded_crate: krate,
502             hir_crate: Some(hir_crate),
503             crate_name: Some(crate_name),
504             out_file: out_file.as_ref().map(|s| &**s),
505             ..CompileState::empty(input, session, out_dir)
506         }
507     }
508
509     fn state_after_llvm(input: &'a Input,
510                         session: &'tcx Session,
511                         out_dir: &'a Option<PathBuf>,
512                         out_file: &'a Option<PathBuf>,
513                         trans: &'a trans::CrateTranslation)
514                         -> Self {
515         CompileState {
516             trans: Some(trans),
517             out_file: out_file.as_ref().map(|s| &**s),
518             ..CompileState::empty(input, session, out_dir)
519         }
520     }
521
522     fn state_when_compilation_done(input: &'a Input,
523                                    session: &'tcx Session,
524                                    out_dir: &'a Option<PathBuf>,
525                                    out_file: &'a Option<PathBuf>)
526                                    -> Self {
527         CompileState {
528             out_file: out_file.as_ref().map(|s| &**s),
529             ..CompileState::empty(input, session, out_dir)
530         }
531     }
532 }
533
534 pub fn phase_1_parse_input<'a>(control: &CompileController,
535                                sess: &'a Session,
536                                input: &Input)
537                                -> PResult<'a, ast::Crate> {
538     sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
539
540     let krate = time(sess.time_passes(), "parsing", || {
541         match *input {
542             Input::File(ref file) => {
543                 parse::parse_crate_from_file(file, &sess.parse_sess)
544             }
545             Input::Str { ref input, ref name } => {
546                 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
547             }
548         }
549     })?;
550
551     sess.diagnostic().set_continue_after_error(true);
552
553     if sess.opts.debugging_opts.ast_json_noexpand {
554         println!("{}", json::as_json(&krate));
555     }
556
557     if sess.opts.debugging_opts.input_stats {
558         println!("Lines of code:             {}", sess.codemap().count_lines());
559         println!("Pre-expansion node count:  {}", count_nodes(&krate));
560     }
561
562     if let Some(ref s) = sess.opts.debugging_opts.show_span {
563         syntax::show_span::run(sess.diagnostic(), s, &krate);
564     }
565
566     if sess.opts.debugging_opts.hir_stats {
567         hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
568     }
569
570     Ok(krate)
571 }
572
573 fn count_nodes(krate: &ast::Crate) -> usize {
574     let mut counter = NodeCounter::new();
575     visit::walk_crate(&mut counter, krate);
576     counter.count
577 }
578
579 // For continuing compilation after a parsed crate has been
580 // modified
581
582 pub struct ExpansionResult {
583     pub expanded_crate: ast::Crate,
584     pub defs: hir_map::Definitions,
585     pub analysis: ty::CrateAnalysis,
586     pub resolutions: Resolutions,
587     pub hir_forest: hir_map::Forest,
588 }
589
590 /// Run the "early phases" of the compiler: initial `cfg` processing,
591 /// loading compiler plugins (including those from `addl_plugins`),
592 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
593 /// harness if one is to be provided, injection of a dependency on the
594 /// standard library and prelude, and name resolution.
595 ///
596 /// Returns `None` if we're aborting after handling -W help.
597 pub fn phase_2_configure_and_expand<F>(sess: &Session,
598                                        cstore: &CStore,
599                                        krate: ast::Crate,
600                                        registry: Option<Registry>,
601                                        crate_name: &str,
602                                        addl_plugins: Option<Vec<String>>,
603                                        make_glob_map: MakeGlobMap,
604                                        after_expand: F)
605                                        -> Result<ExpansionResult, CompileIncomplete>
606     where F: FnOnce(&ast::Crate) -> CompileResult,
607 {
608     let time_passes = sess.time_passes();
609
610     let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
611     // these need to be set "early" so that expansion sees `quote` if enabled.
612     *sess.features.borrow_mut() = features;
613
614     *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
615     *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
616
617     time(time_passes, "recursion limit", || {
618         middle::recursion_limit::update_limits(sess, &krate);
619     });
620
621     krate = time(time_passes, "crate injection", || {
622         let alt_std_name = sess.opts.alt_std_name.clone();
623         syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
624     });
625
626     let mut addl_plugins = Some(addl_plugins);
627     let registrars = time(time_passes, "plugin loading", || {
628         plugin::load::load_plugins(sess,
629                                    &cstore,
630                                    &krate,
631                                    crate_name,
632                                    addl_plugins.take().unwrap())
633     });
634
635     let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
636
637     time(time_passes, "plugin registration", || {
638         if sess.features.borrow().rustc_diagnostic_macros {
639             registry.register_macro("__diagnostic_used",
640                                     diagnostics::plugin::expand_diagnostic_used);
641             registry.register_macro("__register_diagnostic",
642                                     diagnostics::plugin::expand_register_diagnostic);
643             registry.register_macro("__build_diagnostic_array",
644                                     diagnostics::plugin::expand_build_diagnostic_array);
645         }
646
647         for registrar in registrars {
648             registry.args_hidden = Some(registrar.args);
649             (registrar.fun)(&mut registry);
650         }
651     });
652
653     let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
654     let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
655                    llvm_passes, attributes, .. } = registry;
656
657     sess.track_errors(|| {
658         let mut ls = sess.lint_store.borrow_mut();
659         for pass in early_lint_passes {
660             ls.register_early_pass(Some(sess), true, pass);
661         }
662         for pass in late_lint_passes {
663             ls.register_late_pass(Some(sess), true, pass);
664         }
665
666         for (name, to) in lint_groups {
667             ls.register_group(Some(sess), true, name, to);
668         }
669
670         *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
671         *sess.plugin_attributes.borrow_mut() = attributes.clone();
672     })?;
673
674     // Lint plugins are registered; now we can process command line flags.
675     if sess.opts.describe_lints {
676         super::describe_lints(&sess.lint_store.borrow(), true);
677         return Err(CompileIncomplete::Stopped);
678     }
679
680     // Currently, we ignore the name resolution data structures for the purposes of dependency
681     // tracking. Instead we will run name resolution and include its output in the hash of each
682     // item, much like we do for macro expansion. In other words, the hash reflects not just
683     // its contents but the results of name resolution on those contents. Hopefully we'll push
684     // this back at some point.
685     let _ignore = sess.dep_graph.in_ignore();
686     let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
687     crate_loader.preprocess(&krate);
688     let resolver_arenas = Resolver::arenas();
689     let mut resolver = Resolver::new(sess,
690                                      &krate,
691                                      crate_name,
692                                      make_glob_map,
693                                      &mut crate_loader,
694                                      &resolver_arenas);
695     resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
696     syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
697
698     krate = time(time_passes, "expansion", || {
699         // Windows dlls do not have rpaths, so they don't know how to find their
700         // dependencies. It's up to us to tell the system where to find all the
701         // dependent dlls. Note that this uses cfg!(windows) as opposed to
702         // targ_cfg because syntax extensions are always loaded for the host
703         // compiler, not for the target.
704         //
705         // This is somewhat of an inherently racy operation, however, as
706         // multiple threads calling this function could possibly continue
707         // extending PATH far beyond what it should. To solve this for now we
708         // just don't add any new elements to PATH which are already there
709         // within PATH. This is basically a targeted fix at #17360 for rustdoc
710         // which runs rustc in parallel but has been seen (#33844) to cause
711         // problems with PATH becoming too long.
712         let mut old_path = OsString::new();
713         if cfg!(windows) {
714             old_path = env::var_os("PATH").unwrap_or(old_path);
715             let mut new_path = sess.host_filesearch(PathKind::All)
716                                    .get_dylib_search_paths();
717             for path in env::split_paths(&old_path) {
718                 if !new_path.contains(&path) {
719                     new_path.push(path);
720                 }
721             }
722             env::set_var("PATH",
723                 &env::join_paths(new_path.iter()
724                                          .filter(|p| env::join_paths(iter::once(p)).is_ok()))
725                      .unwrap());
726         }
727         let features = sess.features.borrow();
728         let cfg = syntax::ext::expand::ExpansionConfig {
729             features: Some(&features),
730             recursion_limit: sess.recursion_limit.get(),
731             trace_mac: sess.opts.debugging_opts.trace_macros,
732             should_test: sess.opts.test,
733             ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
734         };
735
736         let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
737         let err_count = ecx.parse_sess.span_diagnostic.err_count();
738
739         let krate = ecx.monotonic_expander().expand_crate(krate);
740
741         ecx.check_unused_macros();
742
743         let mut missing_fragment_specifiers: Vec<_> =
744             ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
745         missing_fragment_specifiers.sort();
746         for span in missing_fragment_specifiers {
747             let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
748             let msg = "missing fragment specifier";
749             sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
750         }
751         if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
752             ecx.parse_sess.span_diagnostic.abort_if_errors();
753         }
754         if cfg!(windows) {
755             env::set_var("PATH", &old_path);
756         }
757         krate
758     });
759
760     krate = time(time_passes, "maybe building test harness", || {
761         syntax::test::modify_for_testing(&sess.parse_sess,
762                                          &mut resolver,
763                                          sess.opts.test,
764                                          krate,
765                                          sess.diagnostic())
766     });
767
768     // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
769     // bunch of checks in the `modify` function below. For now just skip this
770     // step entirely if we're rustdoc as it's not too useful anyway.
771     if !sess.opts.actually_rustdoc {
772         krate = time(time_passes, "maybe creating a macro crate", || {
773             let crate_types = sess.crate_types.borrow();
774             let num_crate_types = crate_types.len();
775             let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
776             let is_test_crate = sess.opts.test;
777             syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
778                                                      &mut resolver,
779                                                      krate,
780                                                      is_proc_macro_crate,
781                                                      is_test_crate,
782                                                      num_crate_types,
783                                                      sess.diagnostic())
784         });
785     }
786
787     krate = time(time_passes, "creating allocators", || {
788         allocator::expand::modify(&sess.parse_sess,
789                                   &mut resolver,
790                                   krate,
791                                   sess.diagnostic())
792     });
793
794     after_expand(&krate)?;
795
796     if sess.opts.debugging_opts.input_stats {
797         println!("Post-expansion node count: {}", count_nodes(&krate));
798     }
799
800     if sess.opts.debugging_opts.hir_stats {
801         hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
802     }
803
804     if sess.opts.debugging_opts.ast_json {
805         println!("{}", json::as_json(&krate));
806     }
807
808     time(time_passes,
809          "checking for inline asm in case the target doesn't support it",
810          || no_asm::check_crate(sess, &krate));
811
812     time(time_passes,
813          "AST validation",
814          || ast_validation::check_crate(sess, &krate));
815
816     time(time_passes, "name resolution", || -> CompileResult {
817         resolver.resolve_crate(&krate);
818         Ok(())
819     })?;
820
821     if resolver.found_unresolved_macro {
822         sess.parse_sess.span_diagnostic.abort_if_errors();
823     }
824
825     // Needs to go *after* expansion to be able to check the results of macro expansion.
826     time(time_passes, "complete gated feature checking", || {
827         sess.track_errors(|| {
828             syntax::feature_gate::check_crate(&krate,
829                                               &sess.parse_sess,
830                                               &sess.features.borrow(),
831                                               &attributes,
832                                               sess.opts.unstable_features);
833         })
834     })?;
835
836     time(time_passes,
837          "early lint checks",
838          || lint::check_ast_crate(sess, &krate));
839
840     // Lower ast -> hir.
841     let hir_forest = time(time_passes, "lowering ast -> hir", || {
842         let hir_crate = lower_crate(sess, &krate, &mut resolver);
843
844         if sess.opts.debugging_opts.hir_stats {
845             hir_stats::print_hir_stats(&hir_crate);
846         }
847
848         hir_map::Forest::new(hir_crate, &sess.dep_graph)
849     });
850
851     // Discard hygiene data, which isn't required after lowering to HIR.
852     if !keep_hygiene_data(sess) {
853         syntax::ext::hygiene::clear_markings();
854     }
855
856     Ok(ExpansionResult {
857         expanded_crate: krate,
858         defs: resolver.definitions,
859         analysis: ty::CrateAnalysis {
860             access_levels: Rc::new(AccessLevels::default()),
861             reachable: Rc::new(NodeSet()),
862             name: crate_name.to_string(),
863             glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
864         },
865         resolutions: Resolutions {
866             freevars: resolver.freevars,
867             export_map: resolver.export_map,
868             trait_map: resolver.trait_map,
869             maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
870         },
871         hir_forest: hir_forest,
872     })
873 }
874
875 /// Run the resolution, typechecking, region checking and other
876 /// miscellaneous analysis passes on the crate. Return various
877 /// structures carrying the results of the analysis.
878 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
879                                                hir_map: hir_map::Map<'tcx>,
880                                                mut analysis: ty::CrateAnalysis,
881                                                resolutions: Resolutions,
882                                                arena: &'tcx DroplessArena,
883                                                arenas: &'tcx GlobalArenas<'tcx>,
884                                                name: &str,
885                                                f: F)
886                                                -> Result<R, CompileIncomplete>
887     where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
888                             ty::CrateAnalysis,
889                             IncrementalHashesMap,
890                             CompileResult) -> R
891 {
892     macro_rules! try_with_f {
893         ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
894             match $e {
895                 Ok(x) => x,
896                 Err(x) => {
897                     f($t, $a, $h, Err(x));
898                     return Err(x);
899                 }
900             }
901         }
902     }
903
904     let time_passes = sess.time_passes();
905
906     let lang_items = time(time_passes, "language item collection", || {
907         sess.track_errors(|| {
908             middle::lang_items::collect_language_items(&sess, &hir_map)
909         })
910     })?;
911
912     let named_region_map = time(time_passes,
913                                 "lifetime resolution",
914                                 || middle::resolve_lifetime::krate(sess, &hir_map))?;
915
916     time(time_passes,
917          "looking for entry point",
918          || middle::entry::find_entry_point(sess, &hir_map));
919
920     sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
921         plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
922     }));
923     sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
924
925     time(time_passes,
926          "loop checking",
927          || loops::check_crate(sess, &hir_map));
928
929     time(time_passes,
930               "static item recursion checking",
931               || static_recursion::check_crate(sess, &hir_map))?;
932
933     let index = stability::Index::new(&sess);
934
935     let mut local_providers = ty::maps::Providers::default();
936     borrowck::provide(&mut local_providers);
937     mir::provide(&mut local_providers);
938     reachable::provide(&mut local_providers);
939     rustc_privacy::provide(&mut local_providers);
940     trans::provide(&mut local_providers);
941     typeck::provide(&mut local_providers);
942     ty::provide(&mut local_providers);
943     traits::provide(&mut local_providers);
944     reachable::provide(&mut local_providers);
945     rustc_const_eval::provide(&mut local_providers);
946     middle::region::provide(&mut local_providers);
947     cstore::provide_local(&mut local_providers);
948     lint::provide(&mut local_providers);
949
950     let mut extern_providers = ty::maps::Providers::default();
951     cstore::provide(&mut extern_providers);
952     trans::provide(&mut extern_providers);
953     ty::provide_extern(&mut extern_providers);
954     traits::provide_extern(&mut extern_providers);
955     // FIXME(eddyb) get rid of this once we replace const_eval with miri.
956     rustc_const_eval::provide(&mut extern_providers);
957
958     // Setup the MIR passes that we want to run.
959     let mut passes = Passes::new();
960     passes.push_hook(mir::transform::dump_mir::DumpMir);
961
962     // Remove all `EndRegion` statements that are not involved in borrows.
963     passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
964
965     // What we need to do constant evaluation.
966     passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
967     passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
968     passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
969
970     // We compute "constant qualifications" between MIR_CONST and MIR_VALIDATED.
971
972     // What we need to run borrowck etc.
973     passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
974     passes.push_pass(MIR_VALIDATED,
975                      mir::transform::simplify_branches::SimplifyBranches::new("initial"));
976     passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
977     passes.push_pass(MIR_VALIDATED, mir::transform::nll::NLL);
978
979     // borrowck runs between MIR_VALIDATED and MIR_OPTIMIZED.
980
981     // These next passes must be executed together
982     passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
983     passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
984     passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
985     passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
986     // AddValidation needs to run after ElaborateDrops and before EraseRegions, and it needs
987     // an AllCallEdges pass right before it.
988     passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AllCallEdges);
989     passes.push_pass(MIR_OPTIMIZED, mir::transform::add_validation::AddValidation);
990     passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
991     // No lifetime analysis based on borrowing can be done from here on out.
992
993     // From here on out, regions are gone.
994     passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
995
996     // Optimizations begin.
997     passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
998     passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
999     passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
1000     passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
1001     passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
1002     passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
1003     passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
1004
1005     TyCtxt::create_and_enter(sess,
1006                              local_providers,
1007                              extern_providers,
1008                              Rc::new(passes),
1009                              arenas,
1010                              arena,
1011                              resolutions,
1012                              named_region_map,
1013                              hir_map,
1014                              lang_items,
1015                              index,
1016                              name,
1017                              |tcx| {
1018         let incremental_hashes_map =
1019             time(time_passes,
1020                  "compute_incremental_hashes_map",
1021                  || rustc_incremental::compute_incremental_hashes_map(tcx));
1022
1023         time(time_passes,
1024              "load_dep_graph",
1025              || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
1026
1027         time(time_passes, "stability index", || {
1028             tcx.stability.borrow_mut().build(tcx)
1029         });
1030
1031         time(time_passes,
1032              "stability checking",
1033              || stability::check_unstable_api_usage(tcx));
1034
1035         // passes are timed inside typeck
1036         try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
1037
1038         time(time_passes,
1039              "const checking",
1040              || consts::check_crate(tcx));
1041
1042         analysis.access_levels =
1043             time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1044
1045         time(time_passes,
1046              "intrinsic checking",
1047              || middle::intrinsicck::check_crate(tcx));
1048
1049         time(time_passes,
1050              "effect checking",
1051              || middle::effect::check_crate(tcx));
1052
1053         time(time_passes,
1054              "match checking",
1055              || check_match::check_crate(tcx));
1056
1057         // this must run before MIR dump, because
1058         // "not all control paths return a value" is reported here.
1059         //
1060         // maybe move the check to a MIR pass?
1061         time(time_passes,
1062              "liveness checking",
1063              || middle::liveness::check_crate(tcx));
1064
1065         time(time_passes,
1066              "borrow checking",
1067              || borrowck::check_crate(tcx));
1068
1069         // Avoid overwhelming user with errors if type checking failed.
1070         // I'm not sure how helpful this is, to be honest, but it avoids
1071         // a
1072         // lot of annoying errors in the compile-fail tests (basically,
1073         // lint warnings and so on -- kindck used to do this abort, but
1074         // kindck is gone now). -nmatsakis
1075         if sess.err_count() > 0 {
1076             return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1077         }
1078
1079         analysis.reachable =
1080             time(time_passes,
1081                  "reachability checking",
1082                  || reachable::find_reachable(tcx));
1083
1084         time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1085
1086         time(time_passes, "unused lib feature checking", || {
1087             stability::check_unused_or_stable_features(tcx)
1088         });
1089
1090         time(time_passes, "lint checking", || lint::check_crate(tcx));
1091
1092         return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1093     })
1094 }
1095
1096 /// Run the translation phase to LLVM, after which the AST and analysis can
1097 /// be discarded.
1098 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1099                                            analysis: ty::CrateAnalysis,
1100                                            incremental_hashes_map: IncrementalHashesMap,
1101                                            output_filenames: &OutputFilenames)
1102                                            -> write::OngoingCrateTranslation {
1103     let time_passes = tcx.sess.time_passes();
1104
1105     time(time_passes,
1106          "resolving dependency formats",
1107          || ::rustc::middle::dependency_format::calculate(tcx));
1108
1109     let translation =
1110         time(time_passes,
1111              "translation",
1112              move || trans::trans_crate(tcx, analysis, incremental_hashes_map, output_filenames));
1113
1114     translation
1115 }
1116
1117 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1118 /// as a side effect.
1119 #[cfg(feature="llvm")]
1120 pub fn phase_5_run_llvm_passes(sess: &Session,
1121                                trans: write::OngoingCrateTranslation)
1122                                -> (CompileResult, trans::CrateTranslation) {
1123     let trans = trans.join(sess);
1124
1125     if sess.opts.debugging_opts.incremental_info {
1126         write::dump_incremental_data(&trans);
1127     }
1128
1129     time(sess.time_passes(),
1130          "serialize work products",
1131          move || rustc_incremental::save_work_products(sess));
1132
1133     (sess.compile_status(), trans)
1134 }
1135
1136 /// Run the linker on any artifacts that resulted from the LLVM run.
1137 /// This should produce either a finished executable or library.
1138 #[cfg(feature="llvm")]
1139 pub fn phase_6_link_output(sess: &Session,
1140                            trans: &trans::CrateTranslation,
1141                            outputs: &OutputFilenames) {
1142     time(sess.time_passes(), "linking", || {
1143         ::rustc_trans::back::link::link_binary(sess, trans, outputs, &trans.crate_name.as_str())
1144     });
1145 }
1146
1147 fn escape_dep_filename(filename: &str) -> String {
1148     // Apparently clang and gcc *only* escape spaces:
1149     // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1150     filename.replace(" ", "\\ ")
1151 }
1152
1153 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1154     let mut out_filenames = Vec::new();
1155     for output_type in sess.opts.output_types.keys() {
1156         let file = outputs.path(*output_type);
1157         match *output_type {
1158             OutputType::Exe => {
1159                 for output in sess.crate_types.borrow().iter() {
1160                     let p = ::rustc_trans_utils::link::filename_for_input(
1161                         sess,
1162                         *output,
1163                         crate_name,
1164                         outputs
1165                     );
1166                     out_filenames.push(p);
1167                 }
1168             }
1169             _ => {
1170                 out_filenames.push(file);
1171             }
1172         }
1173     }
1174
1175     // Write out dependency rules to the dep-info file if requested
1176     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1177         return;
1178     }
1179     let deps_filename = outputs.path(OutputType::DepInfo);
1180
1181     let result =
1182         (|| -> io::Result<()> {
1183             // Build a list of files used to compile the output and
1184             // write Makefile-compatible dependency rules
1185             let files: Vec<String> = sess.codemap()
1186                                          .files()
1187                                          .iter()
1188                                          .filter(|fmap| fmap.is_real_file())
1189                                          .filter(|fmap| !fmap.is_imported())
1190                                          .map(|fmap| escape_dep_filename(&fmap.name))
1191                                          .collect();
1192             let mut file = fs::File::create(&deps_filename)?;
1193             for path in &out_filenames {
1194                 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1195             }
1196
1197             // Emit a fake target for each input file to the compilation. This
1198             // prevents `make` from spitting out an error if a file is later
1199             // deleted. For more info see #28735
1200             for path in files {
1201                 writeln!(file, "{}:", path)?;
1202             }
1203             Ok(())
1204         })();
1205
1206     match result {
1207         Ok(()) => {}
1208         Err(e) => {
1209             sess.fatal(&format!("error writing dependencies to `{}`: {}",
1210                                 deps_filename.display(),
1211                                 e));
1212         }
1213     }
1214 }
1215
1216 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1217     // Unconditionally collect crate types from attributes to make them used
1218     let attr_types: Vec<config::CrateType> =
1219         attrs.iter()
1220              .filter_map(|a| {
1221                  if a.check_name("crate_type") {
1222                      match a.value_str() {
1223                          Some(ref n) if *n == "rlib" => {
1224                              Some(config::CrateTypeRlib)
1225                          }
1226                          Some(ref n) if *n == "dylib" => {
1227                              Some(config::CrateTypeDylib)
1228                          }
1229                          Some(ref n) if *n == "cdylib" => {
1230                              Some(config::CrateTypeCdylib)
1231                          }
1232                          Some(ref n) if *n == "lib" => {
1233                              Some(config::default_lib_output())
1234                          }
1235                          Some(ref n) if *n == "staticlib" => {
1236                              Some(config::CrateTypeStaticlib)
1237                          }
1238                          Some(ref n) if *n == "proc-macro" => {
1239                              Some(config::CrateTypeProcMacro)
1240                          }
1241                          Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1242                          Some(_) => {
1243                              session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1244                                                  ast::CRATE_NODE_ID,
1245                                                  a.span,
1246                                                  "invalid `crate_type` value");
1247                              None
1248                          }
1249                          _ => {
1250                              session.struct_span_err(a.span, "`crate_type` requires a value")
1251                                  .note("for example: `#![crate_type=\"lib\"]`")
1252                                  .emit();
1253                              None
1254                          }
1255                      }
1256                  } else {
1257                      None
1258                  }
1259              })
1260              .collect();
1261
1262     // If we're generating a test executable, then ignore all other output
1263     // styles at all other locations
1264     if session.opts.test {
1265         return vec![config::CrateTypeExecutable];
1266     }
1267
1268     // Only check command line flags if present. If no types are specified by
1269     // command line, then reuse the empty `base` Vec to hold the types that
1270     // will be found in crate attributes.
1271     let mut base = session.opts.crate_types.clone();
1272     if base.is_empty() {
1273         base.extend(attr_types);
1274         if base.is_empty() {
1275             base.push(::rustc_trans_utils::link::default_output_for_target(session));
1276         }
1277         base.sort();
1278         base.dedup();
1279     }
1280
1281     base.into_iter()
1282         .filter(|crate_type| {
1283             let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1284
1285             if !res {
1286                 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1287                                       *crate_type,
1288                                       session.opts.target_triple));
1289             }
1290
1291             res
1292         })
1293         .collect()
1294 }
1295
1296 pub fn compute_crate_disambiguator(session: &Session) -> String {
1297     use std::hash::Hasher;
1298
1299     // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1300     // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1301     // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1302     // should still be safe enough to avoid collisions in practice.
1303     // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1304     //            a hex-string instead of raw bytes. We should really use the
1305     //            smaller representation.
1306     let mut hasher = StableHasher::<Fingerprint>::new();
1307
1308     let mut metadata = session.opts.cg.metadata.clone();
1309     // We don't want the crate_disambiguator to dependent on the order
1310     // -C metadata arguments, so sort them:
1311     metadata.sort();
1312     // Every distinct -C metadata value is only incorporated once:
1313     metadata.dedup();
1314
1315     hasher.write(b"metadata");
1316     for s in &metadata {
1317         // Also incorporate the length of a metadata string, so that we generate
1318         // different values for `-Cmetadata=ab -Cmetadata=c` and
1319         // `-Cmetadata=a -Cmetadata=bc`
1320         hasher.write_usize(s.len());
1321         hasher.write(s.as_bytes());
1322     }
1323
1324     // If this is an executable, add a special suffix, so that we don't get
1325     // symbol conflicts when linking against a library of the same name.
1326     let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1327
1328     format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1329 }
1330
1331 pub fn build_output_filenames(input: &Input,
1332                               odir: &Option<PathBuf>,
1333                               ofile: &Option<PathBuf>,
1334                               attrs: &[ast::Attribute],
1335                               sess: &Session)
1336                               -> OutputFilenames {
1337     match *ofile {
1338         None => {
1339             // "-" as input file will cause the parser to read from stdin so we
1340             // have to make up a name
1341             // We want to toss everything after the final '.'
1342             let dirpath = match *odir {
1343                 Some(ref d) => d.clone(),
1344                 None => PathBuf::new(),
1345             };
1346
1347             // If a crate name is present, we use it as the link name
1348             let stem = sess.opts
1349                            .crate_name
1350                            .clone()
1351                            .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1352                            .unwrap_or(input.filestem());
1353
1354             OutputFilenames {
1355                 out_directory: dirpath,
1356                 out_filestem: stem,
1357                 single_output_file: None,
1358                 extra: sess.opts.cg.extra_filename.clone(),
1359                 outputs: sess.opts.output_types.clone(),
1360             }
1361         }
1362
1363         Some(ref out_file) => {
1364             let unnamed_output_types = sess.opts
1365                                            .output_types
1366                                            .values()
1367                                            .filter(|a| a.is_none())
1368                                            .count();
1369             let ofile = if unnamed_output_types > 1 {
1370                 sess.warn("due to multiple output types requested, the explicitly specified \
1371                            output file name will be adapted for each output type");
1372                 None
1373             } else {
1374                 Some(out_file.clone())
1375             };
1376             if *odir != None {
1377                 sess.warn("ignoring --out-dir flag due to -o flag.");
1378             }
1379
1380             let cur_dir = Path::new("");
1381
1382             OutputFilenames {
1383                 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1384                 out_filestem: out_file.file_stem()
1385                                       .unwrap_or(OsStr::new(""))
1386                                       .to_str()
1387                                       .unwrap()
1388                                       .to_string(),
1389                 single_output_file: ofile,
1390                 extra: sess.opts.cg.extra_filename.clone(),
1391                 outputs: sess.opts.output_types.clone(),
1392             }
1393         }
1394     }
1395 }