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