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