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