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