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