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