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