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