]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / librustc / session / config.rs
1 // Copyright 2014 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 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
13
14 pub use self::EntryFnType::*;
15 pub use self::CrateType::*;
16 pub use self::Passes::*;
17 pub use self::DebugInfoLevel::*;
18
19 use session::{early_error, early_warn, Session};
20 use session::search_paths::SearchPaths;
21
22 use rustc_back::PanicStrategy;
23 use rustc_back::target::Target;
24 use lint;
25 use middle::cstore;
26
27 use syntax::ast::{self, IntTy, UintTy};
28 use syntax::parse::token;
29 use syntax::parse;
30 use syntax::symbol::Symbol;
31 use syntax::feature_gate::UnstableFeatures;
32
33 use errors::{ColorConfig, FatalError, Handler};
34
35 use getopts;
36 use std::collections::{BTreeMap, BTreeSet};
37 use std::collections::btree_map::Iter as BTreeMapIter;
38 use std::collections::btree_map::Keys as BTreeMapKeysIter;
39 use std::collections::btree_map::Values as BTreeMapValuesIter;
40
41 use std::fmt;
42 use std::hash::Hasher;
43 use std::collections::hash_map::DefaultHasher;
44 use std::collections::HashSet;
45 use std::iter::FromIterator;
46 use std::path::PathBuf;
47
48 pub struct Config {
49     pub target: Target,
50     pub int_type: IntTy,
51     pub uint_type: UintTy,
52 }
53
54 #[derive(Clone, Hash)]
55 pub enum Sanitizer {
56     Address,
57     Leak,
58     Memory,
59     Thread,
60 }
61
62 #[derive(Clone, Copy, PartialEq, Hash)]
63 pub enum OptLevel {
64     No, // -O0
65     Less, // -O1
66     Default, // -O2
67     Aggressive, // -O3
68     Size, // -Os
69     SizeMin, // -Oz
70 }
71
72 #[derive(Clone, Copy, PartialEq, Hash)]
73 pub enum DebugInfoLevel {
74     NoDebugInfo,
75     LimitedDebugInfo,
76     FullDebugInfo,
77 }
78
79 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord,
80          RustcEncodable, RustcDecodable)]
81 pub enum OutputType {
82     Bitcode,
83     Assembly,
84     LlvmAssembly,
85     Metadata,
86     Object,
87     Exe,
88     DepInfo,
89 }
90
91 impl OutputType {
92     fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
93         match *self {
94             OutputType::Exe |
95             OutputType::DepInfo => true,
96             OutputType::Bitcode |
97             OutputType::Assembly |
98             OutputType::LlvmAssembly |
99             OutputType::Object |
100             OutputType::Metadata => false,
101         }
102     }
103
104     fn shorthand(&self) -> &'static str {
105         match *self {
106             OutputType::Bitcode => "llvm-bc",
107             OutputType::Assembly => "asm",
108             OutputType::LlvmAssembly => "llvm-ir",
109             OutputType::Object => "obj",
110             OutputType::Metadata => "metadata",
111             OutputType::Exe => "link",
112             OutputType::DepInfo => "dep-info",
113         }
114     }
115
116     pub fn extension(&self) -> &'static str {
117         match *self {
118             OutputType::Bitcode => "bc",
119             OutputType::Assembly => "s",
120             OutputType::LlvmAssembly => "ll",
121             OutputType::Object => "o",
122             OutputType::Metadata => "rmeta",
123             OutputType::DepInfo => "d",
124             OutputType::Exe => "",
125         }
126     }
127 }
128
129 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
130 pub enum ErrorOutputType {
131     HumanReadable(ColorConfig),
132     Json,
133 }
134
135 impl Default for ErrorOutputType {
136     fn default() -> ErrorOutputType {
137         ErrorOutputType::HumanReadable(ColorConfig::Auto)
138     }
139 }
140
141 // Use tree-based collections to cheaply get a deterministic Hash implementation.
142 // DO NOT switch BTreeMap out for an unsorted container type! That would break
143 // dependency tracking for commandline arguments.
144 #[derive(Clone, Hash)]
145 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
146
147 impl OutputTypes {
148     pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
149         OutputTypes(BTreeMap::from_iter(entries.iter()
150                                                .map(|&(k, ref v)| (k, v.clone()))))
151     }
152
153     pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
154         self.0.get(key)
155     }
156
157     pub fn contains_key(&self, key: &OutputType) -> bool {
158         self.0.contains_key(key)
159     }
160
161     pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
162         self.0.keys()
163     }
164
165     pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
166         self.0.values()
167     }
168
169     // True if any of the output types require codegen or linking.
170     pub fn should_trans(&self) -> bool {
171         self.0.keys().any(|k| match *k {
172             OutputType::Bitcode |
173             OutputType::Assembly |
174             OutputType::LlvmAssembly |
175             OutputType::Object |
176             OutputType::Exe => true,
177             OutputType::Metadata |
178             OutputType::DepInfo => false,
179         })
180     }
181 }
182
183
184 // Use tree-based collections to cheaply get a deterministic Hash implementation.
185 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
186 // would break dependency tracking for commandline arguments.
187 #[derive(Clone, Hash)]
188 pub struct Externs(BTreeMap<String, BTreeSet<String>>);
189
190 impl Externs {
191     pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
192         Externs(data)
193     }
194
195     pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
196         self.0.get(key)
197     }
198
199     pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
200         self.0.iter()
201     }
202 }
203
204 macro_rules! hash_option {
205     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
206     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
207         if $sub_hashes.insert(stringify!($opt_name),
208                               $opt_expr as &dep_tracking::DepTrackingHash).is_some() {
209             bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
210         }
211     });
212     ($opt_name:ident,
213      $opt_expr:expr,
214      $sub_hashes:expr,
215      [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
216         if *$opt_expr == $warn_val {
217             early_warn($error_format, $warn_text)
218         }
219     });
220 }
221
222 macro_rules! top_level_options {
223     (pub struct Options { $(
224         $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
225     )* } ) => (
226         #[derive(Clone)]
227         pub struct Options {
228             $(pub $opt: $t),*
229         }
230
231         impl Options {
232             pub fn dep_tracking_hash(&self) -> u64 {
233                 let mut sub_hashes = BTreeMap::new();
234                 $({
235                     hash_option!($opt,
236                                  &self.$opt,
237                                  &mut sub_hashes,
238                                  [$dep_tracking_marker $($warn_val,
239                                                          $warn_text,
240                                                          self.error_format)*]);
241                 })*
242                 let mut hasher = DefaultHasher::new();
243                 dep_tracking::stable_hash(sub_hashes,
244                                           &mut hasher,
245                                           self.error_format);
246                 hasher.finish()
247             }
248         }
249     );
250 }
251
252 // The top-level commandline options struct
253 //
254 // For each option, one has to specify how it behaves with regard to the
255 // dependency tracking system of incremental compilation. This is done via the
256 // square-bracketed directive after the field type. The options are:
257 //
258 // [TRACKED]
259 // A change in the given field will cause the compiler to completely clear the
260 // incremental compilation cache before proceeding.
261 //
262 // [UNTRACKED]
263 // Incremental compilation is not influenced by this option.
264 //
265 // [UNTRACKED_WITH_WARNING(val, warning)]
266 // The option is incompatible with incremental compilation in some way. If it
267 // has the value `val`, the string `warning` is emitted as a warning.
268 //
269 // If you add a new option to this struct or one of the sub-structs like
270 // CodegenOptions, think about how it influences incremental compilation. If in
271 // doubt, specify [TRACKED], which is always "correct" but might lead to
272 // unnecessary re-compilation.
273 top_level_options!(
274     pub struct Options {
275         // The crate config requested for the session, which may be combined
276         // with additional crate configurations during the compile process
277         crate_types: Vec<CrateType> [TRACKED],
278         optimize: OptLevel [TRACKED],
279         // Include the debug_assertions flag into dependency tracking, since it
280         // can influence whether overflow checks are done or not.
281         debug_assertions: bool [TRACKED],
282         debuginfo: DebugInfoLevel [TRACKED],
283         lint_opts: Vec<(String, lint::Level)> [TRACKED],
284         lint_cap: Option<lint::Level> [TRACKED],
285         describe_lints: bool [UNTRACKED],
286         output_types: OutputTypes [TRACKED],
287         // FIXME(mw): We track this for now but it actually doesn't make too
288         //            much sense: The search path can stay the same while the
289         //            things discovered there might have changed on disk.
290         search_paths: SearchPaths [TRACKED],
291         libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
292         maybe_sysroot: Option<PathBuf> [TRACKED],
293
294         target_triple: String [TRACKED],
295
296         test: bool [TRACKED],
297         error_format: ErrorOutputType [UNTRACKED],
298
299         // if Some, enable incremental compilation, using the given
300         // directory to store intermediate results
301         incremental: Option<PathBuf> [UNTRACKED],
302
303         debugging_opts: DebuggingOptions [TRACKED],
304         prints: Vec<PrintRequest> [UNTRACKED],
305         cg: CodegenOptions [TRACKED],
306         // FIXME(mw): We track this for now but it actually doesn't make too
307         //            much sense: The value of this option can stay the same
308         //            while the files they refer to might have changed on disk.
309         externs: Externs [TRACKED],
310         crate_name: Option<String> [TRACKED],
311         // An optional name to use as the crate for std during std injection,
312         // written `extern crate std = "name"`. Default to "std". Used by
313         // out-of-tree drivers.
314         alt_std_name: Option<String> [TRACKED],
315         // Indicates how the compiler should treat unstable features
316         unstable_features: UnstableFeatures [TRACKED],
317
318         // Indicates whether this run of the compiler is actually rustdoc. This
319         // is currently just a hack and will be removed eventually, so please
320         // try to not rely on this too much.
321         actually_rustdoc: bool [TRACKED],
322     }
323 );
324
325 #[derive(Clone, PartialEq, Eq)]
326 pub enum PrintRequest {
327     FileNames,
328     Sysroot,
329     CrateName,
330     Cfg,
331     TargetList,
332     TargetCPUs,
333     TargetFeatures,
334     RelocationModels,
335     CodeModels,
336     TargetSpec,
337 }
338
339 pub enum Input {
340     /// Load source from file
341     File(PathBuf),
342     Str {
343         /// String that is shown in place of a filename
344         name: String,
345         /// Anonymous source string
346         input: String,
347     },
348 }
349
350 impl Input {
351     pub fn filestem(&self) -> String {
352         match *self {
353             Input::File(ref ifile) => ifile.file_stem().unwrap()
354                                            .to_str().unwrap().to_string(),
355             Input::Str { .. } => "rust_out".to_string(),
356         }
357     }
358 }
359
360 #[derive(Clone)]
361 pub struct OutputFilenames {
362     pub out_directory: PathBuf,
363     pub out_filestem: String,
364     pub single_output_file: Option<PathBuf>,
365     pub extra: String,
366     pub outputs: OutputTypes,
367 }
368
369 /// Codegen unit names generated by the numbered naming scheme will contain this
370 /// marker right before the index of the codegen unit.
371 pub const NUMBERED_CODEGEN_UNIT_MARKER: &'static str = ".cgu-";
372
373 impl OutputFilenames {
374     pub fn path(&self, flavor: OutputType) -> PathBuf {
375         self.outputs.get(&flavor).and_then(|p| p.to_owned())
376             .or_else(|| self.single_output_file.clone())
377             .unwrap_or_else(|| self.temp_path(flavor, None))
378     }
379
380     /// Get the path where a compilation artifact of the given type for the
381     /// given codegen unit should be placed on disk. If codegen_unit_name is
382     /// None, a path distinct from those of any codegen unit will be generated.
383     pub fn temp_path(&self,
384                      flavor: OutputType,
385                      codegen_unit_name: Option<&str>)
386                      -> PathBuf {
387         let extension = flavor.extension();
388         self.temp_path_ext(extension, codegen_unit_name)
389     }
390
391     /// Like temp_path, but also supports things where there is no corresponding
392     /// OutputType, like no-opt-bitcode or lto-bitcode.
393     pub fn temp_path_ext(&self,
394                          ext: &str,
395                          codegen_unit_name: Option<&str>)
396                          -> PathBuf {
397         let base = self.out_directory.join(&self.filestem());
398
399         let mut extension = String::new();
400
401         if let Some(codegen_unit_name) = codegen_unit_name {
402             if codegen_unit_name.contains(NUMBERED_CODEGEN_UNIT_MARKER) {
403                 // If we use the numbered naming scheme for modules, we don't want
404                 // the files to look like <crate-name><extra>.<crate-name>.<index>.<ext>
405                 // but simply <crate-name><extra>.<index>.<ext>
406                 let marker_offset = codegen_unit_name.rfind(NUMBERED_CODEGEN_UNIT_MARKER)
407                                                      .unwrap();
408                 let index_offset = marker_offset + NUMBERED_CODEGEN_UNIT_MARKER.len();
409                 extension.push_str(&codegen_unit_name[index_offset .. ]);
410             } else {
411                 extension.push_str(codegen_unit_name);
412             };
413         }
414
415         if !ext.is_empty() {
416             if !extension.is_empty() {
417                 extension.push_str(".");
418             }
419
420             extension.push_str(ext);
421         }
422
423         let path = base.with_extension(&extension[..]);
424         path
425     }
426
427     pub fn with_extension(&self, extension: &str) -> PathBuf {
428         self.out_directory.join(&self.filestem()).with_extension(extension)
429     }
430
431     pub fn filestem(&self) -> String {
432         format!("{}{}", self.out_filestem, self.extra)
433     }
434 }
435
436 pub fn host_triple() -> &'static str {
437     // Get the host triple out of the build environment. This ensures that our
438     // idea of the host triple is the same as for the set of libraries we've
439     // actually built.  We can't just take LLVM's host triple because they
440     // normalize all ix86 architectures to i386.
441     //
442     // Instead of grabbing the host triple (for the current host), we grab (at
443     // compile time) the target triple that this rustc is built with and
444     // calling that (at runtime) the host triple.
445     (option_env!("CFG_COMPILER_HOST_TRIPLE")).
446         expect("CFG_COMPILER_HOST_TRIPLE")
447 }
448
449 /// Some reasonable defaults
450 pub fn basic_options() -> Options {
451     Options {
452         crate_types: Vec::new(),
453         optimize: OptLevel::No,
454         debuginfo: NoDebugInfo,
455         lint_opts: Vec::new(),
456         lint_cap: None,
457         describe_lints: false,
458         output_types: OutputTypes(BTreeMap::new()),
459         search_paths: SearchPaths::new(),
460         maybe_sysroot: None,
461         target_triple: host_triple().to_string(),
462         test: false,
463         incremental: None,
464         debugging_opts: basic_debugging_options(),
465         prints: Vec::new(),
466         cg: basic_codegen_options(),
467         error_format: ErrorOutputType::default(),
468         externs: Externs(BTreeMap::new()),
469         crate_name: None,
470         alt_std_name: None,
471         libs: Vec::new(),
472         unstable_features: UnstableFeatures::Disallow,
473         debug_assertions: true,
474         actually_rustdoc: false,
475     }
476 }
477
478 impl Options {
479     /// True if there is a reason to build the dep graph.
480     pub fn build_dep_graph(&self) -> bool {
481         self.incremental.is_some() ||
482             self.debugging_opts.dump_dep_graph ||
483             self.debugging_opts.query_dep_graph
484     }
485
486     pub fn single_codegen_unit(&self) -> bool {
487         self.incremental.is_none() ||
488         self.cg.codegen_units == 1
489     }
490 }
491
492 // The type of entry function, so
493 // users can have their own entry
494 // functions that don't start a
495 // scheduler
496 #[derive(Copy, Clone, PartialEq)]
497 pub enum EntryFnType {
498     EntryMain,
499     EntryStart,
500     EntryNone,
501 }
502
503 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
504 pub enum CrateType {
505     CrateTypeExecutable,
506     CrateTypeDylib,
507     CrateTypeRlib,
508     CrateTypeStaticlib,
509     CrateTypeCdylib,
510     CrateTypeProcMacro,
511 }
512
513 #[derive(Clone, Hash)]
514 pub enum Passes {
515     SomePasses(Vec<String>),
516     AllPasses,
517 }
518
519 impl Passes {
520     pub fn is_empty(&self) -> bool {
521         match *self {
522             SomePasses(ref v) => v.is_empty(),
523             AllPasses => false,
524         }
525     }
526 }
527
528 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
529 /// at once. The goal of this macro is to define an interface that can be
530 /// programmatically used by the option parser in order to initialize the struct
531 /// without hardcoding field names all over the place.
532 ///
533 /// The goal is to invoke this macro once with the correct fields, and then this
534 /// macro generates all necessary code. The main gotcha of this macro is the
535 /// cgsetters module which is a bunch of generated code to parse an option into
536 /// its respective field in the struct. There are a few hand-written parsers for
537 /// parsing specific types of values in this module.
538 macro_rules! options {
539     ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
540      $buildfn:ident, $prefix:expr, $outputname:expr,
541      $stat:ident, $mod_desc:ident, $mod_set:ident,
542      $($opt:ident : $t:ty = (
543         $init:expr,
544         $parse:ident,
545         [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
546         $desc:expr)
547      ),* ,) =>
548 (
549     #[derive(Clone)]
550     pub struct $struct_name { $(pub $opt: $t),* }
551
552     pub fn $defaultfn() -> $struct_name {
553         $struct_name { $($opt: $init),* }
554     }
555
556     pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
557     {
558         let mut op = $defaultfn();
559         for option in matches.opt_strs($prefix) {
560             let mut iter = option.splitn(2, '=');
561             let key = iter.next().unwrap();
562             let value = iter.next();
563             let option_to_lookup = key.replace("-", "_");
564             let mut found = false;
565             for &(candidate, setter, opt_type_desc, _) in $stat {
566                 if option_to_lookup != candidate { continue }
567                 if !setter(&mut op, value) {
568                     match (value, opt_type_desc) {
569                         (Some(..), None) => {
570                             early_error(error_format, &format!("{} option `{}` takes no \
571                                                               value", $outputname, key))
572                         }
573                         (None, Some(type_desc)) => {
574                             early_error(error_format, &format!("{0} option `{1}` requires \
575                                                               {2} ({3} {1}=<value>)",
576                                                              $outputname, key,
577                                                              type_desc, $prefix))
578                         }
579                         (Some(value), Some(type_desc)) => {
580                             early_error(error_format, &format!("incorrect value `{}` for {} \
581                                                               option `{}` - {} was expected",
582                                                              value, $outputname,
583                                                              key, type_desc))
584                         }
585                         (None, None) => bug!()
586                     }
587                 }
588                 found = true;
589                 break;
590             }
591             if !found {
592                 early_error(error_format, &format!("unknown {} option: `{}`",
593                                                  $outputname, key));
594             }
595         }
596         return op;
597     }
598
599     impl<'a> dep_tracking::DepTrackingHash for $struct_name {
600
601         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
602             let mut sub_hashes = BTreeMap::new();
603             $({
604                 hash_option!($opt,
605                              &self.$opt,
606                              &mut sub_hashes,
607                              [$dep_tracking_marker $($dep_warn_val,
608                                                      $dep_warn_text,
609                                                      error_format)*]);
610             })*
611             dep_tracking::stable_hash(sub_hashes, hasher, error_format);
612         }
613     }
614
615     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
616     pub const $stat: &'static [(&'static str, $setter_name,
617                                      Option<&'static str>, &'static str)] =
618         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
619
620     #[allow(non_upper_case_globals, dead_code)]
621     mod $mod_desc {
622         pub const parse_bool: Option<&'static str> = None;
623         pub const parse_opt_bool: Option<&'static str> =
624             Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
625         pub const parse_string: Option<&'static str> = Some("a string");
626         pub const parse_string_push: Option<&'static str> = Some("a string");
627         pub const parse_opt_string: Option<&'static str> = Some("a string");
628         pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
629         pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
630         pub const parse_uint: Option<&'static str> = Some("a number");
631         pub const parse_passes: Option<&'static str> =
632             Some("a space-separated list of passes, or `all`");
633         pub const parse_opt_uint: Option<&'static str> =
634             Some("a number");
635         pub const parse_panic_strategy: Option<&'static str> =
636             Some("either `panic` or `abort`");
637         pub const parse_sanitizer: Option<&'static str> =
638             Some("one of: `address`, `leak`, `memory` or `thread`");
639     }
640
641     #[allow(dead_code)]
642     mod $mod_set {
643         use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer};
644         use rustc_back::PanicStrategy;
645
646         $(
647             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
648                 $parse(&mut cg.$opt, v)
649             }
650         )*
651
652         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
653             match v {
654                 Some(..) => false,
655                 None => { *slot = true; true }
656             }
657         }
658
659         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
660             match v {
661                 Some(s) => {
662                     match s {
663                         "n" | "no" | "off" => {
664                             *slot = Some(false);
665                         }
666                         "y" | "yes" | "on" => {
667                             *slot = Some(true);
668                         }
669                         _ => { return false; }
670                     }
671
672                     true
673                 },
674                 None => { *slot = Some(true); true }
675             }
676         }
677
678         fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
679             match v {
680                 Some(s) => { *slot = Some(s.to_string()); true },
681                 None => false,
682             }
683         }
684
685         fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
686             match v {
687                 Some(s) => { *slot = s.to_string(); true },
688                 None => false,
689             }
690         }
691
692         fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
693             match v {
694                 Some(s) => { slot.push(s.to_string()); true },
695                 None => false,
696             }
697         }
698
699         fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
700                       -> bool {
701             match v {
702                 Some(s) => {
703                     for s in s.split_whitespace() {
704                         slot.push(s.to_string());
705                     }
706                     true
707                 },
708                 None => false,
709             }
710         }
711
712         fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
713                       -> bool {
714             match v {
715                 Some(s) => {
716                     let v = s.split_whitespace().map(|s| s.to_string()).collect();
717                     *slot = Some(v);
718                     true
719                 },
720                 None => false,
721             }
722         }
723
724         fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
725             match v.and_then(|s| s.parse().ok()) {
726                 Some(i) => { *slot = i; true },
727                 None => false
728             }
729         }
730
731         fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
732             match v {
733                 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
734                 None => { *slot = None; true }
735             }
736         }
737
738         fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
739             match v {
740                 Some("all") => {
741                     *slot = AllPasses;
742                     true
743                 }
744                 v => {
745                     let mut passes = vec![];
746                     if parse_list(&mut passes, v) {
747                         *slot = SomePasses(passes);
748                         true
749                     } else {
750                         false
751                     }
752                 }
753             }
754         }
755
756         fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
757             match v {
758                 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
759                 Some("abort") => *slot = Some(PanicStrategy::Abort),
760                 _ => return false
761             }
762             true
763         }
764
765         fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
766             match v {
767                 Some("address") => *slote = Some(Sanitizer::Address),
768                 Some("leak") => *slote = Some(Sanitizer::Leak),
769                 Some("memory") => *slote = Some(Sanitizer::Memory),
770                 Some("thread") => *slote = Some(Sanitizer::Thread),
771                 _ => return false,
772             }
773             true
774         }
775     }
776 ) }
777
778 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
779          build_codegen_options, "C", "codegen",
780          CG_OPTIONS, cg_type_desc, cgsetters,
781     ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
782         "tool to assemble archives with"),
783     linker: Option<String> = (None, parse_opt_string, [UNTRACKED],
784         "system linker to link outputs with"),
785     link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
786         "a single extra argument to pass to the linker (can be used several times)"),
787     link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
788         "extra arguments to pass to the linker (space separated)"),
789     link_dead_code: bool = (false, parse_bool, [UNTRACKED],
790         "don't let linker strip dead code (turning it on can be used for code coverage)"),
791     lto: bool = (false, parse_bool, [TRACKED],
792         "perform LLVM link-time optimizations"),
793     target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
794         "select target processor (rustc --print target-cpus for details)"),
795     target_feature: String = ("".to_string(), parse_string, [TRACKED],
796         "target specific attributes (rustc --print target-features for details)"),
797     passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
798         "a list of extra LLVM passes to run (space separated)"),
799     llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
800         "a list of arguments to pass to llvm (space separated)"),
801     save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
802         "`-C save-temps` might not produce all requested temporary products \
803          when incremental compilation is enabled.")],
804         "save all temporary output files during compilation"),
805     rpath: bool = (false, parse_bool, [UNTRACKED],
806         "set rpath values in libs/exes"),
807     overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
808         "use overflow checks for integer arithmetic"),
809     no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
810         "don't pre-populate the pass manager with a list of passes"),
811     no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
812         "don't run the loop vectorization optimization passes"),
813     no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
814         "don't run LLVM's SLP vectorization pass"),
815     soft_float: bool = (false, parse_bool, [TRACKED],
816         "use soft float ABI (*eabihf targets only)"),
817     prefer_dynamic: bool = (false, parse_bool, [TRACKED],
818         "prefer dynamic linking to static linking"),
819     no_integrated_as: bool = (false, parse_bool, [TRACKED],
820         "use an external assembler rather than LLVM's integrated one"),
821     no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
822         "disable the use of the redzone"),
823     relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
824          "choose the relocation model to use (rustc --print relocation-models for details)"),
825     code_model: Option<String> = (None, parse_opt_string, [TRACKED],
826          "choose the code model to use (rustc --print code-models for details)"),
827     metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
828          "metadata to mangle symbol names with"),
829     extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
830          "extra data to put in each output filename"),
831     codegen_units: usize = (1, parse_uint, [UNTRACKED],
832         "divide crate into N units to optimize in parallel"),
833     remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
834         "print remarks for these optimization passes (space separated, or \"all\")"),
835     no_stack_check: bool = (false, parse_bool, [UNTRACKED],
836         "the --no-stack-check flag is deprecated and does nothing"),
837     debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
838         "debug info emission level, 0 = no debug info, 1 = line tables only, \
839          2 = full debug info with variable and type information"),
840     opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
841         "optimize with possible levels 0-3, s, or z"),
842     debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
843         "explicitly enable the cfg(debug_assertions) directive"),
844     inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
845         "set the inlining threshold for"),
846     panic: Option<PanicStrategy> = (None, parse_panic_strategy,
847         [TRACKED], "panic strategy to compile crate with"),
848 }
849
850 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
851          build_debugging_options, "Z", "debugging",
852          DB_OPTIONS, db_type_desc, dbsetters,
853     verbose: bool = (false, parse_bool, [UNTRACKED],
854         "in general, enable more debug printouts"),
855     time_passes: bool = (false, parse_bool, [UNTRACKED],
856         "measure time of each rustc pass"),
857     count_llvm_insns: bool = (false, parse_bool,
858         [UNTRACKED_WITH_WARNING(true,
859         "The output generated by `-Z count_llvm_insns` might not be reliable \
860          when used with incremental compilation")],
861         "count where LLVM instrs originate"),
862     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
863         "The output of `-Z time-llvm-passes` will only reflect timings of \
864          re-translated modules when used with incremental compilation" )],
865         "measure time of each LLVM pass"),
866     input_stats: bool = (false, parse_bool, [UNTRACKED],
867         "gather statistics about the input"),
868     trans_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
869         "The output of `-Z trans-stats` might not be accurate when incremental \
870          compilation is enabled")],
871         "gather trans statistics"),
872     asm_comments: bool = (false, parse_bool, [TRACKED],
873         "generate comments into the assembly (may change behavior)"),
874     no_verify: bool = (false, parse_bool, [TRACKED],
875         "skip LLVM verification"),
876     borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
877         "gather borrowck statistics"),
878     no_landing_pads: bool = (false, parse_bool, [TRACKED],
879         "omit landing pads for unwinding"),
880     debug_llvm: bool = (false, parse_bool, [UNTRACKED],
881         "enable debug output from LLVM"),
882     meta_stats: bool = (false, parse_bool, [UNTRACKED],
883         "gather metadata statistics"),
884     print_link_args: bool = (false, parse_bool, [UNTRACKED],
885         "print the arguments passed to the linker"),
886     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
887         "prints the llvm optimization passes being run"),
888     ast_json: bool = (false, parse_bool, [UNTRACKED],
889         "print the AST as JSON and halt"),
890     ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
891         "print the pre-expansion AST as JSON and halt"),
892     ls: bool = (false, parse_bool, [UNTRACKED],
893         "list the symbols defined by a library crate"),
894     save_analysis: bool = (false, parse_bool, [UNTRACKED],
895         "write syntax and type analysis (in JSON format) information, in \
896          addition to normal output"),
897     save_analysis_csv: bool = (false, parse_bool, [UNTRACKED],
898         "write syntax and type analysis (in CSV format) information, in addition to normal output"),
899     save_analysis_api: bool = (false, parse_bool, [UNTRACKED],
900         "write syntax and type analysis information for opaque libraries (in JSON format), \
901          in addition to normal output"),
902     print_move_fragments: bool = (false, parse_bool, [UNTRACKED],
903         "print out move-fragment data for every fn"),
904     flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
905         "include loan analysis data in --unpretty flowgraph output"),
906     flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
907         "include move analysis data in --unpretty flowgraph output"),
908     flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
909         "include assignment analysis data in --unpretty flowgraph output"),
910     flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
911         "include all dataflow analysis data in --unpretty flowgraph output"),
912     print_region_graph: bool = (false, parse_bool, [UNTRACKED],
913          "prints region inference graph. \
914           Use with RUST_REGION_GRAPH=help for more info"),
915     parse_only: bool = (false, parse_bool, [UNTRACKED],
916           "parse only; do not compile, assemble, or link"),
917     no_trans: bool = (false, parse_bool, [TRACKED],
918           "run all passes except translation; no output"),
919     treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
920           "treat all errors that occur as bugs"),
921     continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
922           "attempt to recover from parse errors (experimental)"),
923     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
924           "enable incremental compilation (experimental)"),
925     incremental_cc: bool = (false, parse_bool, [UNTRACKED],
926           "enable cross-crate incremental compilation (even more experimental)"),
927     incremental_info: bool = (false, parse_bool, [UNTRACKED],
928         "print high-level information about incremental reuse (or the lack thereof)"),
929     incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
930         "dump hash information in textual format to stdout"),
931     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
932           "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
933     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
934           "enable queries of the dependency graph for regression testing"),
935     no_analysis: bool = (false, parse_bool, [UNTRACKED],
936           "parse and expand the source, but run no analysis"),
937     extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
938         "load extra plugins"),
939     unstable_options: bool = (false, parse_bool, [UNTRACKED],
940           "adds unstable command line options to rustc interface"),
941     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
942           "force overflow checks on or off"),
943     trace_macros: bool = (false, parse_bool, [UNTRACKED],
944           "for every macro invocation, print its name and arguments"),
945     debug_macros: bool = (false, parse_bool, [TRACKED],
946           "emit line numbers debug info inside macros"),
947     enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
948           "force nonzeroing move optimization on"),
949     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
950           "don't clear the hygiene data after analysis"),
951     keep_ast: bool = (false, parse_bool, [UNTRACKED],
952           "keep the AST after lowering it to HIR"),
953     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
954           "show spans for compiler debugging (expr|pat|ty)"),
955     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
956           "print layout information for each type encountered"),
957     print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
958           "print the result of the translation item collection pass"),
959     mir_opt_level: usize = (1, parse_uint, [TRACKED],
960           "set the MIR optimization level (0-3, default: 1)"),
961     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
962           "dump MIR state at various points in translation"),
963     dump_mir_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
964           "the directory the MIR is dumped into"),
965     perf_stats: bool = (false, parse_bool, [UNTRACKED],
966           "print some performance-related statistics"),
967     hir_stats: bool = (false, parse_bool, [UNTRACKED],
968           "print some statistics about AST and HIR"),
969     mir_stats: bool = (false, parse_bool, [UNTRACKED],
970           "print some statistics about MIR"),
971     always_encode_mir: bool = (false, parse_bool, [TRACKED],
972           "encode MIR of all functions into the crate metadata"),
973     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
974           "pass `-install_name @rpath/...` to the macOS linker"),
975     sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
976                                    "Use a sanitizer"),
977 }
978
979 pub fn default_lib_output() -> CrateType {
980     CrateTypeRlib
981 }
982
983 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
984     let end = &sess.target.target.target_endian;
985     let arch = &sess.target.target.arch;
986     let wordsz = &sess.target.target.target_pointer_width;
987     let os = &sess.target.target.target_os;
988     let env = &sess.target.target.target_env;
989     let vendor = &sess.target.target.target_vendor;
990     let min_atomic_width = sess.target.target.min_atomic_width();
991     let max_atomic_width = sess.target.target.max_atomic_width();
992
993     let mut ret = HashSet::new();
994     // Target bindings.
995     ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
996     if let Some(ref fam) = sess.target.target.options.target_family {
997         ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
998         if fam == "windows" || fam == "unix" {
999             ret.insert((Symbol::intern(fam), None));
1000         }
1001     }
1002     ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1003     ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1004     ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
1005     ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1006     ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
1007     if sess.target.target.options.has_elf_tls {
1008         ret.insert((Symbol::intern("target_thread_local"), None));
1009     }
1010     for &i in &[8, 16, 32, 64, 128] {
1011         if i >= min_atomic_width && i <= max_atomic_width {
1012             let s = i.to_string();
1013             ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
1014             if &s == wordsz {
1015                 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
1016             }
1017         }
1018     }
1019     if sess.opts.debug_assertions {
1020         ret.insert((Symbol::intern("debug_assertions"), None));
1021     }
1022     if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1023         ret.insert((Symbol::intern("proc_macro"), None));
1024     }
1025     return ret;
1026 }
1027
1028 pub fn build_configuration(sess: &Session,
1029                            mut user_cfg: ast::CrateConfig)
1030                            -> ast::CrateConfig {
1031     // Combine the configuration requested by the session (command line) with
1032     // some default and generated configuration items
1033     let default_cfg = default_configuration(sess);
1034     // If the user wants a test runner, then add the test cfg
1035     if sess.opts.test {
1036         user_cfg.insert((Symbol::intern("test"), None));
1037     }
1038     user_cfg.extend(default_cfg.iter().cloned());
1039     user_cfg
1040 }
1041
1042 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1043     let target = match Target::search(&opts.target_triple) {
1044         Ok(t) => t,
1045         Err(e) => {
1046             sp.struct_fatal(&format!("Error loading target specification: {}", e))
1047                 .help("Use `--print target-list` for a list of built-in targets")
1048                 .emit();
1049             panic!(FatalError);
1050         }
1051     };
1052
1053     let (int_type, uint_type) = match &target.target_pointer_width[..] {
1054         "16" => (ast::IntTy::I16, ast::UintTy::U16),
1055         "32" => (ast::IntTy::I32, ast::UintTy::U32),
1056         "64" => (ast::IntTy::I64, ast::UintTy::U64),
1057         w    => panic!(sp.fatal(&format!("target specification was invalid: \
1058                                           unrecognized target-pointer-width {}", w))),
1059     };
1060
1061     Config {
1062         target: target,
1063         int_type: int_type,
1064         uint_type: uint_type,
1065     }
1066 }
1067
1068 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1069 pub enum OptionStability {
1070     Stable,
1071
1072     // FIXME: historically there were some options which were either `-Z` or
1073     //        required the `-Z unstable-options` flag, which were all intended
1074     //        to be unstable. Unfortunately we didn't actually gate usage of
1075     //        these options on the stable compiler, so we still allow them there
1076     //        today. There are some warnings printed out about this in the
1077     //        driver.
1078     UnstableButNotReally,
1079
1080     Unstable,
1081 }
1082
1083 #[derive(Clone, PartialEq, Eq)]
1084 pub struct RustcOptGroup {
1085     pub opt_group: getopts::OptGroup,
1086     pub stability: OptionStability,
1087 }
1088
1089 impl RustcOptGroup {
1090     pub fn is_stable(&self) -> bool {
1091         self.stability == OptionStability::Stable
1092     }
1093
1094     pub fn stable(g: getopts::OptGroup) -> RustcOptGroup {
1095         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
1096     }
1097
1098     #[allow(dead_code)] // currently we have no "truly unstable" options
1099     pub fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
1100         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
1101     }
1102
1103     fn unstable_bnr(g: getopts::OptGroup) -> RustcOptGroup {
1104         RustcOptGroup {
1105             opt_group: g,
1106             stability: OptionStability::UnstableButNotReally,
1107         }
1108     }
1109 }
1110
1111 // The `opt` local module holds wrappers around the `getopts` API that
1112 // adds extra rustc-specific metadata to each option; such metadata
1113 // is exposed by .  The public
1114 // functions below ending with `_u` are the functions that return
1115 // *unstable* options, i.e. options that are only enabled when the
1116 // user also passes the `-Z unstable-options` debugging flag.
1117 mod opt {
1118     // The `fn opt_u` etc below are written so that we can use them
1119     // in the future; do not warn about them not being used right now.
1120     #![allow(dead_code)]
1121
1122     use getopts;
1123     use super::RustcOptGroup;
1124
1125     pub type R = RustcOptGroup;
1126     pub type S<'a> = &'a str;
1127
1128     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
1129     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
1130     fn unstable_bnr(g: getopts::OptGroup) -> R { RustcOptGroup::unstable_bnr(g) }
1131
1132     pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1133         stable(getopts::optopt(a, b, c, d))
1134     }
1135     pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1136         stable(getopts::optmulti(a, b, c, d))
1137     }
1138     pub fn flag_s(a: S, b: S, c: S) -> R {
1139         stable(getopts::optflag(a, b, c))
1140     }
1141     pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1142         stable(getopts::optflagopt(a, b, c, d))
1143     }
1144     pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1145         stable(getopts::optflagmulti(a, b, c))
1146     }
1147
1148     pub fn opt(a: S, b: S, c: S, d: S) -> R {
1149         unstable(getopts::optopt(a, b, c, d))
1150     }
1151     pub fn multi(a: S, b: S, c: S, d: S) -> R {
1152         unstable(getopts::optmulti(a, b, c, d))
1153     }
1154     pub fn flag(a: S, b: S, c: S) -> R {
1155         unstable(getopts::optflag(a, b, c))
1156     }
1157     pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1158         unstable(getopts::optflagopt(a, b, c, d))
1159     }
1160     pub fn flagmulti(a: S, b: S, c: S) -> R {
1161         unstable(getopts::optflagmulti(a, b, c))
1162     }
1163
1164     // Do not use these functions for any new options added to the compiler, all
1165     // new options should use the `*_u` variants above to be truly unstable.
1166     pub fn opt_ubnr(a: S, b: S, c: S, d: S) -> R {
1167         unstable_bnr(getopts::optopt(a, b, c, d))
1168     }
1169     pub fn multi_ubnr(a: S, b: S, c: S, d: S) -> R {
1170         unstable_bnr(getopts::optmulti(a, b, c, d))
1171     }
1172     pub fn flag_ubnr(a: S, b: S, c: S) -> R {
1173         unstable_bnr(getopts::optflag(a, b, c))
1174     }
1175     pub fn flagopt_ubnr(a: S, b: S, c: S, d: S) -> R {
1176         unstable_bnr(getopts::optflagopt(a, b, c, d))
1177     }
1178     pub fn flagmulti_ubnr(a: S, b: S, c: S) -> R {
1179         unstable_bnr(getopts::optflagmulti(a, b, c))
1180     }
1181 }
1182
1183 /// Returns the "short" subset of the rustc command line options,
1184 /// including metadata for each option, such as whether the option is
1185 /// part of the stable long-term interface for rustc.
1186 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1187     let mut print_opts = vec!["crate-name", "file-names", "sysroot", "cfg",
1188                               "target-list", "target-cpus", "target-features",
1189                               "relocation-models", "code-models"];
1190     if nightly_options::is_nightly_build() {
1191         print_opts.push("target-spec-json");
1192     }
1193
1194     vec![
1195         opt::flag_s("h", "help", "Display this message"),
1196         opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1197         opt::multi_s("L", "",   "Add a directory to the library search path. The
1198                              optional KIND can be one of dependency, crate, native,
1199                              framework or all (the default).", "[KIND=]PATH"),
1200         opt::multi_s("l", "",   "Link the generated crate(s) to the specified native
1201                              library NAME. The optional KIND can be one of
1202                              static, dylib, or framework. If omitted, dylib is
1203                              assumed.", "[KIND=]NAME"),
1204         opt::multi_s("", "crate-type", "Comma separated list of types of crates
1205                                     for the compiler to emit",
1206                    "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
1207         opt::opt_s("", "crate-name", "Specify the name of the crate being built",
1208                "NAME"),
1209         opt::multi_s("", "emit", "Comma separated list of types of output for \
1210                               the compiler to emit",
1211                  "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info]"),
1212         opt::multi_s("", "print", "Comma separated list of compiler information to \
1213                                print on stdout", &format!("[{}]",
1214                                &print_opts.join("|"))),
1215         opt::flagmulti_s("g",  "",  "Equivalent to -C debuginfo=2"),
1216         opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1217         opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1218         opt::opt_s("",  "out-dir", "Write output to compiler-chosen filename \
1219                                 in <dir>", "DIR"),
1220         opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1221                                message", "OPT"),
1222         opt::flag_s("", "test", "Build a test harness"),
1223         opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1224         opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1225         opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1226         opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1227         opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1228         opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1229                                      More restrictive lints are capped at this \
1230                                      level", "LEVEL"),
1231         opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1232         opt::flag_s("V", "version", "Print version info and exit"),
1233         opt::flag_s("v", "verbose", "Use verbose output"),
1234     ]
1235 }
1236
1237 /// Returns all rustc command line options, including metadata for
1238 /// each option, such as whether the option is part of the stable
1239 /// long-term interface for rustc.
1240 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1241     let mut opts = rustc_short_optgroups();
1242     opts.extend_from_slice(&[
1243         opt::multi_s("", "extern", "Specify where an external rust library is located",
1244                      "NAME=PATH"),
1245         opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1246         opt::multi_ubnr("Z", "", "Set internal debugging options", "FLAG"),
1247         opt::opt_s("", "error-format",
1248                       "How errors and other messages are produced",
1249                       "human|json"),
1250         opt::opt_s("", "color", "Configure coloring of output:
1251                                  auto   = colorize, if output goes to a tty (default);
1252                                  always = always colorize output;
1253                                  never  = never colorize output", "auto|always|never"),
1254
1255         opt::flagopt_ubnr("", "pretty",
1256                           "Pretty-print the input instead of compiling;
1257                            valid types are: `normal` (un-annotated source),
1258                            `expanded` (crates expanded), or
1259                            `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1260                           "TYPE"),
1261         opt::flagopt_ubnr("", "unpretty",
1262                           "Present the input source, unstable (and less-pretty) variants;
1263                            valid types are any of the types for `--pretty`, as well as:
1264                            `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1265                            `everybody_loops` (all function bodies replaced with `loop {}`),
1266                            `hir` (the HIR), `hir,identified`, or
1267                            `hir,typed` (HIR with types for each node).",
1268                           "TYPE"),
1269
1270         // new options here should **not** use the `_ubnr` functions, all new
1271         // unstable options should use the short variants to indicate that they
1272         // are truly unstable. All `_ubnr` flags are just that way because they
1273         // were so historically.
1274         //
1275         // You may also wish to keep this comment at the bottom of this list to
1276         // ensure that others see it.
1277     ]);
1278     opts
1279 }
1280
1281 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1282 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1283     cfgspecs.into_iter().map(|s| {
1284         let sess = parse::ParseSess::new();
1285         let mut parser =
1286             parse::new_parser_from_source_str(&sess, "cfgspec".to_string(), s.to_string());
1287
1288         let meta_item = panictry!(parser.parse_meta_item());
1289
1290         if parser.token != token::Eof {
1291             early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
1292         } else if meta_item.is_meta_item_list() {
1293             let msg =
1294                 format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
1295             early_error(ErrorOutputType::default(), &msg)
1296         }
1297
1298         (meta_item.name(), meta_item.value_str())
1299     }).collect::<ast::CrateConfig>()
1300 }
1301
1302 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1303                                               -> (Options, ast::CrateConfig) {
1304     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1305         Some("auto")   => ColorConfig::Auto,
1306         Some("always") => ColorConfig::Always,
1307         Some("never")  => ColorConfig::Never,
1308
1309         None => ColorConfig::Auto,
1310
1311         Some(arg) => {
1312             early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1313                                                               always or never (instead was `{}`)",
1314                                                             arg))
1315         }
1316     };
1317
1318     // We need the opts_present check because the driver will send us Matches
1319     // with only stable options if no unstable options are used. Since error-format
1320     // is unstable, it will not be present. We have to use opts_present not
1321     // opt_present because the latter will panic.
1322     let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1323         match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1324             Some("human")   => ErrorOutputType::HumanReadable(color),
1325             Some("json") => ErrorOutputType::Json,
1326
1327             None => ErrorOutputType::HumanReadable(color),
1328
1329             Some(arg) => {
1330                 early_error(ErrorOutputType::HumanReadable(color),
1331                             &format!("argument for --error-format must be human or json (instead \
1332                                       was `{}`)",
1333                                      arg))
1334             }
1335         }
1336     } else {
1337         ErrorOutputType::HumanReadable(color)
1338     };
1339
1340     let unparsed_crate_types = matches.opt_strs("crate-type");
1341     let (crate_types, emit_metadata) = parse_crate_types_from_list(unparsed_crate_types)
1342         .unwrap_or_else(|e| early_error(error_format, &e[..]));
1343
1344     let mut lint_opts = vec![];
1345     let mut describe_lints = false;
1346
1347     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1348         for lint_name in matches.opt_strs(level.as_str()) {
1349             if lint_name == "help" {
1350                 describe_lints = true;
1351             } else {
1352                 lint_opts.push((lint_name.replace("-", "_"), level));
1353             }
1354         }
1355     }
1356
1357     let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1358         lint::Level::from_str(&cap).unwrap_or_else(|| {
1359             early_error(error_format, &format!("unknown lint level: `{}`", cap))
1360         })
1361     });
1362
1363     let debugging_opts = build_debugging_options(matches, error_format);
1364
1365     let mut output_types = BTreeMap::new();
1366     if !debugging_opts.parse_only {
1367         for list in matches.opt_strs("emit") {
1368             for output_type in list.split(',') {
1369                 let mut parts = output_type.splitn(2, '=');
1370                 let output_type = match parts.next().unwrap() {
1371                     "asm" => OutputType::Assembly,
1372                     "llvm-ir" => OutputType::LlvmAssembly,
1373                     "llvm-bc" => OutputType::Bitcode,
1374                     "obj" => OutputType::Object,
1375                     "metadata" => OutputType::Metadata,
1376                     "link" => OutputType::Exe,
1377                     "dep-info" => OutputType::DepInfo,
1378                     part => {
1379                         early_error(error_format, &format!("unknown emission type: `{}`",
1380                                                     part))
1381                     }
1382                 };
1383                 let path = parts.next().map(PathBuf::from);
1384                 output_types.insert(output_type, path);
1385             }
1386         }
1387     };
1388     if emit_metadata {
1389         output_types.insert(OutputType::Metadata, None);
1390     } else if output_types.is_empty() {
1391         output_types.insert(OutputType::Exe, None);
1392     }
1393
1394     let mut cg = build_codegen_options(matches, error_format);
1395
1396     // Issue #30063: if user requests llvm-related output to one
1397     // particular path, disable codegen-units.
1398     if matches.opt_present("o") && cg.codegen_units != 1 {
1399         let incompatible: Vec<_> = output_types.iter()
1400             .map(|ot_path| ot_path.0)
1401             .filter(|ot| {
1402                 !ot.is_compatible_with_codegen_units_and_single_output_file()
1403             }).collect();
1404         if !incompatible.is_empty() {
1405             for ot in &incompatible {
1406                 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1407                                                  -C codegen-units=N for N > 1",
1408                                                 ot.shorthand()));
1409             }
1410             early_warn(error_format, "resetting to default -C codegen-units=1");
1411             cg.codegen_units = 1;
1412         }
1413     }
1414
1415     if cg.codegen_units < 1 {
1416         early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1417     }
1418
1419     let mut prints = Vec::<PrintRequest>::new();
1420     if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1421         prints.push(PrintRequest::TargetCPUs);
1422         cg.target_cpu = None;
1423     };
1424     if cg.target_feature == "help" {
1425         prints.push(PrintRequest::TargetFeatures);
1426         cg.target_feature = "".to_string();
1427     }
1428     if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1429         prints.push(PrintRequest::RelocationModels);
1430         cg.relocation_model = None;
1431     }
1432     if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1433         prints.push(PrintRequest::CodeModels);
1434         cg.code_model = None;
1435     }
1436
1437     let cg = cg;
1438
1439     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1440     let target = matches.opt_str("target").unwrap_or(
1441         host_triple().to_string());
1442     let opt_level = {
1443         if matches.opt_present("O") {
1444             if cg.opt_level.is_some() {
1445                 early_error(error_format, "-O and -C opt-level both provided");
1446             }
1447             OptLevel::Default
1448         } else {
1449             match (cg.opt_level.as_ref().map(String::as_ref),
1450                    nightly_options::is_nightly_build()) {
1451                 (None, _) => OptLevel::No,
1452                 (Some("0"), _) => OptLevel::No,
1453                 (Some("1"), _) => OptLevel::Less,
1454                 (Some("2"), _) => OptLevel::Default,
1455                 (Some("3"), _) => OptLevel::Aggressive,
1456                 (Some("s"), true) => OptLevel::Size,
1457                 (Some("z"), true) => OptLevel::SizeMin,
1458                 (Some("s"), false) | (Some("z"), false) => {
1459                     early_error(error_format, &format!("the optimizations s or z are only \
1460                                                         accepted on the nightly compiler"));
1461                 },
1462                 (Some(arg), _) => {
1463                     early_error(error_format, &format!("optimization level needs to be \
1464                                                       between 0-3 (instead was `{}`)",
1465                                                      arg));
1466                 }
1467             }
1468         }
1469     };
1470     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1471     let debuginfo = if matches.opt_present("g") {
1472         if cg.debuginfo.is_some() {
1473             early_error(error_format, "-g and -C debuginfo both provided");
1474         }
1475         FullDebugInfo
1476     } else {
1477         match cg.debuginfo {
1478             None | Some(0) => NoDebugInfo,
1479             Some(1) => LimitedDebugInfo,
1480             Some(2) => FullDebugInfo,
1481             Some(arg) => {
1482                 early_error(error_format, &format!("debug info level needs to be between \
1483                                                   0-2 (instead was `{}`)",
1484                                                  arg));
1485             }
1486         }
1487     };
1488
1489     let mut search_paths = SearchPaths::new();
1490     for s in &matches.opt_strs("L") {
1491         search_paths.add_path(&s[..], error_format);
1492     }
1493
1494     let libs = matches.opt_strs("l").into_iter().map(|s| {
1495         // Parse string of the form "[KIND=]lib[:new_name]",
1496         // where KIND is one of "dylib", "framework", "static".
1497         let mut parts = s.splitn(2, '=');
1498         let kind = parts.next().unwrap();
1499         let (name, kind) = match (parts.next(), kind) {
1500             (None, name) => (name, None),
1501             (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
1502             (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
1503             (Some(name), "static") => (name, Some(cstore::NativeStatic)),
1504             (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
1505             (_, s) => {
1506                 early_error(error_format, &format!("unknown library kind `{}`, expected \
1507                                                   one of dylib, framework, or static",
1508                                                  s));
1509             }
1510         };
1511         if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
1512             early_error(error_format, &format!("the library kind 'static-nobundle' is only \
1513                                                 accepted on the nightly compiler"));
1514         }
1515         let mut name_parts = name.splitn(2, ':');
1516         let name = name_parts.next().unwrap();
1517         let new_name = name_parts.next();
1518         (name.to_string(), new_name.map(|n| n.to_string()), kind)
1519     }).collect();
1520
1521     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1522     let test = matches.opt_present("test");
1523
1524     prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1525         match &*s {
1526             "crate-name" => PrintRequest::CrateName,
1527             "file-names" => PrintRequest::FileNames,
1528             "sysroot" => PrintRequest::Sysroot,
1529             "cfg" => PrintRequest::Cfg,
1530             "target-list" => PrintRequest::TargetList,
1531             "target-cpus" => PrintRequest::TargetCPUs,
1532             "target-features" => PrintRequest::TargetFeatures,
1533             "relocation-models" => PrintRequest::RelocationModels,
1534             "code-models" => PrintRequest::CodeModels,
1535             "target-spec-json" if nightly_options::is_unstable_enabled(matches)
1536                 => PrintRequest::TargetSpec,
1537             req => {
1538                 early_error(error_format, &format!("unknown print request `{}`", req))
1539             }
1540         }
1541     }));
1542
1543     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1544         early_warn(error_format, "-C remark will not show source locations without \
1545                                 --debuginfo");
1546     }
1547
1548     let mut externs = BTreeMap::new();
1549     for arg in &matches.opt_strs("extern") {
1550         let mut parts = arg.splitn(2, '=');
1551         let name = match parts.next() {
1552             Some(s) => s,
1553             None => early_error(error_format, "--extern value must not be empty"),
1554         };
1555         let location = match parts.next() {
1556             Some(s) => s,
1557             None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1558         };
1559
1560         externs.entry(name.to_string())
1561                .or_insert_with(BTreeSet::new)
1562                .insert(location.to_string());
1563     }
1564
1565     let crate_name = matches.opt_str("crate-name");
1566
1567     let incremental = debugging_opts.incremental.as_ref().map(|m| PathBuf::from(m));
1568
1569     (Options {
1570         crate_types: crate_types,
1571         optimize: opt_level,
1572         debuginfo: debuginfo,
1573         lint_opts: lint_opts,
1574         lint_cap: lint_cap,
1575         describe_lints: describe_lints,
1576         output_types: OutputTypes(output_types),
1577         search_paths: search_paths,
1578         maybe_sysroot: sysroot_opt,
1579         target_triple: target,
1580         test: test,
1581         incremental: incremental,
1582         debugging_opts: debugging_opts,
1583         prints: prints,
1584         cg: cg,
1585         error_format: error_format,
1586         externs: Externs(externs),
1587         crate_name: crate_name,
1588         alt_std_name: None,
1589         libs: libs,
1590         unstable_features: UnstableFeatures::from_environment(),
1591         debug_assertions: debug_assertions,
1592         actually_rustdoc: false,
1593     },
1594     cfg)
1595 }
1596
1597 pub fn parse_crate_types_from_list(list_list: Vec<String>)
1598                                    -> Result<(Vec<CrateType>, bool), String> {
1599     let mut crate_types: Vec<CrateType> = Vec::new();
1600     let mut emit_metadata = false;
1601     for unparsed_crate_type in &list_list {
1602         for part in unparsed_crate_type.split(',') {
1603             let new_part = match part {
1604                 "lib"       => default_lib_output(),
1605                 "rlib"      => CrateTypeRlib,
1606                 "staticlib" => CrateTypeStaticlib,
1607                 "dylib"     => CrateTypeDylib,
1608                 "cdylib"    => CrateTypeCdylib,
1609                 "bin"       => CrateTypeExecutable,
1610                 "proc-macro" => CrateTypeProcMacro,
1611                 // FIXME(#38640) remove this when Cargo is fixed.
1612                 "metadata"  => {
1613                     early_warn(ErrorOutputType::default(), "--crate-type=metadata is deprecated, \
1614                                                             prefer --emit=metadata");
1615                     emit_metadata = true;
1616                     CrateTypeRlib
1617                 }
1618                 _ => {
1619                     return Err(format!("unknown crate type: `{}`",
1620                                        part));
1621                 }
1622             };
1623             if !crate_types.contains(&new_part) {
1624                 crate_types.push(new_part)
1625             }
1626         }
1627     }
1628
1629     return Ok((crate_types, emit_metadata));
1630 }
1631
1632 pub mod nightly_options {
1633     use getopts;
1634     use syntax::feature_gate::UnstableFeatures;
1635     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
1636     use session::{early_error, early_warn};
1637
1638     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
1639         is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
1640     }
1641
1642     pub fn is_nightly_build() -> bool {
1643         UnstableFeatures::from_environment().is_nightly_build()
1644     }
1645
1646     pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
1647         let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
1648         let really_allows_unstable_options = UnstableFeatures::from_environment()
1649             .is_nightly_build();
1650
1651         for opt in flags.iter() {
1652             if opt.stability == OptionStability::Stable {
1653                 continue
1654             }
1655             let opt_name = if opt.opt_group.long_name.is_empty() {
1656                 &opt.opt_group.short_name
1657             } else {
1658                 &opt.opt_group.long_name
1659             };
1660             if !matches.opt_present(opt_name) {
1661                 continue
1662             }
1663             if opt_name != "Z" && !has_z_unstable_option {
1664                 early_error(ErrorOutputType::default(),
1665                             &format!("the `-Z unstable-options` flag must also be passed to enable \
1666                                       the flag `{}`",
1667                                      opt_name));
1668             }
1669             if really_allows_unstable_options {
1670                 continue
1671             }
1672             match opt.stability {
1673                 OptionStability::Unstable => {
1674                     let msg = format!("the option `{}` is only accepted on the \
1675                                        nightly compiler", opt_name);
1676                     early_error(ErrorOutputType::default(), &msg);
1677                 }
1678                 OptionStability::UnstableButNotReally => {
1679                     let msg = format!("the option `{}` is unstable and should \
1680                                        only be used on the nightly compiler, but \
1681                                        it is currently accepted for backwards \
1682                                        compatibility; this will soon change, \
1683                                        see issue #31847 for more details",
1684                                       opt_name);
1685                     early_warn(ErrorOutputType::default(), &msg);
1686                 }
1687                 OptionStability::Stable => {}
1688             }
1689         }
1690     }
1691 }
1692
1693 impl fmt::Display for CrateType {
1694     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1695         match *self {
1696             CrateTypeExecutable => "bin".fmt(f),
1697             CrateTypeDylib => "dylib".fmt(f),
1698             CrateTypeRlib => "rlib".fmt(f),
1699             CrateTypeStaticlib => "staticlib".fmt(f),
1700             CrateTypeCdylib => "cdylib".fmt(f),
1701             CrateTypeProcMacro => "proc-macro".fmt(f),
1702         }
1703     }
1704 }
1705
1706 /// Commandline arguments passed to the compiler have to be incorporated with
1707 /// the dependency tracking system for incremental compilation. This module
1708 /// provides some utilities to make this more convenient.
1709 ///
1710 /// The values of all commandline arguments that are relevant for dependency
1711 /// tracking are hashed into a single value that determines whether the
1712 /// incremental compilation cache can be re-used or not. This hashing is done
1713 /// via the DepTrackingHash trait defined below, since the standard Hash
1714 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
1715 /// the hash of which is order dependent, but we might not want the order of
1716 /// arguments to make a difference for the hash).
1717 ///
1718 /// However, since the value provided by Hash::hash often *is* suitable,
1719 /// especially for primitive types, there is the
1720 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
1721 /// Hash implementation for DepTrackingHash. It's important though that
1722 /// we have an opt-in scheme here, so one is hopefully forced to think about
1723 /// how the hash should be calculated when adding a new commandline argument.
1724 mod dep_tracking {
1725     use lint;
1726     use middle::cstore;
1727     use session::search_paths::{PathKind, SearchPaths};
1728     use std::collections::BTreeMap;
1729     use std::hash::Hash;
1730     use std::path::PathBuf;
1731     use std::collections::hash_map::DefaultHasher;
1732     use super::{Passes, CrateType, OptLevel, DebugInfoLevel,
1733                 OutputTypes, Externs, ErrorOutputType, Sanitizer};
1734     use syntax::feature_gate::UnstableFeatures;
1735     use rustc_back::PanicStrategy;
1736
1737     pub trait DepTrackingHash {
1738         fn hash(&self, &mut DefaultHasher, ErrorOutputType);
1739     }
1740
1741     macro_rules! impl_dep_tracking_hash_via_hash {
1742         ($t:ty) => (
1743             impl DepTrackingHash for $t {
1744                 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1745                     Hash::hash(self, hasher);
1746                 }
1747             }
1748         )
1749     }
1750
1751     macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
1752         ($t:ty) => (
1753             impl DepTrackingHash for Vec<$t> {
1754                 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1755                     let mut elems: Vec<&$t> = self.iter().collect();
1756                     elems.sort();
1757                     Hash::hash(&elems.len(), hasher);
1758                     for (index, elem) in elems.iter().enumerate() {
1759                         Hash::hash(&index, hasher);
1760                         DepTrackingHash::hash(*elem, hasher, error_format);
1761                     }
1762                 }
1763             }
1764         );
1765     }
1766
1767     impl_dep_tracking_hash_via_hash!(bool);
1768     impl_dep_tracking_hash_via_hash!(usize);
1769     impl_dep_tracking_hash_via_hash!(String);
1770     impl_dep_tracking_hash_via_hash!(lint::Level);
1771     impl_dep_tracking_hash_via_hash!(Option<bool>);
1772     impl_dep_tracking_hash_via_hash!(Option<usize>);
1773     impl_dep_tracking_hash_via_hash!(Option<String>);
1774     impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
1775     impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
1776     impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
1777     impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
1778     impl_dep_tracking_hash_via_hash!(CrateType);
1779     impl_dep_tracking_hash_via_hash!(PanicStrategy);
1780     impl_dep_tracking_hash_via_hash!(Passes);
1781     impl_dep_tracking_hash_via_hash!(OptLevel);
1782     impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
1783     impl_dep_tracking_hash_via_hash!(UnstableFeatures);
1784     impl_dep_tracking_hash_via_hash!(Externs);
1785     impl_dep_tracking_hash_via_hash!(OutputTypes);
1786     impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
1787     impl_dep_tracking_hash_via_hash!(Sanitizer);
1788     impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
1789
1790     impl_dep_tracking_hash_for_sortable_vec_of!(String);
1791     impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
1792     impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
1793     impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
1794                                                  Option<cstore::NativeLibraryKind>));
1795     impl DepTrackingHash for SearchPaths {
1796         fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1797             let mut elems: Vec<_> = self
1798                 .iter(PathKind::All)
1799                 .collect();
1800             elems.sort();
1801             Hash::hash(&elems, hasher);
1802         }
1803     }
1804
1805     impl<T1, T2> DepTrackingHash for (T1, T2)
1806         where T1: DepTrackingHash,
1807               T2: DepTrackingHash
1808     {
1809         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1810             Hash::hash(&0, hasher);
1811             DepTrackingHash::hash(&self.0, hasher, error_format);
1812             Hash::hash(&1, hasher);
1813             DepTrackingHash::hash(&self.1, hasher, error_format);
1814         }
1815     }
1816
1817     impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
1818         where T1: DepTrackingHash,
1819               T2: DepTrackingHash,
1820               T3: DepTrackingHash
1821     {
1822         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1823             Hash::hash(&0, hasher);
1824             DepTrackingHash::hash(&self.0, hasher, error_format);
1825             Hash::hash(&1, hasher);
1826             DepTrackingHash::hash(&self.1, hasher, error_format);
1827             Hash::hash(&2, hasher);
1828             DepTrackingHash::hash(&self.2, hasher, error_format);
1829         }
1830     }
1831
1832     // This is a stable hash because BTreeMap is a sorted container
1833     pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
1834                        hasher: &mut DefaultHasher,
1835                        error_format: ErrorOutputType) {
1836         for (key, sub_hash) in sub_hashes {
1837             // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
1838             // the keys, as they are just plain strings
1839             Hash::hash(&key.len(), hasher);
1840             Hash::hash(key, hasher);
1841             sub_hash.hash(hasher, error_format);
1842         }
1843     }
1844 }
1845
1846 #[cfg(test)]
1847 mod tests {
1848     use dep_graph::DepGraph;
1849     use errors;
1850     use getopts::{getopts, OptGroup};
1851     use lint;
1852     use middle::cstore::{self, DummyCrateStore};
1853     use session::config::{build_configuration, build_session_options_and_crate_config};
1854     use session::build_session;
1855     use std::collections::{BTreeMap, BTreeSet};
1856     use std::iter::FromIterator;
1857     use std::path::PathBuf;
1858     use std::rc::Rc;
1859     use super::{OutputType, OutputTypes, Externs};
1860     use rustc_back::PanicStrategy;
1861     use syntax::symbol::Symbol;
1862
1863     fn optgroups() -> Vec<OptGroup> {
1864         super::rustc_optgroups().into_iter()
1865                                 .map(|a| a.opt_group)
1866                                 .collect()
1867     }
1868
1869     fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
1870         BTreeMap::from_iter(entries.into_iter())
1871     }
1872
1873     fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
1874         BTreeSet::from_iter(entries.into_iter())
1875     }
1876
1877     // When the user supplies --test we should implicitly supply --cfg test
1878     #[test]
1879     fn test_switch_implies_cfg_test() {
1880         let dep_graph = DepGraph::new(false);
1881         let matches =
1882             &match getopts(&["--test".to_string()], &optgroups()) {
1883               Ok(m) => m,
1884               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1885             };
1886         let registry = errors::registry::Registry::new(&[]);
1887         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
1888         let sess = build_session(sessopts, &dep_graph, None, registry, Rc::new(DummyCrateStore));
1889         let cfg = build_configuration(&sess, cfg);
1890         assert!(cfg.contains(&(Symbol::intern("test"), None)));
1891     }
1892
1893     // When the user supplies --test and --cfg test, don't implicitly add
1894     // another --cfg test
1895     #[test]
1896     fn test_switch_implies_cfg_test_unless_cfg_test() {
1897         let dep_graph = DepGraph::new(false);
1898         let matches =
1899             &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1900                            &optgroups()) {
1901               Ok(m) => m,
1902               Err(f) => {
1903                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1904               }
1905             };
1906         let registry = errors::registry::Registry::new(&[]);
1907         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
1908         let sess = build_session(sessopts, &dep_graph, None, registry,
1909                                  Rc::new(DummyCrateStore));
1910         let cfg = build_configuration(&sess, cfg);
1911         let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
1912         assert!(test_items.next().is_some());
1913         assert!(test_items.next().is_none());
1914     }
1915
1916     #[test]
1917     fn test_can_print_warnings() {
1918         let dep_graph = DepGraph::new(false);
1919         {
1920             let matches = getopts(&[
1921                 "-Awarnings".to_string()
1922             ], &optgroups()).unwrap();
1923             let registry = errors::registry::Registry::new(&[]);
1924             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1925             let sess = build_session(sessopts, &dep_graph, None, registry,
1926                                      Rc::new(DummyCrateStore));
1927             assert!(!sess.diagnostic().can_emit_warnings);
1928         }
1929
1930         {
1931             let matches = getopts(&[
1932                 "-Awarnings".to_string(),
1933                 "-Dwarnings".to_string()
1934             ], &optgroups()).unwrap();
1935             let registry = errors::registry::Registry::new(&[]);
1936             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1937             let sess = build_session(sessopts, &dep_graph, None, registry,
1938                                      Rc::new(DummyCrateStore));
1939             assert!(sess.diagnostic().can_emit_warnings);
1940         }
1941
1942         {
1943             let matches = getopts(&[
1944                 "-Adead_code".to_string()
1945             ], &optgroups()).unwrap();
1946             let registry = errors::registry::Registry::new(&[]);
1947             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1948             let sess = build_session(sessopts, &dep_graph, None, registry,
1949                                      Rc::new(DummyCrateStore));
1950             assert!(sess.diagnostic().can_emit_warnings);
1951         }
1952     }
1953
1954     #[test]
1955     fn test_output_types_tracking_hash_different_paths() {
1956         let mut v1 = super::basic_options();
1957         let mut v2 = super::basic_options();
1958         let mut v3 = super::basic_options();
1959
1960         v1.output_types = OutputTypes::new(&[(OutputType::Exe,
1961                                               Some(PathBuf::from("./some/thing")))]);
1962         v2.output_types = OutputTypes::new(&[(OutputType::Exe,
1963                                               Some(PathBuf::from("/some/thing")))]);
1964         v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
1965
1966         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
1967         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
1968         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
1969
1970         // Check clone
1971         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1972         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
1973         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
1974     }
1975
1976     #[test]
1977     fn test_output_types_tracking_hash_different_construction_order() {
1978         let mut v1 = super::basic_options();
1979         let mut v2 = super::basic_options();
1980
1981         v1.output_types = OutputTypes::new(&[
1982             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
1983             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
1984         ]);
1985
1986         v2.output_types = OutputTypes::new(&[
1987             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
1988             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
1989         ]);
1990
1991         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
1992
1993         // Check clone
1994         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1995     }
1996
1997     #[test]
1998     fn test_externs_tracking_hash_different_values() {
1999         let mut v1 = super::basic_options();
2000         let mut v2 = super::basic_options();
2001         let mut v3 = super::basic_options();
2002
2003         v1.externs = Externs::new(mk_map(vec![
2004             (String::from("a"), mk_set(vec![String::from("b"),
2005                                             String::from("c")])),
2006             (String::from("d"), mk_set(vec![String::from("e"),
2007                                             String::from("f")])),
2008         ]));
2009
2010         v2.externs = Externs::new(mk_map(vec![
2011             (String::from("a"), mk_set(vec![String::from("b"),
2012                                             String::from("c")])),
2013             (String::from("X"), mk_set(vec![String::from("e"),
2014                                             String::from("f")])),
2015         ]));
2016
2017         v3.externs = Externs::new(mk_map(vec![
2018             (String::from("a"), mk_set(vec![String::from("b"),
2019                                             String::from("c")])),
2020             (String::from("d"), mk_set(vec![String::from("X"),
2021                                             String::from("f")])),
2022         ]));
2023
2024         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2025         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2026         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2027
2028         // Check clone
2029         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2030         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2031         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2032     }
2033
2034     #[test]
2035     fn test_externs_tracking_hash_different_construction_order() {
2036         let mut v1 = super::basic_options();
2037         let mut v2 = super::basic_options();
2038         let mut v3 = super::basic_options();
2039
2040         v1.externs = Externs::new(mk_map(vec![
2041             (String::from("a"), mk_set(vec![String::from("b"),
2042                                             String::from("c")])),
2043             (String::from("d"), mk_set(vec![String::from("e"),
2044                                             String::from("f")])),
2045         ]));
2046
2047         v2.externs = Externs::new(mk_map(vec![
2048             (String::from("d"), mk_set(vec![String::from("e"),
2049                                             String::from("f")])),
2050             (String::from("a"), mk_set(vec![String::from("b"),
2051                                             String::from("c")])),
2052         ]));
2053
2054         v3.externs = Externs::new(mk_map(vec![
2055             (String::from("a"), mk_set(vec![String::from("b"),
2056                                             String::from("c")])),
2057             (String::from("d"), mk_set(vec![String::from("f"),
2058                                             String::from("e")])),
2059         ]));
2060
2061         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2062         assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2063         assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2064
2065         // Check clone
2066         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2067         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2068         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2069     }
2070
2071     #[test]
2072     fn test_lints_tracking_hash_different_values() {
2073         let mut v1 = super::basic_options();
2074         let mut v2 = super::basic_options();
2075         let mut v3 = super::basic_options();
2076
2077         v1.lint_opts = vec![(String::from("a"), lint::Allow),
2078                             (String::from("b"), lint::Warn),
2079                             (String::from("c"), lint::Deny),
2080                             (String::from("d"), lint::Forbid)];
2081
2082         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2083                             (String::from("b"), lint::Warn),
2084                             (String::from("X"), lint::Deny),
2085                             (String::from("d"), lint::Forbid)];
2086
2087         v3.lint_opts = vec![(String::from("a"), lint::Allow),
2088                             (String::from("b"), lint::Warn),
2089                             (String::from("c"), lint::Forbid),
2090                             (String::from("d"), lint::Deny)];
2091
2092         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2093         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2094         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2095
2096         // Check clone
2097         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2098         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2099         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2100     }
2101
2102     #[test]
2103     fn test_lints_tracking_hash_different_construction_order() {
2104         let mut v1 = super::basic_options();
2105         let mut v2 = super::basic_options();
2106
2107         v1.lint_opts = vec![(String::from("a"), lint::Allow),
2108                             (String::from("b"), lint::Warn),
2109                             (String::from("c"), lint::Deny),
2110                             (String::from("d"), lint::Forbid)];
2111
2112         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2113                             (String::from("c"), lint::Deny),
2114                             (String::from("b"), lint::Warn),
2115                             (String::from("d"), lint::Forbid)];
2116
2117         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2118
2119         // Check clone
2120         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2121         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2122     }
2123
2124     #[test]
2125     fn test_search_paths_tracking_hash_different_values() {
2126         let mut v1 = super::basic_options();
2127         let mut v2 = super::basic_options();
2128         let mut v3 = super::basic_options();
2129         let mut v4 = super::basic_options();
2130         let mut v5 = super::basic_options();
2131
2132         // Reference
2133         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2134         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2135         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2136         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2137         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2138
2139         // Native changed
2140         v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json);
2141         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2142         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2143         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2144         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2145
2146         // Crate changed
2147         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2148         v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json);
2149         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2150         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2151         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2152
2153         // Dependency changed
2154         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2155         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2156         v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json);
2157         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2158         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2159
2160         // Framework changed
2161         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2162         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2163         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2164         v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json);
2165         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2166
2167         // All changed
2168         v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2169         v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2170         v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2171         v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2172         v5.search_paths.add_path("all=XXX", super::ErrorOutputType::Json);
2173
2174         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2175         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2176         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2177         assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2178
2179         // Check clone
2180         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2181         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2182         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2183         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2184         assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2185     }
2186
2187     #[test]
2188     fn test_search_paths_tracking_hash_different_order() {
2189         let mut v1 = super::basic_options();
2190         let mut v2 = super::basic_options();
2191         let mut v3 = super::basic_options();
2192         let mut v4 = super::basic_options();
2193
2194         // Reference
2195         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2196         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2197         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2198         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2199         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2200
2201         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2202         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2203         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2204         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2205         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2206
2207         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2208         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2209         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2210         v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2211         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2212
2213         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2214         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2215         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2216         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2217         v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2218
2219         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2220         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2221         assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2222
2223         // Check clone
2224         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2225         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2226         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2227         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2228     }
2229
2230     #[test]
2231     fn test_native_libs_tracking_hash_different_values() {
2232         let mut v1 = super::basic_options();
2233         let mut v2 = super::basic_options();
2234         let mut v3 = super::basic_options();
2235         let mut v4 = super::basic_options();
2236
2237         // Reference
2238         v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2239                        (String::from("b"), None, Some(cstore::NativeFramework)),
2240                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2241
2242         // Change label
2243         v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2244                        (String::from("X"), None, Some(cstore::NativeFramework)),
2245                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2246
2247         // Change kind
2248         v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2249                        (String::from("b"), None, Some(cstore::NativeStatic)),
2250                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2251
2252         // Change new-name
2253         v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2254                        (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
2255                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2256
2257         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2258         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2259         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2260
2261         // Check clone
2262         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2263         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2264         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2265         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2266     }
2267
2268     #[test]
2269     fn test_native_libs_tracking_hash_different_order() {
2270         let mut v1 = super::basic_options();
2271         let mut v2 = super::basic_options();
2272         let mut v3 = super::basic_options();
2273
2274         // Reference
2275         v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2276                        (String::from("b"), None, Some(cstore::NativeFramework)),
2277                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2278
2279         v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
2280                        (String::from("a"), None, Some(cstore::NativeStatic)),
2281                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2282
2283         v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
2284                        (String::from("a"), None, Some(cstore::NativeStatic)),
2285                        (String::from("b"), None, Some(cstore::NativeFramework))];
2286
2287         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2288         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2289         assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2290
2291         // Check clone
2292         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2293         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2294         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2295     }
2296
2297     #[test]
2298     fn test_codegen_options_tracking_hash() {
2299         let reference = super::basic_options();
2300         let mut opts = super::basic_options();
2301
2302         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2303         opts.cg.ar = Some(String::from("abc"));
2304         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2305
2306         opts.cg.linker = Some(String::from("linker"));
2307         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2308
2309         opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2310         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2311
2312         opts.cg.link_dead_code = true;
2313         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2314
2315         opts.cg.rpath = true;
2316         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2317
2318         opts.cg.extra_filename = String::from("extra-filename");
2319         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2320
2321         opts.cg.codegen_units = 42;
2322         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2323
2324         opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2325                                                 String::from("pass2")]);
2326         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2327
2328         opts.cg.save_temps = true;
2329         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2330
2331
2332         // Make sure changing a [TRACKED] option changes the hash
2333         opts = reference.clone();
2334         opts.cg.lto = true;
2335         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2336
2337         opts = reference.clone();
2338         opts.cg.target_cpu = Some(String::from("abc"));
2339         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2340
2341         opts = reference.clone();
2342         opts.cg.target_feature = String::from("all the features, all of them");
2343         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2344
2345         opts = reference.clone();
2346         opts.cg.passes = vec![String::from("1"), String::from("2")];
2347         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2348
2349         opts = reference.clone();
2350         opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2351         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2352
2353         opts = reference.clone();
2354         opts.cg.overflow_checks = Some(true);
2355         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2356
2357         opts = reference.clone();
2358         opts.cg.no_prepopulate_passes = true;
2359         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2360
2361         opts = reference.clone();
2362         opts.cg.no_vectorize_loops = true;
2363         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2364
2365         opts = reference.clone();
2366         opts.cg.no_vectorize_slp = true;
2367         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2368
2369         opts = reference.clone();
2370         opts.cg.soft_float = true;
2371         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2372
2373         opts = reference.clone();
2374         opts.cg.prefer_dynamic = true;
2375         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2376
2377         opts = reference.clone();
2378         opts.cg.no_integrated_as = true;
2379         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2380
2381         opts = reference.clone();
2382         opts.cg.no_redzone = Some(true);
2383         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2384
2385         opts = reference.clone();
2386         opts.cg.relocation_model = Some(String::from("relocation model"));
2387         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2388
2389         opts = reference.clone();
2390         opts.cg.code_model = Some(String::from("code model"));
2391         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2392
2393         opts = reference.clone();
2394         opts.cg.metadata = vec![String::from("A"), String::from("B")];
2395         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2396
2397         opts = reference.clone();
2398         opts.cg.debuginfo = Some(0xdeadbeef);
2399         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2400
2401         opts = reference.clone();
2402         opts.cg.debuginfo = Some(0xba5eba11);
2403         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2404
2405         opts = reference.clone();
2406         opts.cg.debug_assertions = Some(true);
2407         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2408
2409         opts = reference.clone();
2410         opts.cg.inline_threshold = Some(0xf007ba11);
2411         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2412
2413         opts = reference.clone();
2414         opts.cg.panic = Some(PanicStrategy::Abort);
2415         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2416     }
2417
2418     #[test]
2419     fn test_debugging_options_tracking_hash() {
2420         let reference = super::basic_options();
2421         let mut opts = super::basic_options();
2422
2423         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2424         opts.debugging_opts.verbose = true;
2425         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2426         opts.debugging_opts.time_passes = true;
2427         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2428         opts.debugging_opts.count_llvm_insns = true;
2429         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2430         opts.debugging_opts.time_llvm_passes = true;
2431         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2432         opts.debugging_opts.input_stats = true;
2433         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2434         opts.debugging_opts.trans_stats = true;
2435         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2436         opts.debugging_opts.borrowck_stats = true;
2437         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2438         opts.debugging_opts.debug_llvm = true;
2439         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2440         opts.debugging_opts.meta_stats = true;
2441         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2442         opts.debugging_opts.print_link_args = true;
2443         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2444         opts.debugging_opts.print_llvm_passes = true;
2445         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2446         opts.debugging_opts.ast_json = true;
2447         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2448         opts.debugging_opts.ast_json_noexpand = true;
2449         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2450         opts.debugging_opts.ls = true;
2451         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2452         opts.debugging_opts.save_analysis = true;
2453         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2454         opts.debugging_opts.save_analysis_csv = true;
2455         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2456         opts.debugging_opts.save_analysis_api = true;
2457         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2458         opts.debugging_opts.print_move_fragments = true;
2459         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2460         opts.debugging_opts.flowgraph_print_loans = true;
2461         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2462         opts.debugging_opts.flowgraph_print_moves = true;
2463         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2464         opts.debugging_opts.flowgraph_print_assigns = true;
2465         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2466         opts.debugging_opts.flowgraph_print_all = true;
2467         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2468         opts.debugging_opts.print_region_graph = true;
2469         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2470         opts.debugging_opts.parse_only = true;
2471         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2472         opts.debugging_opts.incremental = Some(String::from("abc"));
2473         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2474         opts.debugging_opts.dump_dep_graph = true;
2475         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2476         opts.debugging_opts.query_dep_graph = true;
2477         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2478         opts.debugging_opts.no_analysis = true;
2479         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2480         opts.debugging_opts.unstable_options = true;
2481         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2482         opts.debugging_opts.trace_macros = true;
2483         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2484         opts.debugging_opts.keep_hygiene_data = true;
2485         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2486         opts.debugging_opts.keep_ast = true;
2487         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2488         opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2489         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2490         opts.debugging_opts.dump_mir = Some(String::from("abc"));
2491         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2492         opts.debugging_opts.dump_mir_dir = Some(String::from("abc"));
2493         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2494
2495         // Make sure changing a [TRACKED] option changes the hash
2496         opts = reference.clone();
2497         opts.debugging_opts.asm_comments = true;
2498         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2499
2500         opts = reference.clone();
2501         opts.debugging_opts.no_verify = true;
2502         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2503
2504         opts = reference.clone();
2505         opts.debugging_opts.no_landing_pads = true;
2506         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2507
2508         opts = reference.clone();
2509         opts.debugging_opts.no_trans = true;
2510         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2511
2512         opts = reference.clone();
2513         opts.debugging_opts.treat_err_as_bug = true;
2514         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2515
2516         opts = reference.clone();
2517         opts.debugging_opts.continue_parse_after_error = true;
2518         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2519
2520         opts = reference.clone();
2521         opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2522         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2523
2524         opts = reference.clone();
2525         opts.debugging_opts.force_overflow_checks = Some(true);
2526         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2527
2528         opts = reference.clone();
2529         opts.debugging_opts.enable_nonzeroing_move_hints = true;
2530         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2531
2532         opts = reference.clone();
2533         opts.debugging_opts.show_span = Some(String::from("abc"));
2534         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2535
2536         opts = reference.clone();
2537         opts.debugging_opts.mir_opt_level = 3;
2538         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2539     }
2540 }