]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
16522a73f56a514fa2b551f47545edc00014753f
[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::attr;
29 use syntax::parse;
30 use syntax::parse::token::InternedString;
31 use syntax::feature_gate::UnstableFeatures;
32
33 use errors::{ColorConfig, FatalError, Handler};
34
35 use getopts;
36 use std::collections::{BTreeMap, BTreeSet};
37 use std::collections::btree_map::Iter as BTreeMapIter;
38 use std::collections::btree_map::Keys as BTreeMapKeysIter;
39 use std::collections::btree_map::Values as BTreeMapValuesIter;
40
41 use std::fmt;
42 use std::hash::Hasher;
43 use std::collections::hash_map::DefaultHasher;
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 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
82 pub enum ErrorOutputType {
83     HumanReadable(ColorConfig),
84     Json,
85 }
86
87 impl Default for ErrorOutputType {
88     fn default() -> ErrorOutputType {
89         ErrorOutputType::HumanReadable(ColorConfig::Auto)
90     }
91 }
92
93 impl OutputType {
94     fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
95         match *self {
96             OutputType::Exe |
97             OutputType::DepInfo => true,
98             OutputType::Bitcode |
99             OutputType::Assembly |
100             OutputType::LlvmAssembly |
101             OutputType::Object => false,
102         }
103     }
104
105     fn shorthand(&self) -> &'static str {
106         match *self {
107             OutputType::Bitcode => "llvm-bc",
108             OutputType::Assembly => "asm",
109             OutputType::LlvmAssembly => "llvm-ir",
110             OutputType::Object => "obj",
111             OutputType::Exe => "link",
112             OutputType::DepInfo => "dep-info",
113         }
114     }
115
116     pub fn extension(&self) -> &'static str {
117         match *self {
118             OutputType::Bitcode => "bc",
119             OutputType::Assembly => "s",
120             OutputType::LlvmAssembly => "ll",
121             OutputType::Object => "o",
122             OutputType::DepInfo => "d",
123             OutputType::Exe => "",
124         }
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, 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         mir_opt_level: usize [TRACKED],
273
274         // if Some, enable incremental compilation, using the given
275         // directory to store intermediate results
276         incremental: Option<PathBuf> [UNTRACKED],
277
278         debugging_opts: DebuggingOptions [TRACKED],
279         prints: Vec<PrintRequest> [UNTRACKED],
280         cg: CodegenOptions [TRACKED],
281         // FIXME(mw): We track this for now but it actually doesn't make too
282         //            much sense: The value of this option can stay the same
283         //            while the files they refer to might have changed on disk.
284         externs: Externs [TRACKED],
285         crate_name: Option<String> [TRACKED],
286         // An optional name to use as the crate for std during std injection,
287         // written `extern crate std = "name"`. Default to "std". Used by
288         // out-of-tree drivers.
289         alt_std_name: Option<String> [TRACKED],
290         // Indicates how the compiler should treat unstable features
291         unstable_features: UnstableFeatures [TRACKED],
292
293         // Indicates whether this run of the compiler is actually rustdoc. This
294         // is currently just a hack and will be removed eventually, so please
295         // try to not rely on this too much.
296         actually_rustdoc: bool [TRACKED],
297     }
298 );
299
300 #[derive(Clone, PartialEq, Eq)]
301 pub enum PrintRequest {
302     FileNames,
303     Sysroot,
304     CrateName,
305     Cfg,
306     TargetList,
307     TargetCPUs,
308     TargetFeatures,
309     RelocationModels,
310     CodeModels,
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         mir_opt_level: 1,
438         incremental: None,
439         debugging_opts: basic_debugging_options(),
440         prints: Vec::new(),
441         cg: basic_codegen_options(),
442         error_format: ErrorOutputType::default(),
443         externs: Externs(BTreeMap::new()),
444         crate_name: None,
445         alt_std_name: None,
446         libs: Vec::new(),
447         unstable_features: UnstableFeatures::Disallow,
448         debug_assertions: true,
449         actually_rustdoc: false,
450     }
451 }
452
453 impl Options {
454     /// True if there is a reason to build the dep graph.
455     pub fn build_dep_graph(&self) -> bool {
456         self.incremental.is_some() ||
457             self.debugging_opts.dump_dep_graph ||
458             self.debugging_opts.query_dep_graph
459     }
460
461     pub fn single_codegen_unit(&self) -> bool {
462         self.incremental.is_none() ||
463         self.cg.codegen_units == 1
464     }
465 }
466
467 // The type of entry function, so
468 // users can have their own entry
469 // functions that don't start a
470 // scheduler
471 #[derive(Copy, Clone, PartialEq)]
472 pub enum EntryFnType {
473     EntryMain,
474     EntryStart,
475     EntryNone,
476 }
477
478 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
479 pub enum CrateType {
480     CrateTypeExecutable,
481     CrateTypeDylib,
482     CrateTypeRlib,
483     CrateTypeStaticlib,
484     CrateTypeCdylib,
485     CrateTypeProcMacro,
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     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
888           "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
889     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
890           "enable queries of the dependency graph for regression testing"),
891     no_analysis: bool = (false, parse_bool, [UNTRACKED],
892           "parse and expand the source, but run no analysis"),
893     extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
894         "load extra plugins"),
895     unstable_options: bool = (false, parse_bool, [UNTRACKED],
896           "adds unstable command line options to rustc interface"),
897     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
898           "force overflow checks on or off"),
899     trace_macros: bool = (false, parse_bool, [UNTRACKED],
900           "for every macro invocation, print its name and arguments"),
901     debug_macros: bool = (false, parse_bool, [TRACKED],
902           "emit line numbers debug info inside macros"),
903     enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
904           "force nonzeroing move optimization on"),
905     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
906           "don't clear the hygiene data after analysis"),
907     keep_ast: bool = (false, parse_bool, [UNTRACKED],
908           "keep the AST after lowering it to HIR"),
909     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
910           "show spans for compiler debugging (expr|pat|ty)"),
911     print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
912           "print the result of the translation item collection pass"),
913     mir_opt_level: Option<usize> = (None, parse_opt_uint, [TRACKED],
914           "set the MIR optimization level (0-3)"),
915     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
916           "dump MIR state at various points in translation"),
917     dump_mir_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
918           "the directory the MIR is dumped into"),
919     perf_stats: bool = (false, parse_bool, [UNTRACKED],
920           "print some performance-related statistics"),
921     hir_stats: bool = (false, parse_bool, [UNTRACKED],
922           "print some statistics about AST and HIR"),
923 }
924
925 pub fn default_lib_output() -> CrateType {
926     CrateTypeRlib
927 }
928
929 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
930     use syntax::parse::token::intern_and_get_ident as intern;
931
932     let end = &sess.target.target.target_endian;
933     let arch = &sess.target.target.arch;
934     let wordsz = &sess.target.target.target_pointer_width;
935     let os = &sess.target.target.target_os;
936     let env = &sess.target.target.target_env;
937     let vendor = &sess.target.target.target_vendor;
938     let max_atomic_width = sess.target.target.max_atomic_width();
939
940     let fam = if let Some(ref fam) = sess.target.target.options.target_family {
941         intern(fam)
942     } else if sess.target.target.options.is_like_windows {
943         InternedString::new("windows")
944     } else {
945         InternedString::new("unix")
946     };
947
948     let mk = attr::mk_name_value_item_str;
949     let mut ret = vec![ // Target bindings.
950         mk(InternedString::new("target_os"), intern(os)),
951         mk(InternedString::new("target_family"), fam.clone()),
952         mk(InternedString::new("target_arch"), intern(arch)),
953         mk(InternedString::new("target_endian"), intern(end)),
954         mk(InternedString::new("target_pointer_width"), intern(wordsz)),
955         mk(InternedString::new("target_env"), intern(env)),
956         mk(InternedString::new("target_vendor"), intern(vendor)),
957     ];
958     match &fam[..] {
959         "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
960         _ => (),
961     }
962     if sess.target.target.options.has_elf_tls {
963         ret.push(attr::mk_word_item(InternedString::new("target_thread_local")));
964     }
965     for &i in &[8, 16, 32, 64, 128] {
966         if i <= max_atomic_width {
967             let s = i.to_string();
968             ret.push(mk(InternedString::new("target_has_atomic"), intern(&s)));
969             if &s == wordsz {
970                 ret.push(mk(InternedString::new("target_has_atomic"), intern("ptr")));
971             }
972         }
973     }
974     if sess.opts.debug_assertions {
975         ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
976     }
977     if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
978         ret.push(attr::mk_word_item(InternedString::new("proc_macro")));
979     }
980     return ret;
981 }
982
983 pub fn append_configuration(cfg: &mut ast::CrateConfig,
984                             name: InternedString) {
985     if !cfg.iter().any(|mi| mi.name() == name) {
986         cfg.push(attr::mk_word_item(name))
987     }
988 }
989
990 pub fn build_configuration(sess: &Session,
991                            mut user_cfg: ast::CrateConfig)
992                            -> ast::CrateConfig {
993     // Combine the configuration requested by the session (command line) with
994     // some default and generated configuration items
995     let default_cfg = default_configuration(sess);
996     // If the user wants a test runner, then add the test cfg
997     if sess.opts.test {
998         append_configuration(&mut user_cfg, InternedString::new("test"))
999     }
1000     let mut v = user_cfg.into_iter().collect::<Vec<_>>();
1001     v.extend_from_slice(&default_cfg[..]);
1002     v
1003 }
1004
1005 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1006     let target = match Target::search(&opts.target_triple) {
1007         Ok(t) => t,
1008         Err(e) => {
1009             sp.struct_fatal(&format!("Error loading target specification: {}", e))
1010                 .help("Use `--print target-list` for a list of built-in targets")
1011                 .emit();
1012             panic!(FatalError);
1013         }
1014     };
1015
1016     let (int_type, uint_type) = match &target.target_pointer_width[..] {
1017         "16" => (ast::IntTy::I16, ast::UintTy::U16),
1018         "32" => (ast::IntTy::I32, ast::UintTy::U32),
1019         "64" => (ast::IntTy::I64, ast::UintTy::U64),
1020         w    => panic!(sp.fatal(&format!("target specification was invalid: \
1021                                           unrecognized target-pointer-width {}", w))),
1022     };
1023
1024     Config {
1025         target: target,
1026         int_type: int_type,
1027         uint_type: uint_type,
1028     }
1029 }
1030
1031 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1032 pub enum OptionStability {
1033     Stable,
1034
1035     // FIXME: historically there were some options which were either `-Z` or
1036     //        required the `-Z unstable-options` flag, which were all intended
1037     //        to be unstable. Unfortunately we didn't actually gate usage of
1038     //        these options on the stable compiler, so we still allow them there
1039     //        today. There are some warnings printed out about this in the
1040     //        driver.
1041     UnstableButNotReally,
1042
1043     Unstable,
1044 }
1045
1046 #[derive(Clone, PartialEq, Eq)]
1047 pub struct RustcOptGroup {
1048     pub opt_group: getopts::OptGroup,
1049     pub stability: OptionStability,
1050 }
1051
1052 impl RustcOptGroup {
1053     pub fn is_stable(&self) -> bool {
1054         self.stability == OptionStability::Stable
1055     }
1056
1057     pub fn stable(g: getopts::OptGroup) -> RustcOptGroup {
1058         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
1059     }
1060
1061     #[allow(dead_code)] // currently we have no "truly unstable" options
1062     pub fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
1063         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
1064     }
1065
1066     fn unstable_bnr(g: getopts::OptGroup) -> RustcOptGroup {
1067         RustcOptGroup {
1068             opt_group: g,
1069             stability: OptionStability::UnstableButNotReally,
1070         }
1071     }
1072 }
1073
1074 // The `opt` local module holds wrappers around the `getopts` API that
1075 // adds extra rustc-specific metadata to each option; such metadata
1076 // is exposed by .  The public
1077 // functions below ending with `_u` are the functions that return
1078 // *unstable* options, i.e. options that are only enabled when the
1079 // user also passes the `-Z unstable-options` debugging flag.
1080 mod opt {
1081     // The `fn opt_u` etc below are written so that we can use them
1082     // in the future; do not warn about them not being used right now.
1083     #![allow(dead_code)]
1084
1085     use getopts;
1086     use super::RustcOptGroup;
1087
1088     pub type R = RustcOptGroup;
1089     pub type S<'a> = &'a str;
1090
1091     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
1092     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
1093     fn unstable_bnr(g: getopts::OptGroup) -> R { RustcOptGroup::unstable_bnr(g) }
1094
1095     pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1096         stable(getopts::optopt(a, b, c, d))
1097     }
1098     pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1099         stable(getopts::optmulti(a, b, c, d))
1100     }
1101     pub fn flag_s(a: S, b: S, c: S) -> R {
1102         stable(getopts::optflag(a, b, c))
1103     }
1104     pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1105         stable(getopts::optflagopt(a, b, c, d))
1106     }
1107     pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1108         stable(getopts::optflagmulti(a, b, c))
1109     }
1110
1111     pub fn opt(a: S, b: S, c: S, d: S) -> R {
1112         unstable(getopts::optopt(a, b, c, d))
1113     }
1114     pub fn multi(a: S, b: S, c: S, d: S) -> R {
1115         unstable(getopts::optmulti(a, b, c, d))
1116     }
1117     pub fn flag(a: S, b: S, c: S) -> R {
1118         unstable(getopts::optflag(a, b, c))
1119     }
1120     pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1121         unstable(getopts::optflagopt(a, b, c, d))
1122     }
1123     pub fn flagmulti(a: S, b: S, c: S) -> R {
1124         unstable(getopts::optflagmulti(a, b, c))
1125     }
1126
1127     // Do not use these functions for any new options added to the compiler, all
1128     // new options should use the `*_u` variants above to be truly unstable.
1129     pub fn opt_ubnr(a: S, b: S, c: S, d: S) -> R {
1130         unstable_bnr(getopts::optopt(a, b, c, d))
1131     }
1132     pub fn multi_ubnr(a: S, b: S, c: S, d: S) -> R {
1133         unstable_bnr(getopts::optmulti(a, b, c, d))
1134     }
1135     pub fn flag_ubnr(a: S, b: S, c: S) -> R {
1136         unstable_bnr(getopts::optflag(a, b, c))
1137     }
1138     pub fn flagopt_ubnr(a: S, b: S, c: S, d: S) -> R {
1139         unstable_bnr(getopts::optflagopt(a, b, c, d))
1140     }
1141     pub fn flagmulti_ubnr(a: S, b: S, c: S) -> R {
1142         unstable_bnr(getopts::optflagmulti(a, b, c))
1143     }
1144 }
1145
1146 /// Returns the "short" subset of the rustc command line options,
1147 /// including metadata for each option, such as whether the option is
1148 /// part of the stable long-term interface for rustc.
1149 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
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]"),
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",
1170                  "[crate-name|file-names|sysroot|cfg|target-list|target-cpus|\
1171                    target-features|relocation-models|code-models]"),
1172         opt::flagmulti_s("g",  "",  "Equivalent to -C debuginfo=2"),
1173         opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1174         opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1175         opt::opt_s("",  "out-dir", "Write output to compiler-chosen filename \
1176                                 in <dir>", "DIR"),
1177         opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1178                                message", "OPT"),
1179         opt::flag_s("", "test", "Build a test harness"),
1180         opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1181         opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1182         opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1183         opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1184         opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1185         opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1186                                      More restrictive lints are capped at this \
1187                                      level", "LEVEL"),
1188         opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1189         opt::flag_s("V", "version", "Print version info and exit"),
1190         opt::flag_s("v", "verbose", "Use verbose output"),
1191     ]
1192 }
1193
1194 /// Returns all rustc command line options, including metadata for
1195 /// each option, such as whether the option is part of the stable
1196 /// long-term interface for rustc.
1197 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1198     let mut opts = rustc_short_optgroups();
1199     opts.extend_from_slice(&[
1200         opt::multi_s("", "extern", "Specify where an external rust library is located",
1201                      "NAME=PATH"),
1202         opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1203         opt::multi_ubnr("Z", "", "Set internal debugging options", "FLAG"),
1204         opt::opt_s("", "error-format",
1205                       "How errors and other messages are produced",
1206                       "human|json"),
1207         opt::opt_s("", "color", "Configure coloring of output:
1208                                  auto   = colorize, if output goes to a tty (default);
1209                                  always = always colorize output;
1210                                  never  = never colorize output", "auto|always|never"),
1211
1212         opt::flagopt_ubnr("", "pretty",
1213                           "Pretty-print the input instead of compiling;
1214                            valid types are: `normal` (un-annotated source),
1215                            `expanded` (crates expanded), or
1216                            `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1217                           "TYPE"),
1218         opt::flagopt_ubnr("", "unpretty",
1219                           "Present the input source, unstable (and less-pretty) variants;
1220                            valid types are any of the types for `--pretty`, as well as:
1221                            `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1222                            `everybody_loops` (all function bodies replaced with `loop {}`),
1223                            `hir` (the HIR), `hir,identified`, or
1224                            `hir,typed` (HIR with types for each node).",
1225                           "TYPE"),
1226
1227         // new options here should **not** use the `_ubnr` functions, all new
1228         // unstable options should use the short variants to indicate that they
1229         // are truly unstable. All `_ubnr` flags are just that way because they
1230         // were so historically.
1231         //
1232         // You may also wish to keep this comment at the bottom of this list to
1233         // ensure that others see it.
1234     ]);
1235     opts
1236 }
1237
1238 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1239 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1240     cfgspecs.into_iter().map(|s| {
1241         let sess = parse::ParseSess::new();
1242         let mut parser =
1243             parse::new_parser_from_source_str(&sess, "cfgspec".to_string(), s.to_string());
1244
1245         let meta_item = panictry!(parser.parse_meta_item());
1246
1247         if !parser.reader.is_eof() {
1248             early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}",
1249                                                              s))
1250         }
1251
1252         meta_item
1253     }).collect::<ast::CrateConfig>()
1254 }
1255
1256 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1257                                               -> (Options, ast::CrateConfig) {
1258     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1259         Some("auto")   => ColorConfig::Auto,
1260         Some("always") => ColorConfig::Always,
1261         Some("never")  => ColorConfig::Never,
1262
1263         None => ColorConfig::Auto,
1264
1265         Some(arg) => {
1266             early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1267                                                               always or never (instead was `{}`)",
1268                                                             arg))
1269         }
1270     };
1271
1272     // We need the opts_present check because the driver will send us Matches
1273     // with only stable options if no unstable options are used. Since error-format
1274     // is unstable, it will not be present. We have to use opts_present not
1275     // opt_present because the latter will panic.
1276     let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1277         match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1278             Some("human")   => ErrorOutputType::HumanReadable(color),
1279             Some("json") => ErrorOutputType::Json,
1280
1281             None => ErrorOutputType::HumanReadable(color),
1282
1283             Some(arg) => {
1284                 early_error(ErrorOutputType::HumanReadable(color),
1285                             &format!("argument for --error-format must be human or json (instead \
1286                                       was `{}`)",
1287                                      arg))
1288             }
1289         }
1290     } else {
1291         ErrorOutputType::HumanReadable(color)
1292     };
1293
1294     let unparsed_crate_types = matches.opt_strs("crate-type");
1295     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1296         .unwrap_or_else(|e| early_error(error_format, &e[..]));
1297
1298     let mut lint_opts = vec![];
1299     let mut describe_lints = false;
1300
1301     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1302         for lint_name in matches.opt_strs(level.as_str()) {
1303             if lint_name == "help" {
1304                 describe_lints = true;
1305             } else {
1306                 lint_opts.push((lint_name.replace("-", "_"), level));
1307             }
1308         }
1309     }
1310
1311     let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1312         lint::Level::from_str(&cap).unwrap_or_else(|| {
1313             early_error(error_format, &format!("unknown lint level: `{}`", cap))
1314         })
1315     });
1316
1317     let debugging_opts = build_debugging_options(matches, error_format);
1318
1319     let mir_opt_level = debugging_opts.mir_opt_level.unwrap_or(1);
1320
1321     let mut output_types = BTreeMap::new();
1322     if !debugging_opts.parse_only {
1323         for list in matches.opt_strs("emit") {
1324             for output_type in list.split(',') {
1325                 let mut parts = output_type.splitn(2, '=');
1326                 let output_type = match parts.next().unwrap() {
1327                     "asm" => OutputType::Assembly,
1328                     "llvm-ir" => OutputType::LlvmAssembly,
1329                     "llvm-bc" => OutputType::Bitcode,
1330                     "obj" => OutputType::Object,
1331                     "link" => OutputType::Exe,
1332                     "dep-info" => OutputType::DepInfo,
1333                     part => {
1334                         early_error(error_format, &format!("unknown emission type: `{}`",
1335                                                     part))
1336                     }
1337                 };
1338                 let path = parts.next().map(PathBuf::from);
1339                 output_types.insert(output_type, path);
1340             }
1341         }
1342     };
1343     if output_types.is_empty() {
1344         output_types.insert(OutputType::Exe, None);
1345     }
1346
1347     let mut cg = build_codegen_options(matches, error_format);
1348
1349     // Issue #30063: if user requests llvm-related output to one
1350     // particular path, disable codegen-units.
1351     if matches.opt_present("o") && cg.codegen_units != 1 {
1352         let incompatible: Vec<_> = output_types.iter()
1353             .map(|ot_path| ot_path.0)
1354             .filter(|ot| {
1355                 !ot.is_compatible_with_codegen_units_and_single_output_file()
1356             }).collect();
1357         if !incompatible.is_empty() {
1358             for ot in &incompatible {
1359                 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1360                                                  -C codegen-units=N for N > 1",
1361                                                 ot.shorthand()));
1362             }
1363             early_warn(error_format, "resetting to default -C codegen-units=1");
1364             cg.codegen_units = 1;
1365         }
1366     }
1367
1368     if cg.codegen_units < 1 {
1369         early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1370     }
1371
1372     let mut prints = Vec::<PrintRequest>::new();
1373     if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1374         prints.push(PrintRequest::TargetCPUs);
1375         cg.target_cpu = None;
1376     };
1377     if cg.target_feature == "help" {
1378         prints.push(PrintRequest::TargetFeatures);
1379         cg.target_feature = "".to_string();
1380     }
1381     if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1382         prints.push(PrintRequest::RelocationModels);
1383         cg.relocation_model = None;
1384     }
1385     if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1386         prints.push(PrintRequest::CodeModels);
1387         cg.code_model = None;
1388     }
1389
1390     let cg = cg;
1391
1392     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1393     let target = matches.opt_str("target").unwrap_or(
1394         host_triple().to_string());
1395     let opt_level = {
1396         if matches.opt_present("O") {
1397             if cg.opt_level.is_some() {
1398                 early_error(error_format, "-O and -C opt-level both provided");
1399             }
1400             OptLevel::Default
1401         } else {
1402             match (cg.opt_level.as_ref().map(String::as_ref),
1403                    nightly_options::is_nightly_build()) {
1404                 (None, _) => OptLevel::No,
1405                 (Some("0"), _) => OptLevel::No,
1406                 (Some("1"), _) => OptLevel::Less,
1407                 (Some("2"), _) => OptLevel::Default,
1408                 (Some("3"), _) => OptLevel::Aggressive,
1409                 (Some("s"), true) => OptLevel::Size,
1410                 (Some("z"), true) => OptLevel::SizeMin,
1411                 (Some("s"), false) | (Some("z"), false) => {
1412                     early_error(error_format, &format!("the optimizations s or z are only \
1413                                                         accepted on the nightly compiler"));
1414                 },
1415                 (Some(arg), _) => {
1416                     early_error(error_format, &format!("optimization level needs to be \
1417                                                       between 0-3 (instead was `{}`)",
1418                                                      arg));
1419                 }
1420             }
1421         }
1422     };
1423     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1424     let debuginfo = if matches.opt_present("g") {
1425         if cg.debuginfo.is_some() {
1426             early_error(error_format, "-g and -C debuginfo both provided");
1427         }
1428         FullDebugInfo
1429     } else {
1430         match cg.debuginfo {
1431             None | Some(0) => NoDebugInfo,
1432             Some(1) => LimitedDebugInfo,
1433             Some(2) => FullDebugInfo,
1434             Some(arg) => {
1435                 early_error(error_format, &format!("debug info level needs to be between \
1436                                                   0-2 (instead was `{}`)",
1437                                                  arg));
1438             }
1439         }
1440     };
1441
1442     let mut search_paths = SearchPaths::new();
1443     for s in &matches.opt_strs("L") {
1444         search_paths.add_path(&s[..], error_format);
1445     }
1446
1447     let libs = matches.opt_strs("l").into_iter().map(|s| {
1448         let mut parts = s.splitn(2, '=');
1449         let kind = parts.next().unwrap();
1450         let (name, kind) = match (parts.next(), kind) {
1451             (None, name) |
1452             (Some(name), "dylib") => (name, cstore::NativeUnknown),
1453             (Some(name), "framework") => (name, cstore::NativeFramework),
1454             (Some(name), "static") => (name, cstore::NativeStatic),
1455             (_, s) => {
1456                 early_error(error_format, &format!("unknown library kind `{}`, expected \
1457                                                   one of dylib, framework, or static",
1458                                                  s));
1459             }
1460         };
1461         (name.to_string(), kind)
1462     }).collect();
1463
1464     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1465     let test = matches.opt_present("test");
1466
1467     prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1468         match &*s {
1469             "crate-name" => PrintRequest::CrateName,
1470             "file-names" => PrintRequest::FileNames,
1471             "sysroot" => PrintRequest::Sysroot,
1472             "cfg" => PrintRequest::Cfg,
1473             "target-list" => PrintRequest::TargetList,
1474             "target-cpus" => PrintRequest::TargetCPUs,
1475             "target-features" => PrintRequest::TargetFeatures,
1476             "relocation-models" => PrintRequest::RelocationModels,
1477             "code-models" => PrintRequest::CodeModels,
1478             req => {
1479                 early_error(error_format, &format!("unknown print request `{}`", req))
1480             }
1481         }
1482     }));
1483
1484     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1485         early_warn(error_format, "-C remark will not show source locations without \
1486                                 --debuginfo");
1487     }
1488
1489     let mut externs = BTreeMap::new();
1490     for arg in &matches.opt_strs("extern") {
1491         let mut parts = arg.splitn(2, '=');
1492         let name = match parts.next() {
1493             Some(s) => s,
1494             None => early_error(error_format, "--extern value must not be empty"),
1495         };
1496         let location = match parts.next() {
1497             Some(s) => s,
1498             None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1499         };
1500
1501         externs.entry(name.to_string())
1502                .or_insert_with(BTreeSet::new)
1503                .insert(location.to_string());
1504     }
1505
1506     let crate_name = matches.opt_str("crate-name");
1507
1508     let incremental = debugging_opts.incremental.as_ref().map(|m| PathBuf::from(m));
1509
1510     (Options {
1511         crate_types: crate_types,
1512         optimize: opt_level,
1513         debuginfo: debuginfo,
1514         lint_opts: lint_opts,
1515         lint_cap: lint_cap,
1516         describe_lints: describe_lints,
1517         output_types: OutputTypes(output_types),
1518         search_paths: search_paths,
1519         maybe_sysroot: sysroot_opt,
1520         target_triple: target,
1521         test: test,
1522         mir_opt_level: mir_opt_level,
1523         incremental: incremental,
1524         debugging_opts: debugging_opts,
1525         prints: prints,
1526         cg: cg,
1527         error_format: error_format,
1528         externs: Externs(externs),
1529         crate_name: crate_name,
1530         alt_std_name: None,
1531         libs: libs,
1532         unstable_features: UnstableFeatures::from_environment(),
1533         debug_assertions: debug_assertions,
1534         actually_rustdoc: false,
1535     },
1536     cfg)
1537 }
1538
1539 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1540     let mut crate_types: Vec<CrateType> = Vec::new();
1541     for unparsed_crate_type in &list_list {
1542         for part in unparsed_crate_type.split(',') {
1543             let new_part = match part {
1544                 "lib"       => default_lib_output(),
1545                 "rlib"      => CrateTypeRlib,
1546                 "staticlib" => CrateTypeStaticlib,
1547                 "dylib"     => CrateTypeDylib,
1548                 "cdylib"    => CrateTypeCdylib,
1549                 "bin"       => CrateTypeExecutable,
1550                 "proc-macro" => CrateTypeProcMacro,
1551                 _ => {
1552                     return Err(format!("unknown crate type: `{}`",
1553                                        part));
1554                 }
1555             };
1556             if !crate_types.contains(&new_part) {
1557                 crate_types.push(new_part)
1558             }
1559         }
1560     }
1561
1562     return Ok(crate_types);
1563 }
1564
1565 pub mod nightly_options {
1566     use getopts;
1567     use syntax::feature_gate::UnstableFeatures;
1568     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
1569     use session::{early_error, early_warn};
1570
1571     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
1572         is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
1573     }
1574
1575     pub fn is_nightly_build() -> bool {
1576         UnstableFeatures::from_environment().is_nightly_build()
1577     }
1578
1579     pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
1580         let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
1581         let really_allows_unstable_options = UnstableFeatures::from_environment()
1582             .is_nightly_build();
1583
1584         for opt in flags.iter() {
1585             if opt.stability == OptionStability::Stable {
1586                 continue
1587             }
1588             let opt_name = if opt.opt_group.long_name.is_empty() {
1589                 &opt.opt_group.short_name
1590             } else {
1591                 &opt.opt_group.long_name
1592             };
1593             if !matches.opt_present(opt_name) {
1594                 continue
1595             }
1596             if opt_name != "Z" && !has_z_unstable_option {
1597                 early_error(ErrorOutputType::default(),
1598                             &format!("the `-Z unstable-options` flag must also be passed to enable \
1599                                       the flag `{}`",
1600                                      opt_name));
1601             }
1602             if really_allows_unstable_options {
1603                 continue
1604             }
1605             match opt.stability {
1606                 OptionStability::Unstable => {
1607                     let msg = format!("the option `{}` is only accepted on the \
1608                                        nightly compiler", opt_name);
1609                     early_error(ErrorOutputType::default(), &msg);
1610                 }
1611                 OptionStability::UnstableButNotReally => {
1612                     let msg = format!("the option `{}` is unstable and should \
1613                                        only be used on the nightly compiler, but \
1614                                        it is currently accepted for backwards \
1615                                        compatibility; this will soon change, \
1616                                        see issue #31847 for more details",
1617                                       opt_name);
1618                     early_warn(ErrorOutputType::default(), &msg);
1619                 }
1620                 OptionStability::Stable => {}
1621             }
1622         }
1623     }
1624 }
1625
1626 impl fmt::Display for CrateType {
1627     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1628         match *self {
1629             CrateTypeExecutable => "bin".fmt(f),
1630             CrateTypeDylib => "dylib".fmt(f),
1631             CrateTypeRlib => "rlib".fmt(f),
1632             CrateTypeStaticlib => "staticlib".fmt(f),
1633             CrateTypeCdylib => "cdylib".fmt(f),
1634             CrateTypeProcMacro => "proc-macro".fmt(f),
1635         }
1636     }
1637 }
1638
1639 /// Commandline arguments passed to the compiler have to be incorporated with
1640 /// the dependency tracking system for incremental compilation. This module
1641 /// provides some utilities to make this more convenient.
1642 ///
1643 /// The values of all commandline arguments that are relevant for dependency
1644 /// tracking are hashed into a single value that determines whether the
1645 /// incremental compilation cache can be re-used or not. This hashing is done
1646 /// via the DepTrackingHash trait defined below, since the standard Hash
1647 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
1648 /// the hash of which is order dependent, but we might not want the order of
1649 /// arguments to make a difference for the hash).
1650 ///
1651 /// However, since the value provided by Hash::hash often *is* suitable,
1652 /// especially for primitive types, there is the
1653 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
1654 /// Hash implementation for DepTrackingHash. It's important though that
1655 /// we have an opt-in scheme here, so one is hopefully forced to think about
1656 /// how the hash should be calculated when adding a new commandline argument.
1657 mod dep_tracking {
1658     use lint;
1659     use middle::cstore;
1660     use session::search_paths::{PathKind, SearchPaths};
1661     use std::collections::BTreeMap;
1662     use std::hash::Hash;
1663     use std::path::PathBuf;
1664     use std::collections::hash_map::DefaultHasher;
1665     use super::{Passes, CrateType, OptLevel, DebugInfoLevel,
1666                 OutputTypes, Externs, ErrorOutputType};
1667     use syntax::feature_gate::UnstableFeatures;
1668     use rustc_back::PanicStrategy;
1669
1670     pub trait DepTrackingHash {
1671         fn hash(&self, &mut DefaultHasher, ErrorOutputType);
1672     }
1673
1674     macro_rules! impl_dep_tracking_hash_via_hash {
1675         ($t:ty) => (
1676             impl DepTrackingHash for $t {
1677                 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1678                     Hash::hash(self, hasher);
1679                 }
1680             }
1681         )
1682     }
1683
1684     macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
1685         ($t:ty) => (
1686             impl DepTrackingHash for Vec<$t> {
1687                 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1688                     let mut elems: Vec<&$t> = self.iter().collect();
1689                     elems.sort();
1690                     Hash::hash(&elems.len(), hasher);
1691                     for (index, elem) in elems.iter().enumerate() {
1692                         Hash::hash(&index, hasher);
1693                         DepTrackingHash::hash(*elem, hasher, error_format);
1694                     }
1695                 }
1696             }
1697         );
1698     }
1699
1700     impl_dep_tracking_hash_via_hash!(bool);
1701     impl_dep_tracking_hash_via_hash!(usize);
1702     impl_dep_tracking_hash_via_hash!(String);
1703     impl_dep_tracking_hash_via_hash!(lint::Level);
1704     impl_dep_tracking_hash_via_hash!(Option<bool>);
1705     impl_dep_tracking_hash_via_hash!(Option<usize>);
1706     impl_dep_tracking_hash_via_hash!(Option<String>);
1707     impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
1708     impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
1709     impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
1710     impl_dep_tracking_hash_via_hash!(CrateType);
1711     impl_dep_tracking_hash_via_hash!(PanicStrategy);
1712     impl_dep_tracking_hash_via_hash!(Passes);
1713     impl_dep_tracking_hash_via_hash!(OptLevel);
1714     impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
1715     impl_dep_tracking_hash_via_hash!(UnstableFeatures);
1716     impl_dep_tracking_hash_via_hash!(Externs);
1717     impl_dep_tracking_hash_via_hash!(OutputTypes);
1718     impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
1719
1720     impl_dep_tracking_hash_for_sortable_vec_of!(String);
1721     impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
1722     impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
1723     impl_dep_tracking_hash_for_sortable_vec_of!((String, cstore::NativeLibraryKind));
1724
1725     impl DepTrackingHash for SearchPaths {
1726         fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1727             let mut elems: Vec<_> = self
1728                 .iter(PathKind::All)
1729                 .collect();
1730             elems.sort();
1731             Hash::hash(&elems, hasher);
1732         }
1733     }
1734
1735     impl<T1, T2> DepTrackingHash for (T1, T2)
1736         where T1: DepTrackingHash,
1737               T2: DepTrackingHash
1738     {
1739         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1740             Hash::hash(&0, hasher);
1741             DepTrackingHash::hash(&self.0, hasher, error_format);
1742             Hash::hash(&1, hasher);
1743             DepTrackingHash::hash(&self.1, hasher, error_format);
1744         }
1745     }
1746
1747     // This is a stable hash because BTreeMap is a sorted container
1748     pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
1749                        hasher: &mut DefaultHasher,
1750                        error_format: ErrorOutputType) {
1751         for (key, sub_hash) in sub_hashes {
1752             // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
1753             // the keys, as they are just plain strings
1754             Hash::hash(&key.len(), hasher);
1755             Hash::hash(key, hasher);
1756             sub_hash.hash(hasher, error_format);
1757         }
1758     }
1759 }
1760
1761 #[cfg(test)]
1762 mod tests {
1763     use dep_graph::DepGraph;
1764     use errors;
1765     use getopts::{getopts, OptGroup};
1766     use lint;
1767     use middle::cstore::{self, DummyCrateStore};
1768     use session::config::{build_configuration, build_session_options_and_crate_config};
1769     use session::build_session;
1770     use std::collections::{BTreeMap, BTreeSet};
1771     use std::iter::FromIterator;
1772     use std::path::PathBuf;
1773     use std::rc::Rc;
1774     use super::{OutputType, OutputTypes, Externs};
1775     use rustc_back::PanicStrategy;
1776     use syntax::{ast, attr};
1777     use syntax::parse::token::InternedString;
1778     use syntax::codemap::dummy_spanned;
1779
1780     fn optgroups() -> Vec<OptGroup> {
1781         super::rustc_optgroups().into_iter()
1782                                 .map(|a| a.opt_group)
1783                                 .collect()
1784     }
1785
1786     fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
1787         BTreeMap::from_iter(entries.into_iter())
1788     }
1789
1790     fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
1791         BTreeSet::from_iter(entries.into_iter())
1792     }
1793
1794     // When the user supplies --test we should implicitly supply --cfg test
1795     #[test]
1796     fn test_switch_implies_cfg_test() {
1797         let dep_graph = DepGraph::new(false);
1798         let matches =
1799             &match getopts(&["--test".to_string()], &optgroups()) {
1800               Ok(m) => m,
1801               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1802             };
1803         let registry = errors::registry::Registry::new(&[]);
1804         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
1805         let sess = build_session(sessopts, &dep_graph, None, registry, Rc::new(DummyCrateStore));
1806         let cfg = build_configuration(&sess, cfg);
1807         assert!(attr::contains(&cfg, &dummy_spanned(ast::MetaItemKind::Word({
1808             InternedString::new("test")
1809         }))));
1810     }
1811
1812     // When the user supplies --test and --cfg test, don't implicitly add
1813     // another --cfg test
1814     #[test]
1815     fn test_switch_implies_cfg_test_unless_cfg_test() {
1816         let dep_graph = DepGraph::new(false);
1817         let matches =
1818             &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1819                            &optgroups()) {
1820               Ok(m) => m,
1821               Err(f) => {
1822                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1823               }
1824             };
1825         let registry = errors::registry::Registry::new(&[]);
1826         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
1827         let sess = build_session(sessopts, &dep_graph, None, registry,
1828                                  Rc::new(DummyCrateStore));
1829         let cfg = build_configuration(&sess, cfg);
1830         let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1831         assert!(test_items.next().is_some());
1832         assert!(test_items.next().is_none());
1833     }
1834
1835     #[test]
1836     fn test_can_print_warnings() {
1837         let dep_graph = DepGraph::new(false);
1838         {
1839             let matches = getopts(&[
1840                 "-Awarnings".to_string()
1841             ], &optgroups()).unwrap();
1842             let registry = errors::registry::Registry::new(&[]);
1843             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1844             let sess = build_session(sessopts, &dep_graph, None, registry,
1845                                      Rc::new(DummyCrateStore));
1846             assert!(!sess.diagnostic().can_emit_warnings);
1847         }
1848
1849         {
1850             let matches = getopts(&[
1851                 "-Awarnings".to_string(),
1852                 "-Dwarnings".to_string()
1853             ], &optgroups()).unwrap();
1854             let registry = errors::registry::Registry::new(&[]);
1855             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1856             let sess = build_session(sessopts, &dep_graph, None, registry,
1857                                      Rc::new(DummyCrateStore));
1858             assert!(sess.diagnostic().can_emit_warnings);
1859         }
1860
1861         {
1862             let matches = getopts(&[
1863                 "-Adead_code".to_string()
1864             ], &optgroups()).unwrap();
1865             let registry = errors::registry::Registry::new(&[]);
1866             let (sessopts, _) = build_session_options_and_crate_config(&matches);
1867             let sess = build_session(sessopts, &dep_graph, None, registry,
1868                                      Rc::new(DummyCrateStore));
1869             assert!(sess.diagnostic().can_emit_warnings);
1870         }
1871     }
1872
1873     #[test]
1874     fn test_output_types_tracking_hash_different_paths() {
1875         let mut v1 = super::basic_options();
1876         let mut v2 = super::basic_options();
1877         let mut v3 = super::basic_options();
1878
1879         v1.output_types = OutputTypes::new(&[(OutputType::Exe,
1880                                               Some(PathBuf::from("./some/thing")))]);
1881         v2.output_types = OutputTypes::new(&[(OutputType::Exe,
1882                                               Some(PathBuf::from("/some/thing")))]);
1883         v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
1884
1885         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
1886         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
1887         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
1888
1889         // Check clone
1890         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1891         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
1892         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
1893     }
1894
1895     #[test]
1896     fn test_output_types_tracking_hash_different_construction_order() {
1897         let mut v1 = super::basic_options();
1898         let mut v2 = super::basic_options();
1899
1900         v1.output_types = OutputTypes::new(&[
1901             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
1902             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
1903         ]);
1904
1905         v2.output_types = OutputTypes::new(&[
1906             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
1907             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
1908         ]);
1909
1910         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
1911
1912         // Check clone
1913         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1914     }
1915
1916     #[test]
1917     fn test_externs_tracking_hash_different_values() {
1918         let mut v1 = super::basic_options();
1919         let mut v2 = super::basic_options();
1920         let mut v3 = super::basic_options();
1921
1922         v1.externs = Externs::new(mk_map(vec![
1923             (String::from("a"), mk_set(vec![String::from("b"),
1924                                             String::from("c")])),
1925             (String::from("d"), mk_set(vec![String::from("e"),
1926                                             String::from("f")])),
1927         ]));
1928
1929         v2.externs = Externs::new(mk_map(vec![
1930             (String::from("a"), mk_set(vec![String::from("b"),
1931                                             String::from("c")])),
1932             (String::from("X"), mk_set(vec![String::from("e"),
1933                                             String::from("f")])),
1934         ]));
1935
1936         v3.externs = Externs::new(mk_map(vec![
1937             (String::from("a"), mk_set(vec![String::from("b"),
1938                                             String::from("c")])),
1939             (String::from("d"), mk_set(vec![String::from("X"),
1940                                             String::from("f")])),
1941         ]));
1942
1943         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
1944         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
1945         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
1946
1947         // Check clone
1948         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1949         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
1950         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
1951     }
1952
1953     #[test]
1954     fn test_externs_tracking_hash_different_construction_order() {
1955         let mut v1 = super::basic_options();
1956         let mut v2 = super::basic_options();
1957         let mut v3 = super::basic_options();
1958
1959         v1.externs = Externs::new(mk_map(vec![
1960             (String::from("a"), mk_set(vec![String::from("b"),
1961                                             String::from("c")])),
1962             (String::from("d"), mk_set(vec![String::from("e"),
1963                                             String::from("f")])),
1964         ]));
1965
1966         v2.externs = Externs::new(mk_map(vec![
1967             (String::from("d"), mk_set(vec![String::from("e"),
1968                                             String::from("f")])),
1969             (String::from("a"), mk_set(vec![String::from("b"),
1970                                             String::from("c")])),
1971         ]));
1972
1973         v3.externs = Externs::new(mk_map(vec![
1974             (String::from("a"), mk_set(vec![String::from("b"),
1975                                             String::from("c")])),
1976             (String::from("d"), mk_set(vec![String::from("f"),
1977                                             String::from("e")])),
1978         ]));
1979
1980         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
1981         assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
1982         assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
1983
1984         // Check clone
1985         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
1986         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
1987         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
1988     }
1989
1990     #[test]
1991     fn test_lints_tracking_hash_different_values() {
1992         let mut v1 = super::basic_options();
1993         let mut v2 = super::basic_options();
1994         let mut v3 = super::basic_options();
1995
1996         v1.lint_opts = vec![(String::from("a"), lint::Allow),
1997                             (String::from("b"), lint::Warn),
1998                             (String::from("c"), lint::Deny),
1999                             (String::from("d"), lint::Forbid)];
2000
2001         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2002                             (String::from("b"), lint::Warn),
2003                             (String::from("X"), lint::Deny),
2004                             (String::from("d"), lint::Forbid)];
2005
2006         v3.lint_opts = vec![(String::from("a"), lint::Allow),
2007                             (String::from("b"), lint::Warn),
2008                             (String::from("c"), lint::Forbid),
2009                             (String::from("d"), lint::Deny)];
2010
2011         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2012         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2013         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2014
2015         // Check clone
2016         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2017         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2018         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2019     }
2020
2021     #[test]
2022     fn test_lints_tracking_hash_different_construction_order() {
2023         let mut v1 = super::basic_options();
2024         let mut v2 = super::basic_options();
2025
2026         v1.lint_opts = vec![(String::from("a"), lint::Allow),
2027                             (String::from("b"), lint::Warn),
2028                             (String::from("c"), lint::Deny),
2029                             (String::from("d"), lint::Forbid)];
2030
2031         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2032                             (String::from("c"), lint::Deny),
2033                             (String::from("b"), lint::Warn),
2034                             (String::from("d"), lint::Forbid)];
2035
2036         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2037
2038         // Check clone
2039         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2040         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2041     }
2042
2043     #[test]
2044     fn test_search_paths_tracking_hash_different_values() {
2045         let mut v1 = super::basic_options();
2046         let mut v2 = super::basic_options();
2047         let mut v3 = super::basic_options();
2048         let mut v4 = super::basic_options();
2049         let mut v5 = super::basic_options();
2050
2051         // Reference
2052         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2053         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2054         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2055         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2056         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2057
2058         // Native changed
2059         v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json);
2060         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2061         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2062         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2063         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2064
2065         // Crate changed
2066         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2067         v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json);
2068         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2069         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2070         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2071
2072         // Dependency changed
2073         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2074         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2075         v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json);
2076         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2077         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2078
2079         // Framework changed
2080         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2081         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2082         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2083         v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json);
2084         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2085
2086         // All changed
2087         v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2088         v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2089         v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2090         v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2091         v5.search_paths.add_path("all=XXX", super::ErrorOutputType::Json);
2092
2093         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2094         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2095         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2096         assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2097
2098         // Check clone
2099         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2100         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2101         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2102         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2103         assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2104     }
2105
2106     #[test]
2107     fn test_search_paths_tracking_hash_different_order() {
2108         let mut v1 = super::basic_options();
2109         let mut v2 = super::basic_options();
2110         let mut v3 = super::basic_options();
2111         let mut v4 = super::basic_options();
2112
2113         // Reference
2114         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2115         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2116         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2117         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2118         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2119
2120         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2121         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2122         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2123         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2124         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2125
2126         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2127         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2128         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2129         v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2130         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2131
2132         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2133         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2134         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2135         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2136         v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2137
2138         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2139         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2140         assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2141
2142         // Check clone
2143         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2144         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2145         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2146         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2147     }
2148
2149     #[test]
2150     fn test_native_libs_tracking_hash_different_values() {
2151         let mut v1 = super::basic_options();
2152         let mut v2 = super::basic_options();
2153         let mut v3 = super::basic_options();
2154
2155         // Reference
2156         v1.libs = vec![(String::from("a"), cstore::NativeStatic),
2157                        (String::from("b"), cstore::NativeFramework),
2158                        (String::from("c"), cstore::NativeUnknown)];
2159
2160         // Change label
2161         v2.libs = vec![(String::from("a"), cstore::NativeStatic),
2162                        (String::from("X"), cstore::NativeFramework),
2163                        (String::from("c"), cstore::NativeUnknown)];
2164
2165         // Change kind
2166         v3.libs = vec![(String::from("a"), cstore::NativeStatic),
2167                        (String::from("b"), cstore::NativeStatic),
2168                        (String::from("c"), cstore::NativeUnknown)];
2169
2170         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2171         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2172
2173         // Check clone
2174         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2175         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2176         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2177     }
2178
2179     #[test]
2180     fn test_native_libs_tracking_hash_different_order() {
2181         let mut v1 = super::basic_options();
2182         let mut v2 = super::basic_options();
2183         let mut v3 = super::basic_options();
2184
2185         // Reference
2186         v1.libs = vec![(String::from("a"), cstore::NativeStatic),
2187                        (String::from("b"), cstore::NativeFramework),
2188                        (String::from("c"), cstore::NativeUnknown)];
2189
2190         v2.libs = vec![(String::from("b"), cstore::NativeFramework),
2191                        (String::from("a"), cstore::NativeStatic),
2192                        (String::from("c"), cstore::NativeUnknown)];
2193
2194         v3.libs = vec![(String::from("c"), cstore::NativeUnknown),
2195                        (String::from("a"), cstore::NativeStatic),
2196                        (String::from("b"), cstore::NativeFramework)];
2197
2198         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2199         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2200         assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2201
2202         // Check clone
2203         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2204         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2205         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2206     }
2207
2208     #[test]
2209     fn test_codegen_options_tracking_hash() {
2210         let reference = super::basic_options();
2211         let mut opts = super::basic_options();
2212
2213         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2214         opts.cg.ar = Some(String::from("abc"));
2215         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2216
2217         opts.cg.linker = Some(String::from("linker"));
2218         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2219
2220         opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2221         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2222
2223         opts.cg.link_dead_code = true;
2224         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2225
2226         opts.cg.rpath = true;
2227         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2228
2229         opts.cg.extra_filename = String::from("extra-filename");
2230         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2231
2232         opts.cg.codegen_units = 42;
2233         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2234
2235         opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2236                                                 String::from("pass2")]);
2237         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2238
2239         opts.cg.save_temps = true;
2240         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2241
2242
2243         // Make sure changing a [TRACKED] option changes the hash
2244         opts = reference.clone();
2245         opts.cg.lto = true;
2246         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2247
2248         opts = reference.clone();
2249         opts.cg.target_cpu = Some(String::from("abc"));
2250         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2251
2252         opts = reference.clone();
2253         opts.cg.target_feature = String::from("all the features, all of them");
2254         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2255
2256         opts = reference.clone();
2257         opts.cg.passes = vec![String::from("1"), String::from("2")];
2258         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2259
2260         opts = reference.clone();
2261         opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2262         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2263
2264         opts = reference.clone();
2265         opts.cg.no_prepopulate_passes = true;
2266         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2267
2268         opts = reference.clone();
2269         opts.cg.no_vectorize_loops = true;
2270         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2271
2272         opts = reference.clone();
2273         opts.cg.no_vectorize_slp = true;
2274         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2275
2276         opts = reference.clone();
2277         opts.cg.soft_float = true;
2278         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2279
2280         opts = reference.clone();
2281         opts.cg.prefer_dynamic = true;
2282         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2283
2284         opts = reference.clone();
2285         opts.cg.no_integrated_as = true;
2286         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2287
2288         opts = reference.clone();
2289         opts.cg.no_redzone = Some(true);
2290         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2291
2292         opts = reference.clone();
2293         opts.cg.relocation_model = Some(String::from("relocation model"));
2294         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2295
2296         opts = reference.clone();
2297         opts.cg.code_model = Some(String::from("code model"));
2298         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2299
2300         opts = reference.clone();
2301         opts.cg.metadata = vec![String::from("A"), String::from("B")];
2302         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2303
2304         opts = reference.clone();
2305         opts.cg.debuginfo = Some(0xdeadbeef);
2306         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2307
2308         opts = reference.clone();
2309         opts.cg.debuginfo = Some(0xba5eba11);
2310         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2311
2312         opts = reference.clone();
2313         opts.cg.debug_assertions = Some(true);
2314         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2315
2316         opts = reference.clone();
2317         opts.cg.inline_threshold = Some(0xf007ba11);
2318         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2319
2320         opts = reference.clone();
2321         opts.cg.panic = Some(PanicStrategy::Abort);
2322         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2323     }
2324
2325     #[test]
2326     fn test_debugging_options_tracking_hash() {
2327         let reference = super::basic_options();
2328         let mut opts = super::basic_options();
2329
2330         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2331         opts.debugging_opts.verbose = true;
2332         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2333         opts.debugging_opts.time_passes = true;
2334         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2335         opts.debugging_opts.count_llvm_insns = true;
2336         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2337         opts.debugging_opts.time_llvm_passes = true;
2338         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2339         opts.debugging_opts.input_stats = true;
2340         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2341         opts.debugging_opts.trans_stats = true;
2342         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2343         opts.debugging_opts.borrowck_stats = true;
2344         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2345         opts.debugging_opts.debug_llvm = true;
2346         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2347         opts.debugging_opts.meta_stats = true;
2348         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2349         opts.debugging_opts.print_link_args = true;
2350         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2351         opts.debugging_opts.print_llvm_passes = true;
2352         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2353         opts.debugging_opts.ast_json = true;
2354         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2355         opts.debugging_opts.ast_json_noexpand = true;
2356         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2357         opts.debugging_opts.ls = true;
2358         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2359         opts.debugging_opts.save_analysis = true;
2360         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2361         opts.debugging_opts.save_analysis_csv = true;
2362         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2363         opts.debugging_opts.save_analysis_api = true;
2364         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2365         opts.debugging_opts.print_move_fragments = true;
2366         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2367         opts.debugging_opts.flowgraph_print_loans = true;
2368         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2369         opts.debugging_opts.flowgraph_print_moves = true;
2370         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2371         opts.debugging_opts.flowgraph_print_assigns = true;
2372         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2373         opts.debugging_opts.flowgraph_print_all = true;
2374         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2375         opts.debugging_opts.print_region_graph = true;
2376         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2377         opts.debugging_opts.parse_only = true;
2378         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2379         opts.debugging_opts.incremental = Some(String::from("abc"));
2380         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2381         opts.debugging_opts.dump_dep_graph = true;
2382         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2383         opts.debugging_opts.query_dep_graph = true;
2384         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2385         opts.debugging_opts.no_analysis = true;
2386         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2387         opts.debugging_opts.unstable_options = true;
2388         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2389         opts.debugging_opts.trace_macros = true;
2390         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2391         opts.debugging_opts.keep_hygiene_data = true;
2392         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2393         opts.debugging_opts.keep_ast = true;
2394         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2395         opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2396         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2397         opts.debugging_opts.dump_mir = Some(String::from("abc"));
2398         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2399         opts.debugging_opts.dump_mir_dir = Some(String::from("abc"));
2400         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2401
2402         // Make sure changing a [TRACKED] option changes the hash
2403         opts = reference.clone();
2404         opts.debugging_opts.asm_comments = true;
2405         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2406
2407         opts = reference.clone();
2408         opts.debugging_opts.no_verify = true;
2409         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2410
2411         opts = reference.clone();
2412         opts.debugging_opts.no_landing_pads = true;
2413         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2414
2415         opts = reference.clone();
2416         opts.debugging_opts.no_trans = true;
2417         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2418
2419         opts = reference.clone();
2420         opts.debugging_opts.treat_err_as_bug = true;
2421         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2422
2423         opts = reference.clone();
2424         opts.debugging_opts.continue_parse_after_error = true;
2425         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2426
2427         opts = reference.clone();
2428         opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2429         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2430
2431         opts = reference.clone();
2432         opts.debugging_opts.force_overflow_checks = Some(true);
2433         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2434
2435         opts = reference.clone();
2436         opts.debugging_opts.enable_nonzeroing_move_hints = true;
2437         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2438
2439         opts = reference.clone();
2440         opts.debugging_opts.show_span = Some(String::from("abc"));
2441         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2442
2443         opts = reference.clone();
2444         opts.debugging_opts.mir_opt_level = Some(1);
2445         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2446     }
2447 }