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