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