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