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