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