]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
rustdoc: pretty-print Unevaluated expressions in types.
[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 isize_ty: IntTy,
52     pub usize_ty: 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     emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
923         "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
924     borrowck_mir: bool = (false, parse_bool, [UNTRACKED],
925         "implicitly treat functions as if they have `#[rustc_mir_borrowck]` attribute"),
926     time_passes: bool = (false, parse_bool, [UNTRACKED],
927         "measure time of each rustc pass"),
928     count_llvm_insns: bool = (false, parse_bool,
929         [UNTRACKED_WITH_WARNING(true,
930         "The output generated by `-Z count_llvm_insns` might not be reliable \
931          when used with incremental compilation")],
932         "count where LLVM instrs originate"),
933     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
934         "The output of `-Z time-llvm-passes` will only reflect timings of \
935          re-translated modules when used with incremental compilation" )],
936         "measure time of each LLVM pass"),
937     input_stats: bool = (false, parse_bool, [UNTRACKED],
938         "gather statistics about the input"),
939     trans_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
940         "The output of `-Z trans-stats` might not be accurate when incremental \
941          compilation is enabled")],
942         "gather trans statistics"),
943     asm_comments: bool = (false, parse_bool, [TRACKED],
944         "generate comments into the assembly (may change behavior)"),
945     no_verify: bool = (false, parse_bool, [TRACKED],
946         "skip LLVM verification"),
947     borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
948         "gather borrowck statistics"),
949     no_landing_pads: bool = (false, parse_bool, [TRACKED],
950         "omit landing pads for unwinding"),
951     debug_llvm: bool = (false, parse_bool, [UNTRACKED],
952         "enable debug output from LLVM"),
953     meta_stats: bool = (false, parse_bool, [UNTRACKED],
954         "gather metadata statistics"),
955     print_link_args: bool = (false, parse_bool, [UNTRACKED],
956         "print the arguments passed to the linker"),
957     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
958         "prints the llvm optimization passes being run"),
959     ast_json: bool = (false, parse_bool, [UNTRACKED],
960         "print the AST as JSON and halt"),
961     ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
962         "print the pre-expansion AST as JSON and halt"),
963     ls: bool = (false, parse_bool, [UNTRACKED],
964         "list the symbols defined by a library crate"),
965     save_analysis: bool = (false, parse_bool, [UNTRACKED],
966         "write syntax and type analysis (in JSON format) information, in \
967          addition to normal output"),
968     print_move_fragments: bool = (false, parse_bool, [UNTRACKED],
969         "print out move-fragment data for every fn"),
970     flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
971         "include loan analysis data in --unpretty flowgraph output"),
972     flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
973         "include move analysis data in --unpretty flowgraph output"),
974     flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
975         "include assignment analysis data in --unpretty flowgraph output"),
976     flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
977         "include all dataflow analysis data in --unpretty flowgraph output"),
978     print_region_graph: bool = (false, parse_bool, [UNTRACKED],
979          "prints region inference graph. \
980           Use with RUST_REGION_GRAPH=help for more info"),
981     parse_only: bool = (false, parse_bool, [UNTRACKED],
982           "parse only; do not compile, assemble, or link"),
983     no_trans: bool = (false, parse_bool, [TRACKED],
984           "run all passes except translation; no output"),
985     treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
986           "treat all errors that occur as bugs"),
987     continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
988           "attempt to recover from parse errors (experimental)"),
989     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
990           "enable incremental compilation (experimental)"),
991     incremental_cc: bool = (true, parse_bool, [UNTRACKED],
992           "enable cross-crate incremental compilation (even more experimental)"),
993     incremental_info: bool = (false, parse_bool, [UNTRACKED],
994         "print high-level information about incremental reuse (or the lack thereof)"),
995     incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
996         "dump hash information in textual format to stdout"),
997     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
998           "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
999     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1000           "enable queries of the dependency graph for regression testing"),
1001     profile_queries: bool = (false, parse_bool, [UNTRACKED],
1002           "trace and profile the queries of the incremental compilation framework"),
1003     profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1004           "trace and profile the queries and keys of the incremental compilation framework"),
1005     no_analysis: bool = (false, parse_bool, [UNTRACKED],
1006           "parse and expand the source, but run no analysis"),
1007     extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1008         "load extra plugins"),
1009     unstable_options: bool = (false, parse_bool, [UNTRACKED],
1010           "adds unstable command line options to rustc interface"),
1011     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1012           "force overflow checks on or off"),
1013     trace_macros: bool = (false, parse_bool, [UNTRACKED],
1014           "for every macro invocation, print its name and arguments"),
1015     debug_macros: bool = (false, parse_bool, [TRACKED],
1016           "emit line numbers debug info inside macros"),
1017     enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
1018           "force nonzeroing move optimization on"),
1019     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1020           "don't clear the hygiene data after analysis"),
1021     keep_ast: bool = (false, parse_bool, [UNTRACKED],
1022           "keep the AST after lowering it to HIR"),
1023     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1024           "show spans for compiler debugging (expr|pat|ty)"),
1025     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1026           "print layout information for each type encountered"),
1027     print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1028           "print the result of the translation item collection pass"),
1029     mir_opt_level: usize = (1, parse_uint, [TRACKED],
1030           "set the MIR optimization level (0-3, default: 1)"),
1031     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1032           "dump MIR state at various points in translation"),
1033     dump_mir_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1034           "the directory the MIR is dumped into"),
1035     dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1036           "if set, exclude the pass number when dumping MIR (used in tests)"),
1037     mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1038           "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1039            contains unsafe block, only validate arguments; 2: always emit full validation)"),
1040     perf_stats: bool = (false, parse_bool, [UNTRACKED],
1041           "print some performance-related statistics"),
1042     hir_stats: bool = (false, parse_bool, [UNTRACKED],
1043           "print some statistics about AST and HIR"),
1044     mir_stats: bool = (false, parse_bool, [UNTRACKED],
1045           "print some statistics about MIR"),
1046     always_encode_mir: bool = (false, parse_bool, [TRACKED],
1047           "encode MIR of all functions into the crate metadata"),
1048     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1049           "pass `-install_name @rpath/...` to the macOS linker"),
1050     sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1051                                    "Use a sanitizer"),
1052     linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1053                                            "Linker flavor"),
1054     fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1055         "Set the optimization fuel quota for a crate."),
1056     print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1057         "Make Rustc print the total optimization fuel used by a crate."),
1058     remap_path_prefix_from: Vec<String> = (vec![], parse_string_push, [TRACKED],
1059         "add a source pattern to the file path remapping config"),
1060     remap_path_prefix_to: Vec<String> = (vec![], parse_string_push, [TRACKED],
1061         "add a mapping target to the file path remapping config"),
1062     force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1063         "force all crates to be `rustc_private` unstable"),
1064     pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1065         "a single extra argument to prepend the linker invocation (can be used several times)"),
1066     pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1067         "extra arguments to prepend to the linker invocation (space separated)"),
1068     profile: bool = (false, parse_bool, [TRACKED],
1069                      "insert profiling code"),
1070     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1071         "choose which RELRO level to use"),
1072     nll: bool = (false, parse_bool, [UNTRACKED],
1073                  "run the non-lexical lifetimes MIR pass"),
1074     trans_time_graph: bool = (false, parse_bool, [UNTRACKED],
1075         "generate a graphical HTML report of time spent in trans and LLVM"),
1076 }
1077
1078 pub fn default_lib_output() -> CrateType {
1079     CrateTypeRlib
1080 }
1081
1082 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1083     let end = &sess.target.target.target_endian;
1084     let arch = &sess.target.target.arch;
1085     let wordsz = &sess.target.target.target_pointer_width;
1086     let os = &sess.target.target.target_os;
1087     let env = &sess.target.target.target_env;
1088     let vendor = &sess.target.target.target_vendor;
1089     let min_atomic_width = sess.target.target.min_atomic_width();
1090     let max_atomic_width = sess.target.target.max_atomic_width();
1091
1092     let mut ret = HashSet::new();
1093     // Target bindings.
1094     ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1095     if let Some(ref fam) = sess.target.target.options.target_family {
1096         ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1097         if fam == "windows" || fam == "unix" {
1098             ret.insert((Symbol::intern(fam), None));
1099         }
1100     }
1101     ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1102     ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1103     ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
1104     ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1105     ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
1106     if sess.target.target.options.has_elf_tls {
1107         ret.insert((Symbol::intern("target_thread_local"), None));
1108     }
1109     for &i in &[8, 16, 32, 64, 128] {
1110         if i >= min_atomic_width && i <= max_atomic_width {
1111             let s = i.to_string();
1112             ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
1113             if &s == wordsz {
1114                 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
1115             }
1116         }
1117     }
1118     if sess.opts.debug_assertions {
1119         ret.insert((Symbol::intern("debug_assertions"), None));
1120     }
1121     if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1122         ret.insert((Symbol::intern("proc_macro"), None));
1123     }
1124     return ret;
1125 }
1126
1127 pub fn build_configuration(sess: &Session,
1128                            mut user_cfg: ast::CrateConfig)
1129                            -> ast::CrateConfig {
1130     // Combine the configuration requested by the session (command line) with
1131     // some default and generated configuration items
1132     let default_cfg = default_configuration(sess);
1133     // If the user wants a test runner, then add the test cfg
1134     if sess.opts.test {
1135         user_cfg.insert((Symbol::intern("test"), None));
1136     }
1137     user_cfg.extend(default_cfg.iter().cloned());
1138     user_cfg
1139 }
1140
1141 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1142     let target = match Target::search(&opts.target_triple) {
1143         Ok(t) => t,
1144         Err(e) => {
1145             sp.struct_fatal(&format!("Error loading target specification: {}", e))
1146                 .help("Use `--print target-list` for a list of built-in targets")
1147                 .emit();
1148             panic!(FatalError);
1149         }
1150     };
1151
1152     let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1153         "16" => (ast::IntTy::I16, ast::UintTy::U16),
1154         "32" => (ast::IntTy::I32, ast::UintTy::U32),
1155         "64" => (ast::IntTy::I64, ast::UintTy::U64),
1156         w    => panic!(sp.fatal(&format!("target specification was invalid: \
1157                                           unrecognized target-pointer-width {}", w))),
1158     };
1159
1160     Config {
1161         target,
1162         isize_ty,
1163         usize_ty,
1164     }
1165 }
1166
1167 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1168 pub enum OptionStability {
1169     Stable,
1170
1171     Unstable,
1172 }
1173
1174 pub struct RustcOptGroup {
1175     pub apply: Box<Fn(&mut getopts::Options) -> &mut getopts::Options>,
1176     pub name: &'static str,
1177     pub stability: OptionStability,
1178 }
1179
1180 impl RustcOptGroup {
1181     pub fn is_stable(&self) -> bool {
1182         self.stability == OptionStability::Stable
1183     }
1184
1185     pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1186         where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1187     {
1188         RustcOptGroup {
1189             name,
1190             apply: Box::new(f),
1191             stability: OptionStability::Stable,
1192         }
1193     }
1194
1195     pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1196         where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1197     {
1198         RustcOptGroup {
1199             name,
1200             apply: Box::new(f),
1201             stability: OptionStability::Unstable,
1202         }
1203     }
1204 }
1205
1206 // The `opt` local module holds wrappers around the `getopts` API that
1207 // adds extra rustc-specific metadata to each option; such metadata
1208 // is exposed by .  The public
1209 // functions below ending with `_u` are the functions that return
1210 // *unstable* options, i.e. options that are only enabled when the
1211 // user also passes the `-Z unstable-options` debugging flag.
1212 mod opt {
1213     // The `fn opt_u` etc below are written so that we can use them
1214     // in the future; do not warn about them not being used right now.
1215     #![allow(dead_code)]
1216
1217     use getopts;
1218     use super::RustcOptGroup;
1219
1220     pub type R = RustcOptGroup;
1221     pub type S = &'static str;
1222
1223     fn stable<F>(name: S, f: F) -> R
1224         where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1225     {
1226         RustcOptGroup::stable(name, f)
1227     }
1228
1229     fn unstable<F>(name: S, f: F) -> R
1230         where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1231     {
1232         RustcOptGroup::unstable(name, f)
1233     }
1234
1235     fn longer(a: S, b: S) -> S {
1236         if a.len() > b.len() {
1237             a
1238         } else {
1239             b
1240         }
1241     }
1242
1243     pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1244         stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1245     }
1246     pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1247         stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1248     }
1249     pub fn flag_s(a: S, b: S, c: S) -> R {
1250         stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1251     }
1252     pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1253         stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1254     }
1255     pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1256         stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1257     }
1258
1259     pub fn opt(a: S, b: S, c: S, d: S) -> R {
1260         unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1261     }
1262     pub fn multi(a: S, b: S, c: S, d: S) -> R {
1263         unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1264     }
1265     pub fn flag(a: S, b: S, c: S) -> R {
1266         unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1267     }
1268     pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1269         unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1270     }
1271     pub fn flagmulti(a: S, b: S, c: S) -> R {
1272         unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1273     }
1274 }
1275
1276 /// Returns the "short" subset of the rustc command line options,
1277 /// including metadata for each option, such as whether the option is
1278 /// part of the stable long-term interface for rustc.
1279 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1280     vec![
1281         opt::flag_s("h", "help", "Display this message"),
1282         opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1283         opt::multi_s("L", "",   "Add a directory to the library search path. The
1284                              optional KIND can be one of dependency, crate, native,
1285                              framework or all (the default).", "[KIND=]PATH"),
1286         opt::multi_s("l", "",   "Link the generated crate(s) to the specified native
1287                              library NAME. The optional KIND can be one of
1288                              static, dylib, or framework. If omitted, dylib is
1289                              assumed.", "[KIND=]NAME"),
1290         opt::multi_s("", "crate-type", "Comma separated list of types of crates
1291                                     for the compiler to emit",
1292                    "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
1293         opt::opt_s("", "crate-name", "Specify the name of the crate being built",
1294                "NAME"),
1295         opt::multi_s("", "emit", "Comma separated list of types of output for \
1296                               the compiler to emit",
1297                  "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]"),
1298         opt::multi_s("", "print", "Comma separated list of compiler information to \
1299                                print on stdout",
1300                      "[crate-name|file-names|sysroot|cfg|target-list|\
1301                        target-cpus|target-features|relocation-models|\
1302                        code-models|target-spec-json|native-static-deps]"),
1303         opt::flagmulti_s("g",  "",  "Equivalent to -C debuginfo=2"),
1304         opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1305         opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1306         opt::opt_s("",  "out-dir", "Write output to compiler-chosen filename \
1307                                 in <dir>", "DIR"),
1308         opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1309                                message", "OPT"),
1310         opt::flag_s("", "test", "Build a test harness"),
1311         opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1312         opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1313         opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1314         opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1315         opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1316         opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1317                                      More restrictive lints are capped at this \
1318                                      level", "LEVEL"),
1319         opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1320         opt::flag_s("V", "version", "Print version info and exit"),
1321         opt::flag_s("v", "verbose", "Use verbose output"),
1322     ]
1323 }
1324
1325 /// Returns all rustc command line options, including metadata for
1326 /// each option, such as whether the option is part of the stable
1327 /// long-term interface for rustc.
1328 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1329     let mut opts = rustc_short_optgroups();
1330     opts.extend(vec![
1331         opt::multi_s("", "extern", "Specify where an external rust library is located",
1332                      "NAME=PATH"),
1333         opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1334         opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1335         opt::opt_s("", "error-format",
1336                       "How errors and other messages are produced",
1337                       "human|json"),
1338         opt::opt_s("", "color", "Configure coloring of output:
1339                                  auto   = colorize, if output goes to a tty (default);
1340                                  always = always colorize output;
1341                                  never  = never colorize output", "auto|always|never"),
1342
1343         opt::flagopt("", "pretty",
1344                      "Pretty-print the input instead of compiling;
1345                       valid types are: `normal` (un-annotated source),
1346                       `expanded` (crates expanded), or
1347                       `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1348                      "TYPE"),
1349         opt::flagopt("", "unpretty",
1350                      "Present the input source, unstable (and less-pretty) variants;
1351                       valid types are any of the types for `--pretty`, as well as:
1352                       `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1353                       `everybody_loops` (all function bodies replaced with `loop {}`),
1354                       `hir` (the HIR), `hir,identified`, or
1355                       `hir,typed` (HIR with types for each node).",
1356                      "TYPE"),
1357     ]);
1358     opts
1359 }
1360
1361 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1362 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1363     cfgspecs.into_iter().map(|s| {
1364         let sess = parse::ParseSess::new(FilePathMapping::empty());
1365         let mut parser =
1366             parse::new_parser_from_source_str(&sess, "cfgspec".to_string(), s.to_string());
1367
1368         let meta_item = panictry!(parser.parse_meta_item());
1369
1370         if parser.token != token::Eof {
1371             early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
1372         } else if meta_item.is_meta_item_list() {
1373             let msg =
1374                 format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
1375             early_error(ErrorOutputType::default(), &msg)
1376         }
1377
1378         (meta_item.name(), meta_item.value_str())
1379     }).collect::<ast::CrateConfig>()
1380 }
1381
1382 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1383                                               -> (Options, ast::CrateConfig) {
1384     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1385         Some("auto")   => ColorConfig::Auto,
1386         Some("always") => ColorConfig::Always,
1387         Some("never")  => ColorConfig::Never,
1388
1389         None => ColorConfig::Auto,
1390
1391         Some(arg) => {
1392             early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1393                                                               always or never (instead was `{}`)",
1394                                                             arg))
1395         }
1396     };
1397
1398     // We need the opts_present check because the driver will send us Matches
1399     // with only stable options if no unstable options are used. Since error-format
1400     // is unstable, it will not be present. We have to use opts_present not
1401     // opt_present because the latter will panic.
1402     let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1403         match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1404             Some("human")   => ErrorOutputType::HumanReadable(color),
1405             Some("json") => ErrorOutputType::Json,
1406
1407             None => ErrorOutputType::HumanReadable(color),
1408
1409             Some(arg) => {
1410                 early_error(ErrorOutputType::HumanReadable(color),
1411                             &format!("argument for --error-format must be human or json (instead \
1412                                       was `{}`)",
1413                                      arg))
1414             }
1415         }
1416     } else {
1417         ErrorOutputType::HumanReadable(color)
1418     };
1419
1420     let unparsed_crate_types = matches.opt_strs("crate-type");
1421     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1422         .unwrap_or_else(|e| early_error(error_format, &e[..]));
1423
1424     let mut lint_opts = vec![];
1425     let mut describe_lints = false;
1426
1427     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1428         for lint_name in matches.opt_strs(level.as_str()) {
1429             if lint_name == "help" {
1430                 describe_lints = true;
1431             } else {
1432                 lint_opts.push((lint_name.replace("-", "_"), level));
1433             }
1434         }
1435     }
1436
1437     let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1438         lint::Level::from_str(&cap).unwrap_or_else(|| {
1439             early_error(error_format, &format!("unknown lint level: `{}`", cap))
1440         })
1441     });
1442
1443     let debugging_opts = build_debugging_options(matches, error_format);
1444
1445     let mut output_types = BTreeMap::new();
1446     if !debugging_opts.parse_only {
1447         for list in matches.opt_strs("emit") {
1448             for output_type in list.split(',') {
1449                 let mut parts = output_type.splitn(2, '=');
1450                 let output_type = match parts.next().unwrap() {
1451                     "asm" => OutputType::Assembly,
1452                     "llvm-ir" => OutputType::LlvmAssembly,
1453                     "mir" => OutputType::Mir,
1454                     "llvm-bc" => OutputType::Bitcode,
1455                     "obj" => OutputType::Object,
1456                     "metadata" => OutputType::Metadata,
1457                     "link" => OutputType::Exe,
1458                     "dep-info" => OutputType::DepInfo,
1459                     part => {
1460                         early_error(error_format, &format!("unknown emission type: `{}`",
1461                                                     part))
1462                     }
1463                 };
1464                 let path = parts.next().map(PathBuf::from);
1465                 output_types.insert(output_type, path);
1466             }
1467         }
1468     };
1469     if output_types.is_empty() {
1470         output_types.insert(OutputType::Exe, None);
1471     }
1472
1473     let remap_path_prefix_sources = debugging_opts.remap_path_prefix_from.len();
1474     let remap_path_prefix_targets = debugging_opts.remap_path_prefix_from.len();
1475
1476     if remap_path_prefix_targets < remap_path_prefix_sources {
1477         for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
1478             early_error(error_format,
1479                 &format!("option `-Zremap-path-prefix-from='{}'` does not have \
1480                          a corresponding `-Zremap-path-prefix-to`", source))
1481         }
1482     } else if remap_path_prefix_targets > remap_path_prefix_sources {
1483         for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
1484             early_error(error_format,
1485                 &format!("option `-Zremap-path-prefix-to='{}'` does not have \
1486                           a corresponding `-Zremap-path-prefix-from`", target))
1487         }
1488     }
1489
1490     let mut cg = build_codegen_options(matches, error_format);
1491
1492     // Issue #30063: if user requests llvm-related output to one
1493     // particular path, disable codegen-units.
1494     if matches.opt_present("o") && cg.codegen_units != 1 {
1495         let incompatible: Vec<_> = output_types.iter()
1496             .map(|ot_path| ot_path.0)
1497             .filter(|ot| {
1498                 !ot.is_compatible_with_codegen_units_and_single_output_file()
1499             }).collect();
1500         if !incompatible.is_empty() {
1501             for ot in &incompatible {
1502                 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1503                                                  -C codegen-units=N for N > 1",
1504                                                 ot.shorthand()));
1505             }
1506             early_warn(error_format, "resetting to default -C codegen-units=1");
1507             cg.codegen_units = 1;
1508         }
1509     }
1510
1511     if cg.codegen_units < 1 {
1512         early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1513     }
1514
1515     // It's possible that we have `codegen_units > 1` but only one item in
1516     // `trans.modules`.  We could theoretically proceed and do LTO in that
1517     // case, but it would be confusing to have the validity of
1518     // `-Z lto -C codegen-units=2` depend on details of the crate being
1519     // compiled, so we complain regardless.
1520     if cg.lto && cg.codegen_units > 1 {
1521         // This case is impossible to handle because LTO expects to be able
1522         // to combine the entire crate and all its dependencies into a
1523         // single compilation unit, but each codegen unit is in a separate
1524         // LLVM context, so they can't easily be combined.
1525         early_error(error_format, "can't perform LTO when using multiple codegen units");
1526     }
1527
1528     if cg.lto && debugging_opts.incremental.is_some() {
1529         early_error(error_format, "can't perform LTO when compiling incrementally");
1530     }
1531
1532     let mut prints = Vec::<PrintRequest>::new();
1533     if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1534         prints.push(PrintRequest::TargetCPUs);
1535         cg.target_cpu = None;
1536     };
1537     if cg.target_feature == "help" {
1538         prints.push(PrintRequest::TargetFeatures);
1539         cg.target_feature = "".to_string();
1540     }
1541     if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1542         prints.push(PrintRequest::RelocationModels);
1543         cg.relocation_model = None;
1544     }
1545     if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1546         prints.push(PrintRequest::CodeModels);
1547         cg.code_model = None;
1548     }
1549
1550     let cg = cg;
1551
1552     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1553     let target = matches.opt_str("target").unwrap_or(
1554         host_triple().to_string());
1555     let opt_level = {
1556         if matches.opt_present("O") {
1557             if cg.opt_level.is_some() {
1558                 early_error(error_format, "-O and -C opt-level both provided");
1559             }
1560             OptLevel::Default
1561         } else {
1562             match (cg.opt_level.as_ref().map(String::as_ref),
1563                    nightly_options::is_nightly_build()) {
1564                 (None, _) => OptLevel::No,
1565                 (Some("0"), _) => OptLevel::No,
1566                 (Some("1"), _) => OptLevel::Less,
1567                 (Some("2"), _) => OptLevel::Default,
1568                 (Some("3"), _) => OptLevel::Aggressive,
1569                 (Some("s"), true) => OptLevel::Size,
1570                 (Some("z"), true) => OptLevel::SizeMin,
1571                 (Some("s"), false) | (Some("z"), false) => {
1572                     early_error(error_format, &format!("the optimizations s or z are only \
1573                                                         accepted on the nightly compiler"));
1574                 },
1575                 (Some(arg), _) => {
1576                     early_error(error_format, &format!("optimization level needs to be \
1577                                                       between 0-3 (instead was `{}`)",
1578                                                      arg));
1579                 }
1580             }
1581         }
1582     };
1583     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1584     let debuginfo = if matches.opt_present("g") {
1585         if cg.debuginfo.is_some() {
1586             early_error(error_format, "-g and -C debuginfo both provided");
1587         }
1588         FullDebugInfo
1589     } else {
1590         match cg.debuginfo {
1591             None | Some(0) => NoDebugInfo,
1592             Some(1) => LimitedDebugInfo,
1593             Some(2) => FullDebugInfo,
1594             Some(arg) => {
1595                 early_error(error_format, &format!("debug info level needs to be between \
1596                                                   0-2 (instead was `{}`)",
1597                                                  arg));
1598             }
1599         }
1600     };
1601
1602     let mut search_paths = SearchPaths::new();
1603     for s in &matches.opt_strs("L") {
1604         search_paths.add_path(&s[..], error_format);
1605     }
1606
1607     let libs = matches.opt_strs("l").into_iter().map(|s| {
1608         // Parse string of the form "[KIND=]lib[:new_name]",
1609         // where KIND is one of "dylib", "framework", "static".
1610         let mut parts = s.splitn(2, '=');
1611         let kind = parts.next().unwrap();
1612         let (name, kind) = match (parts.next(), kind) {
1613             (None, name) => (name, None),
1614             (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
1615             (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
1616             (Some(name), "static") => (name, Some(cstore::NativeStatic)),
1617             (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
1618             (_, s) => {
1619                 early_error(error_format, &format!("unknown library kind `{}`, expected \
1620                                                   one of dylib, framework, or static",
1621                                                  s));
1622             }
1623         };
1624         if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
1625             early_error(error_format, &format!("the library kind 'static-nobundle' is only \
1626                                                 accepted on the nightly compiler"));
1627         }
1628         let mut name_parts = name.splitn(2, ':');
1629         let name = name_parts.next().unwrap();
1630         let new_name = name_parts.next();
1631         (name.to_string(), new_name.map(|n| n.to_string()), kind)
1632     }).collect();
1633
1634     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1635     let test = matches.opt_present("test");
1636
1637     prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1638         match &*s {
1639             "crate-name" => PrintRequest::CrateName,
1640             "file-names" => PrintRequest::FileNames,
1641             "sysroot" => PrintRequest::Sysroot,
1642             "cfg" => PrintRequest::Cfg,
1643             "target-list" => PrintRequest::TargetList,
1644             "target-cpus" => PrintRequest::TargetCPUs,
1645             "target-features" => PrintRequest::TargetFeatures,
1646             "relocation-models" => PrintRequest::RelocationModels,
1647             "code-models" => PrintRequest::CodeModels,
1648             "native-static-libs" => PrintRequest::NativeStaticLibs,
1649             "target-spec-json" => {
1650                 if nightly_options::is_unstable_enabled(matches) {
1651                     PrintRequest::TargetSpec
1652                 } else {
1653                     early_error(error_format,
1654                                 &format!("the `-Z unstable-options` flag must also be passed to \
1655                                           enable the target-spec-json print option"));
1656                 }
1657             },
1658             req => {
1659                 early_error(error_format, &format!("unknown print request `{}`", req))
1660             }
1661         }
1662     }));
1663
1664     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1665         early_warn(error_format, "-C remark will not show source locations without \
1666                                 --debuginfo");
1667     }
1668
1669     let mut externs = BTreeMap::new();
1670     for arg in &matches.opt_strs("extern") {
1671         let mut parts = arg.splitn(2, '=');
1672         let name = match parts.next() {
1673             Some(s) => s,
1674             None => early_error(error_format, "--extern value must not be empty"),
1675         };
1676         let location = match parts.next() {
1677             Some(s) => s,
1678             None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1679         };
1680
1681         externs.entry(name.to_string())
1682                .or_insert_with(BTreeSet::new)
1683                .insert(location.to_string());
1684     }
1685
1686     let crate_name = matches.opt_str("crate-name");
1687
1688     let incremental = debugging_opts.incremental.as_ref().map(|m| PathBuf::from(m));
1689
1690     (Options {
1691         crate_types,
1692         optimize: opt_level,
1693         debuginfo,
1694         lint_opts,
1695         lint_cap,
1696         describe_lints,
1697         output_types: OutputTypes(output_types),
1698         search_paths,
1699         maybe_sysroot: sysroot_opt,
1700         target_triple: target,
1701         test,
1702         incremental,
1703         debugging_opts,
1704         prints,
1705         cg,
1706         error_format,
1707         externs: Externs(externs),
1708         crate_name,
1709         alt_std_name: None,
1710         libs,
1711         unstable_features: UnstableFeatures::from_environment(),
1712         debug_assertions,
1713         actually_rustdoc: false,
1714     },
1715     cfg)
1716 }
1717
1718 pub fn parse_crate_types_from_list(list_list: Vec<String>)
1719                                    -> Result<Vec<CrateType>, String> {
1720     let mut crate_types: Vec<CrateType> = Vec::new();
1721     for unparsed_crate_type in &list_list {
1722         for part in unparsed_crate_type.split(',') {
1723             let new_part = match part {
1724                 "lib"       => default_lib_output(),
1725                 "rlib"      => CrateTypeRlib,
1726                 "staticlib" => CrateTypeStaticlib,
1727                 "dylib"     => CrateTypeDylib,
1728                 "cdylib"    => CrateTypeCdylib,
1729                 "bin"       => CrateTypeExecutable,
1730                 "proc-macro" => CrateTypeProcMacro,
1731                 _ => {
1732                     return Err(format!("unknown crate type: `{}`",
1733                                        part));
1734                 }
1735             };
1736             if !crate_types.contains(&new_part) {
1737                 crate_types.push(new_part)
1738             }
1739         }
1740     }
1741
1742     Ok(crate_types)
1743 }
1744
1745 pub mod nightly_options {
1746     use getopts;
1747     use syntax::feature_gate::UnstableFeatures;
1748     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
1749     use session::early_error;
1750
1751     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
1752         is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
1753     }
1754
1755     pub fn is_nightly_build() -> bool {
1756         UnstableFeatures::from_environment().is_nightly_build()
1757     }
1758
1759     pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
1760         let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
1761         let really_allows_unstable_options = UnstableFeatures::from_environment()
1762             .is_nightly_build();
1763
1764         for opt in flags.iter() {
1765             if opt.stability == OptionStability::Stable {
1766                 continue
1767             }
1768             if !matches.opt_present(opt.name) {
1769                 continue
1770             }
1771             if opt.name != "Z" && !has_z_unstable_option {
1772                 early_error(ErrorOutputType::default(),
1773                             &format!("the `-Z unstable-options` flag must also be passed to enable \
1774                                       the flag `{}`",
1775                                      opt.name));
1776             }
1777             if really_allows_unstable_options {
1778                 continue
1779             }
1780             match opt.stability {
1781                 OptionStability::Unstable => {
1782                     let msg = format!("the option `{}` is only accepted on the \
1783                                        nightly compiler", opt.name);
1784                     early_error(ErrorOutputType::default(), &msg);
1785                 }
1786                 OptionStability::Stable => {}
1787             }
1788         }
1789     }
1790 }
1791
1792 impl fmt::Display for CrateType {
1793     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1794         match *self {
1795             CrateTypeExecutable => "bin".fmt(f),
1796             CrateTypeDylib => "dylib".fmt(f),
1797             CrateTypeRlib => "rlib".fmt(f),
1798             CrateTypeStaticlib => "staticlib".fmt(f),
1799             CrateTypeCdylib => "cdylib".fmt(f),
1800             CrateTypeProcMacro => "proc-macro".fmt(f),
1801         }
1802     }
1803 }
1804
1805 /// Commandline arguments passed to the compiler have to be incorporated with
1806 /// the dependency tracking system for incremental compilation. This module
1807 /// provides some utilities to make this more convenient.
1808 ///
1809 /// The values of all commandline arguments that are relevant for dependency
1810 /// tracking are hashed into a single value that determines whether the
1811 /// incremental compilation cache can be re-used or not. This hashing is done
1812 /// via the DepTrackingHash trait defined below, since the standard Hash
1813 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
1814 /// the hash of which is order dependent, but we might not want the order of
1815 /// arguments to make a difference for the hash).
1816 ///
1817 /// However, since the value provided by Hash::hash often *is* suitable,
1818 /// especially for primitive types, there is the
1819 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
1820 /// Hash implementation for DepTrackingHash. It's important though that
1821 /// we have an opt-in scheme here, so one is hopefully forced to think about
1822 /// how the hash should be calculated when adding a new commandline argument.
1823 mod dep_tracking {
1824     use lint;
1825     use middle::cstore;
1826     use session::search_paths::{PathKind, SearchPaths};
1827     use std::collections::BTreeMap;
1828     use std::hash::Hash;
1829     use std::path::PathBuf;
1830     use std::collections::hash_map::DefaultHasher;
1831     use super::{Passes, CrateType, OptLevel, DebugInfoLevel,
1832                 OutputTypes, Externs, ErrorOutputType, Sanitizer};
1833     use syntax::feature_gate::UnstableFeatures;
1834     use rustc_back::{PanicStrategy, RelroLevel};
1835
1836     pub trait DepTrackingHash {
1837         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
1838     }
1839
1840     macro_rules! impl_dep_tracking_hash_via_hash {
1841         ($t:ty) => (
1842             impl DepTrackingHash for $t {
1843                 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1844                     Hash::hash(self, hasher);
1845                 }
1846             }
1847         )
1848     }
1849
1850     macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
1851         ($t:ty) => (
1852             impl DepTrackingHash for Vec<$t> {
1853                 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1854                     let mut elems: Vec<&$t> = self.iter().collect();
1855                     elems.sort();
1856                     Hash::hash(&elems.len(), hasher);
1857                     for (index, elem) in elems.iter().enumerate() {
1858                         Hash::hash(&index, hasher);
1859                         DepTrackingHash::hash(*elem, hasher, error_format);
1860                     }
1861                 }
1862             }
1863         );
1864     }
1865
1866     impl_dep_tracking_hash_via_hash!(bool);
1867     impl_dep_tracking_hash_via_hash!(usize);
1868     impl_dep_tracking_hash_via_hash!(u64);
1869     impl_dep_tracking_hash_via_hash!(String);
1870     impl_dep_tracking_hash_via_hash!(lint::Level);
1871     impl_dep_tracking_hash_via_hash!(Option<bool>);
1872     impl_dep_tracking_hash_via_hash!(Option<usize>);
1873     impl_dep_tracking_hash_via_hash!(Option<String>);
1874     impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
1875     impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
1876     impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
1877     impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
1878     impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
1879     impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
1880     impl_dep_tracking_hash_via_hash!(CrateType);
1881     impl_dep_tracking_hash_via_hash!(PanicStrategy);
1882     impl_dep_tracking_hash_via_hash!(RelroLevel);
1883     impl_dep_tracking_hash_via_hash!(Passes);
1884     impl_dep_tracking_hash_via_hash!(OptLevel);
1885     impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
1886     impl_dep_tracking_hash_via_hash!(UnstableFeatures);
1887     impl_dep_tracking_hash_via_hash!(Externs);
1888     impl_dep_tracking_hash_via_hash!(OutputTypes);
1889     impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
1890     impl_dep_tracking_hash_via_hash!(Sanitizer);
1891     impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
1892
1893     impl_dep_tracking_hash_for_sortable_vec_of!(String);
1894     impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
1895     impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
1896     impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
1897                                                  Option<cstore::NativeLibraryKind>));
1898     impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
1899     impl DepTrackingHash for SearchPaths {
1900         fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
1901             let mut elems: Vec<_> = self
1902                 .iter(PathKind::All)
1903                 .collect();
1904             elems.sort();
1905             Hash::hash(&elems, hasher);
1906         }
1907     }
1908
1909     impl<T1, T2> DepTrackingHash for (T1, T2)
1910         where T1: DepTrackingHash,
1911               T2: DepTrackingHash
1912     {
1913         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1914             Hash::hash(&0, hasher);
1915             DepTrackingHash::hash(&self.0, hasher, error_format);
1916             Hash::hash(&1, hasher);
1917             DepTrackingHash::hash(&self.1, hasher, error_format);
1918         }
1919     }
1920
1921     impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
1922         where T1: DepTrackingHash,
1923               T2: DepTrackingHash,
1924               T3: DepTrackingHash
1925     {
1926         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
1927             Hash::hash(&0, hasher);
1928             DepTrackingHash::hash(&self.0, hasher, error_format);
1929             Hash::hash(&1, hasher);
1930             DepTrackingHash::hash(&self.1, hasher, error_format);
1931             Hash::hash(&2, hasher);
1932             DepTrackingHash::hash(&self.2, hasher, error_format);
1933         }
1934     }
1935
1936     // This is a stable hash because BTreeMap is a sorted container
1937     pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
1938                        hasher: &mut DefaultHasher,
1939                        error_format: ErrorOutputType) {
1940         for (key, sub_hash) in sub_hashes {
1941             // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
1942             // the keys, as they are just plain strings
1943             Hash::hash(&key.len(), hasher);
1944             Hash::hash(key, hasher);
1945             sub_hash.hash(hasher, error_format);
1946         }
1947     }
1948 }
1949
1950 #[cfg(test)]
1951 mod tests {
1952     use dep_graph::DepGraph;
1953     use errors;
1954     use getopts;
1955     use lint;
1956     use middle::cstore;
1957     use session::config::{build_configuration, build_session_options_and_crate_config};
1958     use session::build_session;
1959     use std::collections::{BTreeMap, BTreeSet};
1960     use std::iter::FromIterator;
1961     use std::path::PathBuf;
1962     use super::{OutputType, OutputTypes, Externs};
1963     use rustc_back::{PanicStrategy, RelroLevel};
1964     use syntax::symbol::Symbol;
1965
1966     fn optgroups() -> getopts::Options {
1967         let mut opts = getopts::Options::new();
1968         for group in super::rustc_optgroups() {
1969             (group.apply)(&mut opts);
1970         }
1971         return opts
1972     }
1973
1974     fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
1975         BTreeMap::from_iter(entries.into_iter())
1976     }
1977
1978     fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
1979         BTreeSet::from_iter(entries.into_iter())
1980     }
1981
1982     // When the user supplies --test we should implicitly supply --cfg test
1983     #[test]
1984     fn test_switch_implies_cfg_test() {
1985         let dep_graph = DepGraph::new(false);
1986         let matches =
1987             &match optgroups().parse(&["--test".to_string()]) {
1988               Ok(m) => m,
1989               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1990             };
1991         let registry = errors::registry::Registry::new(&[]);
1992         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
1993         let sess = build_session(sessopts, &dep_graph, None, registry);
1994         let cfg = build_configuration(&sess, cfg);
1995         assert!(cfg.contains(&(Symbol::intern("test"), None)));
1996     }
1997
1998     // When the user supplies --test and --cfg test, don't implicitly add
1999     // another --cfg test
2000     #[test]
2001     fn test_switch_implies_cfg_test_unless_cfg_test() {
2002         let dep_graph = DepGraph::new(false);
2003         let matches =
2004             &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
2005               Ok(m) => m,
2006               Err(f) => {
2007                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
2008               }
2009             };
2010         let registry = errors::registry::Registry::new(&[]);
2011         let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2012         let sess = build_session(sessopts, &dep_graph, None, registry);
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             assert!(!sess.diagnostic().can_emit_warnings);
2030         }
2031
2032         {
2033             let matches = optgroups().parse(&[
2034                 "-Awarnings".to_string(),
2035                 "-Dwarnings".to_string()
2036             ]).unwrap();
2037             let registry = errors::registry::Registry::new(&[]);
2038             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2039             let sess = build_session(sessopts, &dep_graph, None, registry);
2040             assert!(sess.diagnostic().can_emit_warnings);
2041         }
2042
2043         {
2044             let matches = optgroups().parse(&[
2045                 "-Adead_code".to_string()
2046             ]).unwrap();
2047             let registry = errors::registry::Registry::new(&[]);
2048             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2049             let sess = build_session(sessopts, &dep_graph, None, registry);
2050             assert!(sess.diagnostic().can_emit_warnings);
2051         }
2052     }
2053
2054     #[test]
2055     fn test_output_types_tracking_hash_different_paths() {
2056         let mut v1 = super::basic_options();
2057         let mut v2 = super::basic_options();
2058         let mut v3 = super::basic_options();
2059
2060         v1.output_types = OutputTypes::new(&[(OutputType::Exe,
2061                                               Some(PathBuf::from("./some/thing")))]);
2062         v2.output_types = OutputTypes::new(&[(OutputType::Exe,
2063                                               Some(PathBuf::from("/some/thing")))]);
2064         v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2065
2066         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2067         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2068         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2069
2070         // Check clone
2071         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2072         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2073         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2074     }
2075
2076     #[test]
2077     fn test_output_types_tracking_hash_different_construction_order() {
2078         let mut v1 = super::basic_options();
2079         let mut v2 = super::basic_options();
2080
2081         v1.output_types = OutputTypes::new(&[
2082             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2083             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2084         ]);
2085
2086         v2.output_types = OutputTypes::new(&[
2087             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2088             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2089         ]);
2090
2091         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2092
2093         // Check clone
2094         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2095     }
2096
2097     #[test]
2098     fn test_externs_tracking_hash_different_values() {
2099         let mut v1 = super::basic_options();
2100         let mut v2 = super::basic_options();
2101         let mut v3 = super::basic_options();
2102
2103         v1.externs = Externs::new(mk_map(vec![
2104             (String::from("a"), mk_set(vec![String::from("b"),
2105                                             String::from("c")])),
2106             (String::from("d"), mk_set(vec![String::from("e"),
2107                                             String::from("f")])),
2108         ]));
2109
2110         v2.externs = Externs::new(mk_map(vec![
2111             (String::from("a"), mk_set(vec![String::from("b"),
2112                                             String::from("c")])),
2113             (String::from("X"), mk_set(vec![String::from("e"),
2114                                             String::from("f")])),
2115         ]));
2116
2117         v3.externs = Externs::new(mk_map(vec![
2118             (String::from("a"), mk_set(vec![String::from("b"),
2119                                             String::from("c")])),
2120             (String::from("d"), mk_set(vec![String::from("X"),
2121                                             String::from("f")])),
2122         ]));
2123
2124         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2125         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2126         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2127
2128         // Check clone
2129         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2130         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2131         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2132     }
2133
2134     #[test]
2135     fn test_externs_tracking_hash_different_construction_order() {
2136         let mut v1 = super::basic_options();
2137         let mut v2 = super::basic_options();
2138         let mut v3 = super::basic_options();
2139
2140         v1.externs = Externs::new(mk_map(vec![
2141             (String::from("a"), mk_set(vec![String::from("b"),
2142                                             String::from("c")])),
2143             (String::from("d"), mk_set(vec![String::from("e"),
2144                                             String::from("f")])),
2145         ]));
2146
2147         v2.externs = Externs::new(mk_map(vec![
2148             (String::from("d"), mk_set(vec![String::from("e"),
2149                                             String::from("f")])),
2150             (String::from("a"), mk_set(vec![String::from("b"),
2151                                             String::from("c")])),
2152         ]));
2153
2154         v3.externs = Externs::new(mk_map(vec![
2155             (String::from("a"), mk_set(vec![String::from("b"),
2156                                             String::from("c")])),
2157             (String::from("d"), mk_set(vec![String::from("f"),
2158                                             String::from("e")])),
2159         ]));
2160
2161         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2162         assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2163         assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2164
2165         // Check clone
2166         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2167         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2168         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2169     }
2170
2171     #[test]
2172     fn test_lints_tracking_hash_different_values() {
2173         let mut v1 = super::basic_options();
2174         let mut v2 = super::basic_options();
2175         let mut v3 = super::basic_options();
2176
2177         v1.lint_opts = vec![(String::from("a"), lint::Allow),
2178                             (String::from("b"), lint::Warn),
2179                             (String::from("c"), lint::Deny),
2180                             (String::from("d"), lint::Forbid)];
2181
2182         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2183                             (String::from("b"), lint::Warn),
2184                             (String::from("X"), lint::Deny),
2185                             (String::from("d"), lint::Forbid)];
2186
2187         v3.lint_opts = vec![(String::from("a"), lint::Allow),
2188                             (String::from("b"), lint::Warn),
2189                             (String::from("c"), lint::Forbid),
2190                             (String::from("d"), lint::Deny)];
2191
2192         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2193         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2194         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2195
2196         // Check clone
2197         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2198         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2199         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2200     }
2201
2202     #[test]
2203     fn test_lints_tracking_hash_different_construction_order() {
2204         let mut v1 = super::basic_options();
2205         let mut v2 = super::basic_options();
2206
2207         v1.lint_opts = vec![(String::from("a"), lint::Allow),
2208                             (String::from("b"), lint::Warn),
2209                             (String::from("c"), lint::Deny),
2210                             (String::from("d"), lint::Forbid)];
2211
2212         v2.lint_opts = vec![(String::from("a"), lint::Allow),
2213                             (String::from("c"), lint::Deny),
2214                             (String::from("b"), lint::Warn),
2215                             (String::from("d"), lint::Forbid)];
2216
2217         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2218
2219         // Check clone
2220         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2221         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2222     }
2223
2224     #[test]
2225     fn test_search_paths_tracking_hash_different_values() {
2226         let mut v1 = super::basic_options();
2227         let mut v2 = super::basic_options();
2228         let mut v3 = super::basic_options();
2229         let mut v4 = super::basic_options();
2230         let mut v5 = super::basic_options();
2231
2232         // Reference
2233         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2234         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2235         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2236         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2237         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2238
2239         // Native changed
2240         v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json);
2241         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2242         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2243         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2244         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2245
2246         // Crate changed
2247         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2248         v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json);
2249         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2250         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2251         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2252
2253         // Dependency changed
2254         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2255         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2256         v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json);
2257         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2258         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2259
2260         // Framework changed
2261         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2262         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2263         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2264         v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json);
2265         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2266
2267         // All changed
2268         v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2269         v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2270         v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2271         v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2272         v5.search_paths.add_path("all=XXX", super::ErrorOutputType::Json);
2273
2274         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2275         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2276         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2277         assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2278
2279         // Check clone
2280         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2281         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2282         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2283         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2284         assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2285     }
2286
2287     #[test]
2288     fn test_search_paths_tracking_hash_different_order() {
2289         let mut v1 = super::basic_options();
2290         let mut v2 = super::basic_options();
2291         let mut v3 = super::basic_options();
2292         let mut v4 = super::basic_options();
2293
2294         // Reference
2295         v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2296         v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2297         v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2298         v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2299         v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2300
2301         v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2302         v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2303         v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2304         v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2305         v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2306
2307         v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2308         v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2309         v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2310         v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2311         v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2312
2313         v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json);
2314         v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json);
2315         v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json);
2316         v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json);
2317         v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json);
2318
2319         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2320         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2321         assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2322
2323         // Check clone
2324         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2325         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2326         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2327         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2328     }
2329
2330     #[test]
2331     fn test_native_libs_tracking_hash_different_values() {
2332         let mut v1 = super::basic_options();
2333         let mut v2 = super::basic_options();
2334         let mut v3 = super::basic_options();
2335         let mut v4 = super::basic_options();
2336
2337         // Reference
2338         v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2339                        (String::from("b"), None, Some(cstore::NativeFramework)),
2340                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2341
2342         // Change label
2343         v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2344                        (String::from("X"), None, Some(cstore::NativeFramework)),
2345                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2346
2347         // Change kind
2348         v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2349                        (String::from("b"), None, Some(cstore::NativeStatic)),
2350                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2351
2352         // Change new-name
2353         v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2354                        (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
2355                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2356
2357         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2358         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2359         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2360
2361         // Check clone
2362         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2363         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2364         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2365         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2366     }
2367
2368     #[test]
2369     fn test_native_libs_tracking_hash_different_order() {
2370         let mut v1 = super::basic_options();
2371         let mut v2 = super::basic_options();
2372         let mut v3 = super::basic_options();
2373
2374         // Reference
2375         v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2376                        (String::from("b"), None, Some(cstore::NativeFramework)),
2377                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2378
2379         v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
2380                        (String::from("a"), None, Some(cstore::NativeStatic)),
2381                        (String::from("c"), None, Some(cstore::NativeUnknown))];
2382
2383         v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
2384                        (String::from("a"), None, Some(cstore::NativeStatic)),
2385                        (String::from("b"), None, Some(cstore::NativeFramework))];
2386
2387         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2388         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2389         assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2390
2391         // Check clone
2392         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2393         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2394         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2395     }
2396
2397     #[test]
2398     fn test_codegen_options_tracking_hash() {
2399         let reference = super::basic_options();
2400         let mut opts = super::basic_options();
2401
2402         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2403         opts.cg.ar = Some(String::from("abc"));
2404         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2405
2406         opts.cg.linker = Some(String::from("linker"));
2407         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2408
2409         opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2410         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2411
2412         opts.cg.link_dead_code = true;
2413         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2414
2415         opts.cg.rpath = true;
2416         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2417
2418         opts.cg.extra_filename = String::from("extra-filename");
2419         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2420
2421         opts.cg.codegen_units = 42;
2422         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2423
2424         opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2425                                                 String::from("pass2")]);
2426         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2427
2428         opts.cg.save_temps = true;
2429         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2430
2431
2432         // Make sure changing a [TRACKED] option changes the hash
2433         opts = reference.clone();
2434         opts.cg.lto = true;
2435         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2436
2437         opts = reference.clone();
2438         opts.cg.target_cpu = Some(String::from("abc"));
2439         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2440
2441         opts = reference.clone();
2442         opts.cg.target_feature = String::from("all the features, all of them");
2443         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2444
2445         opts = reference.clone();
2446         opts.cg.passes = vec![String::from("1"), String::from("2")];
2447         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2448
2449         opts = reference.clone();
2450         opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2451         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2452
2453         opts = reference.clone();
2454         opts.cg.overflow_checks = Some(true);
2455         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2456
2457         opts = reference.clone();
2458         opts.cg.no_prepopulate_passes = true;
2459         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2460
2461         opts = reference.clone();
2462         opts.cg.no_vectorize_loops = true;
2463         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2464
2465         opts = reference.clone();
2466         opts.cg.no_vectorize_slp = true;
2467         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2468
2469         opts = reference.clone();
2470         opts.cg.soft_float = true;
2471         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2472
2473         opts = reference.clone();
2474         opts.cg.prefer_dynamic = true;
2475         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2476
2477         opts = reference.clone();
2478         opts.cg.no_integrated_as = true;
2479         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2480
2481         opts = reference.clone();
2482         opts.cg.no_redzone = Some(true);
2483         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2484
2485         opts = reference.clone();
2486         opts.cg.relocation_model = Some(String::from("relocation model"));
2487         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2488
2489         opts = reference.clone();
2490         opts.cg.code_model = Some(String::from("code model"));
2491         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2492
2493         opts = reference.clone();
2494         opts.cg.metadata = vec![String::from("A"), String::from("B")];
2495         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2496
2497         opts = reference.clone();
2498         opts.cg.debuginfo = Some(0xdeadbeef);
2499         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2500
2501         opts = reference.clone();
2502         opts.cg.debuginfo = Some(0xba5eba11);
2503         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2504
2505         opts = reference.clone();
2506         opts.cg.debug_assertions = Some(true);
2507         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2508
2509         opts = reference.clone();
2510         opts.cg.inline_threshold = Some(0xf007ba11);
2511         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2512
2513         opts = reference.clone();
2514         opts.cg.panic = Some(PanicStrategy::Abort);
2515         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2516     }
2517
2518     #[test]
2519     fn test_debugging_options_tracking_hash() {
2520         let reference = super::basic_options();
2521         let mut opts = super::basic_options();
2522
2523         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2524         opts.debugging_opts.verbose = true;
2525         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2526         opts.debugging_opts.time_passes = true;
2527         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2528         opts.debugging_opts.count_llvm_insns = true;
2529         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2530         opts.debugging_opts.time_llvm_passes = true;
2531         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2532         opts.debugging_opts.input_stats = true;
2533         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2534         opts.debugging_opts.trans_stats = true;
2535         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2536         opts.debugging_opts.borrowck_stats = true;
2537         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2538         opts.debugging_opts.debug_llvm = true;
2539         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2540         opts.debugging_opts.meta_stats = true;
2541         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2542         opts.debugging_opts.print_link_args = true;
2543         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2544         opts.debugging_opts.print_llvm_passes = true;
2545         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2546         opts.debugging_opts.ast_json = true;
2547         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2548         opts.debugging_opts.ast_json_noexpand = true;
2549         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2550         opts.debugging_opts.ls = true;
2551         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2552         opts.debugging_opts.save_analysis = true;
2553         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2554         opts.debugging_opts.print_move_fragments = true;
2555         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2556         opts.debugging_opts.flowgraph_print_loans = true;
2557         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2558         opts.debugging_opts.flowgraph_print_moves = true;
2559         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2560         opts.debugging_opts.flowgraph_print_assigns = true;
2561         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2562         opts.debugging_opts.flowgraph_print_all = true;
2563         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2564         opts.debugging_opts.print_region_graph = true;
2565         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2566         opts.debugging_opts.parse_only = true;
2567         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2568         opts.debugging_opts.incremental = Some(String::from("abc"));
2569         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2570         opts.debugging_opts.dump_dep_graph = true;
2571         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2572         opts.debugging_opts.query_dep_graph = true;
2573         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2574         opts.debugging_opts.no_analysis = true;
2575         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2576         opts.debugging_opts.unstable_options = true;
2577         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2578         opts.debugging_opts.trace_macros = true;
2579         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2580         opts.debugging_opts.keep_hygiene_data = true;
2581         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2582         opts.debugging_opts.keep_ast = true;
2583         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2584         opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2585         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2586         opts.debugging_opts.dump_mir = Some(String::from("abc"));
2587         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2588         opts.debugging_opts.dump_mir_dir = Some(String::from("abc"));
2589         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2590
2591         // Make sure changing a [TRACKED] option changes the hash
2592         opts = reference.clone();
2593         opts.debugging_opts.asm_comments = true;
2594         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2595
2596         opts = reference.clone();
2597         opts.debugging_opts.no_verify = true;
2598         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2599
2600         opts = reference.clone();
2601         opts.debugging_opts.no_landing_pads = true;
2602         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2603
2604         opts = reference.clone();
2605         opts.debugging_opts.no_trans = true;
2606         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2607
2608         opts = reference.clone();
2609         opts.debugging_opts.treat_err_as_bug = true;
2610         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2611
2612         opts = reference.clone();
2613         opts.debugging_opts.continue_parse_after_error = true;
2614         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2615
2616         opts = reference.clone();
2617         opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2618         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2619
2620         opts = reference.clone();
2621         opts.debugging_opts.force_overflow_checks = Some(true);
2622         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2623
2624         opts = reference.clone();
2625         opts.debugging_opts.enable_nonzeroing_move_hints = true;
2626         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2627
2628         opts = reference.clone();
2629         opts.debugging_opts.show_span = Some(String::from("abc"));
2630         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2631
2632         opts = reference.clone();
2633         opts.debugging_opts.mir_opt_level = 3;
2634         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2635
2636         opts = reference.clone();
2637         opts.debugging_opts.relro_level = Some(RelroLevel::Full);
2638         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2639     }
2640 }