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