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