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