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