]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
Normalize EntryFnType variants to standard style
[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::DebugInfoLevel::*;
15
16 use std::str::FromStr;
17
18 use session::{early_error, early_warn, Session};
19 use session::search_paths::SearchPaths;
20
21 use ich::StableHashingContext;
22 use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
23 use rustc_target::spec::{Target, TargetTriple};
24 use rustc_data_structures::stable_hasher::ToStableHashKey;
25 use lint;
26 use middle::cstore;
27
28 use syntax::ast::{self, IntTy, UintTy};
29 use syntax::codemap::{FileName, FilePathMapping};
30 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
31 use syntax::parse::token;
32 use syntax::parse;
33 use syntax::symbol::Symbol;
34 use syntax::feature_gate::UnstableFeatures;
35
36 use errors::{ColorConfig, FatalError, Handler};
37
38 use getopts;
39 use std::collections::{BTreeMap, BTreeSet};
40 use std::collections::btree_map::Iter as BTreeMapIter;
41 use std::collections::btree_map::Keys as BTreeMapKeysIter;
42 use std::collections::btree_map::Values as BTreeMapValuesIter;
43
44 use std::{fmt, str};
45 use std::hash::Hasher;
46 use std::collections::hash_map::DefaultHasher;
47 use std::collections::HashSet;
48 use std::iter::FromIterator;
49 use std::path::{Path, PathBuf};
50
51 pub struct Config {
52     pub target: Target,
53     pub isize_ty: IntTy,
54     pub usize_ty: UintTy,
55 }
56
57 #[derive(Clone, Hash, Debug)]
58 pub enum Sanitizer {
59     Address,
60     Leak,
61     Memory,
62     Thread,
63 }
64
65 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
66 pub enum OptLevel {
67     No,         // -O0
68     Less,       // -O1
69     Default,    // -O2
70     Aggressive, // -O3
71     Size,       // -Os
72     SizeMin,    // -Oz
73 }
74
75 #[derive(Clone, Copy, PartialEq, Hash)]
76 pub enum Lto {
77     /// Don't do any LTO whatsoever
78     No,
79
80     /// Do a full crate graph LTO. The flavor is determined by the compiler
81     /// (currently the default is "fat").
82     Yes,
83
84     /// Do a full crate graph LTO with ThinLTO
85     Thin,
86
87     /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
88     /// units).
89     ThinLocal,
90
91     /// Do a full crate graph LTO with "fat" LTO
92     Fat,
93 }
94
95 #[derive(Clone, PartialEq, Hash)]
96 pub enum CrossLangLto {
97     LinkerPlugin(PathBuf),
98     LinkerPluginAuto,
99     Disabled
100 }
101
102 impl CrossLangLto {
103     pub fn enabled(&self) -> bool {
104         match *self {
105             CrossLangLto::LinkerPlugin(_) |
106             CrossLangLto::LinkerPluginAuto => true,
107             CrossLangLto::Disabled => false,
108         }
109     }
110 }
111
112 #[derive(Clone, Copy, PartialEq, Hash)]
113 pub enum DebugInfoLevel {
114     NoDebugInfo,
115     LimitedDebugInfo,
116     FullDebugInfo,
117 }
118
119 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
120 pub enum OutputType {
121     Bitcode,
122     Assembly,
123     LlvmAssembly,
124     Mir,
125     Metadata,
126     Object,
127     Exe,
128     DepInfo,
129 }
130
131
132 impl_stable_hash_for!(enum self::OutputType {
133     Bitcode,
134     Assembly,
135     LlvmAssembly,
136     Mir,
137     Metadata,
138     Object,
139     Exe,
140     DepInfo
141 });
142
143 impl<'a, 'tcx> ToStableHashKey<StableHashingContext<'a>> for OutputType {
144     type KeyType = OutputType;
145     #[inline]
146     fn to_stable_hash_key(&self, _: &StableHashingContext<'a>) -> Self::KeyType {
147         *self
148     }
149 }
150
151 impl OutputType {
152     fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
153         match *self {
154             OutputType::Exe | OutputType::DepInfo => true,
155             OutputType::Bitcode
156             | OutputType::Assembly
157             | OutputType::LlvmAssembly
158             | OutputType::Mir
159             | OutputType::Object
160             | OutputType::Metadata => false,
161         }
162     }
163
164     fn shorthand(&self) -> &'static str {
165         match *self {
166             OutputType::Bitcode => "llvm-bc",
167             OutputType::Assembly => "asm",
168             OutputType::LlvmAssembly => "llvm-ir",
169             OutputType::Mir => "mir",
170             OutputType::Object => "obj",
171             OutputType::Metadata => "metadata",
172             OutputType::Exe => "link",
173             OutputType::DepInfo => "dep-info",
174         }
175     }
176
177     fn from_shorthand(shorthand: &str) -> Option<Self> {
178         Some(match shorthand {
179             "asm" => OutputType::Assembly,
180             "llvm-ir" => OutputType::LlvmAssembly,
181             "mir" => OutputType::Mir,
182             "llvm-bc" => OutputType::Bitcode,
183             "obj" => OutputType::Object,
184             "metadata" => OutputType::Metadata,
185             "link" => OutputType::Exe,
186             "dep-info" => OutputType::DepInfo,
187             _ => return None,
188         })
189     }
190
191     fn shorthands_display() -> String {
192         format!(
193             "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
194             OutputType::Bitcode.shorthand(),
195             OutputType::Assembly.shorthand(),
196             OutputType::LlvmAssembly.shorthand(),
197             OutputType::Mir.shorthand(),
198             OutputType::Object.shorthand(),
199             OutputType::Metadata.shorthand(),
200             OutputType::Exe.shorthand(),
201             OutputType::DepInfo.shorthand(),
202         )
203     }
204
205     pub fn extension(&self) -> &'static str {
206         match *self {
207             OutputType::Bitcode => "bc",
208             OutputType::Assembly => "s",
209             OutputType::LlvmAssembly => "ll",
210             OutputType::Mir => "mir",
211             OutputType::Object => "o",
212             OutputType::Metadata => "rmeta",
213             OutputType::DepInfo => "d",
214             OutputType::Exe => "",
215         }
216     }
217 }
218
219 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
220 pub enum ErrorOutputType {
221     HumanReadable(ColorConfig),
222     Json(bool),
223     Short(ColorConfig),
224 }
225
226 impl Default for ErrorOutputType {
227     fn default() -> ErrorOutputType {
228         ErrorOutputType::HumanReadable(ColorConfig::Auto)
229     }
230 }
231
232 // Use tree-based collections to cheaply get a deterministic Hash implementation.
233 // DO NOT switch BTreeMap out for an unsorted container type! That would break
234 // dependency tracking for commandline arguments.
235 #[derive(Clone, Hash)]
236 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
237
238 impl_stable_hash_for!(tuple_struct self::OutputTypes {
239     map
240 });
241
242 impl OutputTypes {
243     pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
244         OutputTypes(BTreeMap::from_iter(
245             entries.iter().map(|&(k, ref v)| (k, v.clone())),
246         ))
247     }
248
249     pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
250         self.0.get(key)
251     }
252
253     pub fn contains_key(&self, key: &OutputType) -> bool {
254         self.0.contains_key(key)
255     }
256
257     pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
258         self.0.keys()
259     }
260
261     pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
262         self.0.values()
263     }
264
265     pub fn len(&self) -> usize {
266         self.0.len()
267     }
268
269     // True if any of the output types require codegen or linking.
270     pub fn should_codegen(&self) -> bool {
271         self.0.keys().any(|k| match *k {
272             OutputType::Bitcode
273             | OutputType::Assembly
274             | OutputType::LlvmAssembly
275             | OutputType::Mir
276             | OutputType::Object
277             | OutputType::Exe => true,
278             OutputType::Metadata | OutputType::DepInfo => false,
279         })
280     }
281 }
282
283 // Use tree-based collections to cheaply get a deterministic Hash implementation.
284 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
285 // would break dependency tracking for commandline arguments.
286 #[derive(Clone, Hash)]
287 pub struct Externs(BTreeMap<String, BTreeSet<String>>);
288
289 impl Externs {
290     pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
291         Externs(data)
292     }
293
294     pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
295         self.0.get(key)
296     }
297
298     pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
299         self.0.iter()
300     }
301 }
302
303 macro_rules! hash_option {
304     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
305     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
306         if $sub_hashes.insert(stringify!($opt_name),
307                               $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
308             bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
309         }
310     });
311     ($opt_name:ident,
312      $opt_expr:expr,
313      $sub_hashes:expr,
314      [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
315         if *$opt_expr == $warn_val {
316             early_warn($error_format, $warn_text)
317         }
318     });
319 }
320
321 macro_rules! top_level_options {
322     (pub struct Options { $(
323         $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
324     )* } ) => (
325         #[derive(Clone)]
326         pub struct Options {
327             $(pub $opt: $t),*
328         }
329
330         impl Options {
331             pub fn dep_tracking_hash(&self) -> u64 {
332                 let mut sub_hashes = BTreeMap::new();
333                 $({
334                     hash_option!($opt,
335                                  &self.$opt,
336                                  &mut sub_hashes,
337                                  [$dep_tracking_marker $($warn_val,
338                                                          $warn_text,
339                                                          self.error_format)*]);
340                 })*
341                 let mut hasher = DefaultHasher::new();
342                 dep_tracking::stable_hash(sub_hashes,
343                                           &mut hasher,
344                                           self.error_format);
345                 hasher.finish()
346             }
347         }
348     );
349 }
350
351 // The top-level commandline options struct
352 //
353 // For each option, one has to specify how it behaves with regard to the
354 // dependency tracking system of incremental compilation. This is done via the
355 // square-bracketed directive after the field type. The options are:
356 //
357 // [TRACKED]
358 // A change in the given field will cause the compiler to completely clear the
359 // incremental compilation cache before proceeding.
360 //
361 // [UNTRACKED]
362 // Incremental compilation is not influenced by this option.
363 //
364 // [UNTRACKED_WITH_WARNING(val, warning)]
365 // The option is incompatible with incremental compilation in some way. If it
366 // has the value `val`, the string `warning` is emitted as a warning.
367 //
368 // If you add a new option to this struct or one of the sub-structs like
369 // CodegenOptions, think about how it influences incremental compilation. If in
370 // doubt, specify [TRACKED], which is always "correct" but might lead to
371 // unnecessary re-compilation.
372 top_level_options!(
373     pub struct Options {
374         // The crate config requested for the session, which may be combined
375         // with additional crate configurations during the compile process
376         crate_types: Vec<CrateType> [TRACKED],
377         optimize: OptLevel [TRACKED],
378         // Include the debug_assertions flag into dependency tracking, since it
379         // can influence whether overflow checks are done or not.
380         debug_assertions: bool [TRACKED],
381         debuginfo: DebugInfoLevel [TRACKED],
382         lint_opts: Vec<(String, lint::Level)> [TRACKED],
383         lint_cap: Option<lint::Level> [TRACKED],
384         describe_lints: bool [UNTRACKED],
385         output_types: OutputTypes [TRACKED],
386         search_paths: SearchPaths [UNTRACKED],
387         libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
388         maybe_sysroot: Option<PathBuf> [TRACKED],
389
390         target_triple: TargetTriple [TRACKED],
391
392         test: bool [TRACKED],
393         error_format: ErrorOutputType [UNTRACKED],
394
395         // if Some, enable incremental compilation, using the given
396         // directory to store intermediate results
397         incremental: Option<PathBuf> [UNTRACKED],
398
399         debugging_opts: DebuggingOptions [TRACKED],
400         prints: Vec<PrintRequest> [UNTRACKED],
401         // Determines which borrow checker(s) to run. This is the parsed, sanitized
402         // version of `debugging_opts.borrowck`, which is just a plain string.
403         borrowck_mode: BorrowckMode [UNTRACKED],
404         cg: CodegenOptions [TRACKED],
405         externs: Externs [UNTRACKED],
406         crate_name: Option<String> [TRACKED],
407         // An optional name to use as the crate for std during std injection,
408         // written `extern crate name as std`. Defaults to `std`. Used by
409         // out-of-tree drivers.
410         alt_std_name: Option<String> [TRACKED],
411         // Indicates how the compiler should treat unstable features
412         unstable_features: UnstableFeatures [TRACKED],
413
414         // Indicates whether this run of the compiler is actually rustdoc. This
415         // is currently just a hack and will be removed eventually, so please
416         // try to not rely on this too much.
417         actually_rustdoc: bool [TRACKED],
418
419         // Specifications of codegen units / ThinLTO which are forced as a
420         // result of parsing command line options. These are not necessarily
421         // what rustc was invoked with, but massaged a bit to agree with
422         // commands like `--emit llvm-ir` which they're often incompatible with
423         // if we otherwise use the defaults of rustc.
424         cli_forced_codegen_units: Option<usize> [UNTRACKED],
425         cli_forced_thinlto_off: bool [UNTRACKED],
426
427         // Remap source path prefixes in all output (messages, object files, debug, etc)
428         remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
429
430         edition: Edition [TRACKED],
431     }
432 );
433
434 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
435 pub enum PrintRequest {
436     FileNames,
437     Sysroot,
438     CrateName,
439     Cfg,
440     TargetList,
441     TargetCPUs,
442     TargetFeatures,
443     RelocationModels,
444     CodeModels,
445     TlsModels,
446     TargetSpec,
447     NativeStaticLibs,
448 }
449
450 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
451 pub enum BorrowckMode {
452     Ast,
453     Mir,
454     Compare,
455     Migrate,
456 }
457
458 impl BorrowckMode {
459     /// Should we run the MIR-based borrow check, but also fall back
460     /// on the AST borrow check if the MIR-based one errors.
461     pub fn migrate(self) -> bool {
462         match self {
463             BorrowckMode::Ast => false,
464             BorrowckMode::Compare => false,
465             BorrowckMode::Mir => false,
466             BorrowckMode::Migrate => true,
467         }
468     }
469
470     /// Should we emit the AST-based borrow checker errors?
471     pub fn use_ast(self) -> bool {
472         match self {
473             BorrowckMode::Ast => true,
474             BorrowckMode::Compare => true,
475             BorrowckMode::Mir => false,
476             BorrowckMode::Migrate => false,
477         }
478     }
479     /// Should we emit the MIR-based borrow checker errors?
480     pub fn use_mir(self) -> bool {
481         match self {
482             BorrowckMode::Ast => false,
483             BorrowckMode::Compare => true,
484             BorrowckMode::Mir => true,
485             BorrowckMode::Migrate => true,
486         }
487     }
488 }
489
490 pub enum Input {
491     /// Load source from file
492     File(PathBuf),
493     Str {
494         /// String that is shown in place of a filename
495         name: FileName,
496         /// Anonymous source string
497         input: String,
498     },
499 }
500
501 impl Input {
502     pub fn filestem(&self) -> String {
503         match *self {
504             Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
505             Input::Str { .. } => "rust_out".to_string(),
506         }
507     }
508
509     pub fn get_input(&mut self) -> Option<&mut String> {
510         match *self {
511             Input::File(_) => None,
512             Input::Str { ref mut input, .. } => Some(input),
513         }
514     }
515 }
516
517 #[derive(Clone)]
518 pub struct OutputFilenames {
519     pub out_directory: PathBuf,
520     pub out_filestem: String,
521     pub single_output_file: Option<PathBuf>,
522     pub extra: String,
523     pub outputs: OutputTypes,
524 }
525
526 impl_stable_hash_for!(struct self::OutputFilenames {
527     out_directory,
528     out_filestem,
529     single_output_file,
530     extra,
531     outputs
532 });
533
534 pub const RUST_CGU_EXT: &str = "rcgu";
535
536 impl OutputFilenames {
537     pub fn path(&self, flavor: OutputType) -> PathBuf {
538         self.outputs
539             .get(&flavor)
540             .and_then(|p| p.to_owned())
541             .or_else(|| self.single_output_file.clone())
542             .unwrap_or_else(|| self.temp_path(flavor, None))
543     }
544
545     /// Get the path where a compilation artifact of the given type for the
546     /// given codegen unit should be placed on disk. If codegen_unit_name is
547     /// None, a path distinct from those of any codegen unit will be generated.
548     pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
549         let extension = flavor.extension();
550         self.temp_path_ext(extension, codegen_unit_name)
551     }
552
553     /// Like temp_path, but also supports things where there is no corresponding
554     /// OutputType, like no-opt-bitcode or lto-bitcode.
555     pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
556         let base = self.out_directory.join(&self.filestem());
557
558         let mut extension = String::new();
559
560         if let Some(codegen_unit_name) = codegen_unit_name {
561             extension.push_str(codegen_unit_name);
562         }
563
564         if !ext.is_empty() {
565             if !extension.is_empty() {
566                 extension.push_str(".");
567                 extension.push_str(RUST_CGU_EXT);
568                 extension.push_str(".");
569             }
570
571             extension.push_str(ext);
572         }
573
574         let path = base.with_extension(&extension[..]);
575         path
576     }
577
578     pub fn with_extension(&self, extension: &str) -> PathBuf {
579         self.out_directory
580             .join(&self.filestem())
581             .with_extension(extension)
582     }
583
584     pub fn filestem(&self) -> String {
585         format!("{}{}", self.out_filestem, self.extra)
586     }
587 }
588
589 pub fn host_triple() -> &'static str {
590     // Get the host triple out of the build environment. This ensures that our
591     // idea of the host triple is the same as for the set of libraries we've
592     // actually built.  We can't just take LLVM's host triple because they
593     // normalize all ix86 architectures to i386.
594     //
595     // Instead of grabbing the host triple (for the current host), we grab (at
596     // compile time) the target triple that this rustc is built with and
597     // calling that (at runtime) the host triple.
598     (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
599 }
600
601 /// Some reasonable defaults
602 pub fn basic_options() -> Options {
603     Options {
604         crate_types: Vec::new(),
605         optimize: OptLevel::No,
606         debuginfo: NoDebugInfo,
607         lint_opts: Vec::new(),
608         lint_cap: None,
609         describe_lints: false,
610         output_types: OutputTypes(BTreeMap::new()),
611         search_paths: SearchPaths::new(),
612         maybe_sysroot: None,
613         target_triple: TargetTriple::from_triple(host_triple()),
614         test: false,
615         incremental: None,
616         debugging_opts: basic_debugging_options(),
617         prints: Vec::new(),
618         borrowck_mode: BorrowckMode::Ast,
619         cg: basic_codegen_options(),
620         error_format: ErrorOutputType::default(),
621         externs: Externs(BTreeMap::new()),
622         crate_name: None,
623         alt_std_name: None,
624         libs: Vec::new(),
625         unstable_features: UnstableFeatures::Disallow,
626         debug_assertions: true,
627         actually_rustdoc: false,
628         cli_forced_codegen_units: None,
629         cli_forced_thinlto_off: false,
630         remap_path_prefix: Vec::new(),
631         edition: DEFAULT_EDITION,
632     }
633 }
634
635 impl Options {
636     /// True if there is a reason to build the dep graph.
637     pub fn build_dep_graph(&self) -> bool {
638         self.incremental.is_some() || self.debugging_opts.dump_dep_graph
639             || self.debugging_opts.query_dep_graph
640     }
641
642     #[inline(always)]
643     pub fn enable_dep_node_debug_strs(&self) -> bool {
644         cfg!(debug_assertions)
645             && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
646     }
647
648     pub fn file_path_mapping(&self) -> FilePathMapping {
649         FilePathMapping::new(self.remap_path_prefix.clone())
650     }
651
652     /// True if there will be an output file generated
653     pub fn will_create_output_file(&self) -> bool {
654         !self.debugging_opts.parse_only && // The file is just being parsed
655             !self.debugging_opts.ls // The file is just being queried
656     }
657 }
658
659 // The type of entry function, so
660 // users can have their own entry
661 // functions
662 #[derive(Copy, Clone, PartialEq)]
663 pub enum EntryFnType {
664     Main,
665     Start,
666 }
667
668 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
669 pub enum CrateType {
670     Executable,
671     Dylib,
672     Rlib,
673     Staticlib,
674     Cdylib,
675     ProcMacro,
676 }
677
678 #[derive(Clone, Hash)]
679 pub enum Passes {
680     Some(Vec<String>),
681     All,
682 }
683
684 impl Passes {
685     pub fn is_empty(&self) -> bool {
686         match *self {
687             Passes::Some(ref v) => v.is_empty(),
688             Passes::All => false,
689         }
690     }
691 }
692
693 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
694 /// at once. The goal of this macro is to define an interface that can be
695 /// programmatically used by the option parser in order to initialize the struct
696 /// without hardcoding field names all over the place.
697 ///
698 /// The goal is to invoke this macro once with the correct fields, and then this
699 /// macro generates all necessary code. The main gotcha of this macro is the
700 /// cgsetters module which is a bunch of generated code to parse an option into
701 /// its respective field in the struct. There are a few hand-written parsers for
702 /// parsing specific types of values in this module.
703 macro_rules! options {
704     ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
705      $buildfn:ident, $prefix:expr, $outputname:expr,
706      $stat:ident, $mod_desc:ident, $mod_set:ident,
707      $($opt:ident : $t:ty = (
708         $init:expr,
709         $parse:ident,
710         [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
711         $desc:expr)
712      ),* ,) =>
713 (
714     #[derive(Clone)]
715     pub struct $struct_name { $(pub $opt: $t),* }
716
717     pub fn $defaultfn() -> $struct_name {
718         $struct_name { $($opt: $init),* }
719     }
720
721     pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
722     {
723         let mut op = $defaultfn();
724         for option in matches.opt_strs($prefix) {
725             let mut iter = option.splitn(2, '=');
726             let key = iter.next().unwrap();
727             let value = iter.next();
728             let option_to_lookup = key.replace("-", "_");
729             let mut found = false;
730             for &(candidate, setter, opt_type_desc, _) in $stat {
731                 if option_to_lookup != candidate { continue }
732                 if !setter(&mut op, value) {
733                     match (value, opt_type_desc) {
734                         (Some(..), None) => {
735                             early_error(error_format, &format!("{} option `{}` takes no \
736                                                               value", $outputname, key))
737                         }
738                         (None, Some(type_desc)) => {
739                             early_error(error_format, &format!("{0} option `{1}` requires \
740                                                               {2} ({3} {1}=<value>)",
741                                                              $outputname, key,
742                                                              type_desc, $prefix))
743                         }
744                         (Some(value), Some(type_desc)) => {
745                             early_error(error_format, &format!("incorrect value `{}` for {} \
746                                                               option `{}` - {} was expected",
747                                                              value, $outputname,
748                                                              key, type_desc))
749                         }
750                         (None, None) => bug!()
751                     }
752                 }
753                 found = true;
754                 break;
755             }
756             if !found {
757                 early_error(error_format, &format!("unknown {} option: `{}`",
758                                                  $outputname, key));
759             }
760         }
761         return op;
762     }
763
764     impl<'a> dep_tracking::DepTrackingHash for $struct_name {
765
766         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
767             let mut sub_hashes = BTreeMap::new();
768             $({
769                 hash_option!($opt,
770                              &self.$opt,
771                              &mut sub_hashes,
772                              [$dep_tracking_marker $($dep_warn_val,
773                                                      $dep_warn_text,
774                                                      error_format)*]);
775             })*
776             dep_tracking::stable_hash(sub_hashes, hasher, error_format);
777         }
778     }
779
780     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
781     pub const $stat: &'static [(&'static str, $setter_name,
782                                      Option<&'static str>, &'static str)] =
783         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
784
785     #[allow(non_upper_case_globals, dead_code)]
786     mod $mod_desc {
787         pub const parse_bool: Option<&'static str> = None;
788         pub const parse_opt_bool: Option<&'static str> =
789             Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
790         pub const parse_string: Option<&'static str> = Some("a string");
791         pub const parse_string_push: Option<&'static str> = Some("a string");
792         pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
793         pub const parse_opt_string: Option<&'static str> = Some("a string");
794         pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
795         pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
796         pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
797         pub const parse_uint: Option<&'static str> = Some("a number");
798         pub const parse_passes: Option<&'static str> =
799             Some("a space-separated list of passes, or `all`");
800         pub const parse_opt_uint: Option<&'static str> =
801             Some("a number");
802         pub const parse_panic_strategy: Option<&'static str> =
803             Some("either `panic` or `abort`");
804         pub const parse_relro_level: Option<&'static str> =
805             Some("one of: `full`, `partial`, or `off`");
806         pub const parse_sanitizer: Option<&'static str> =
807             Some("one of: `address`, `leak`, `memory` or `thread`");
808         pub const parse_linker_flavor: Option<&'static str> =
809             Some(::rustc_target::spec::LinkerFlavor::one_of());
810         pub const parse_optimization_fuel: Option<&'static str> =
811             Some("crate=integer");
812         pub const parse_unpretty: Option<&'static str> =
813             Some("`string` or `string=string`");
814         pub const parse_lto: Option<&'static str> =
815             Some("one of `thin`, `fat`, or omitted");
816         pub const parse_cross_lang_lto: Option<&'static str> =
817             Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `no-link`, \
818                   or the path to the linker plugin");
819     }
820
821     #[allow(dead_code)]
822     mod $mod_set {
823         use super::{$struct_name, Passes, Sanitizer, Lto, CrossLangLto};
824         use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
825         use std::path::PathBuf;
826
827         $(
828             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
829                 $parse(&mut cg.$opt, v)
830             }
831         )*
832
833         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
834             match v {
835                 Some(..) => false,
836                 None => { *slot = true; true }
837             }
838         }
839
840         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
841             match v {
842                 Some(s) => {
843                     match s {
844                         "n" | "no" | "off" => {
845                             *slot = Some(false);
846                         }
847                         "y" | "yes" | "on" => {
848                             *slot = Some(true);
849                         }
850                         _ => { return false; }
851                     }
852
853                     true
854                 },
855                 None => { *slot = Some(true); true }
856             }
857         }
858
859         fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
860             match v {
861                 Some(s) => { *slot = Some(s.to_string()); true },
862                 None => false,
863             }
864         }
865
866         fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
867             match v {
868                 Some(s) => { *slot = Some(PathBuf::from(s)); true },
869                 None => false,
870             }
871         }
872
873         fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
874             match v {
875                 Some(s) => { *slot = s.to_string(); true },
876                 None => false,
877             }
878         }
879
880         fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
881             match v {
882                 Some(s) => { slot.push(s.to_string()); true },
883                 None => false,
884             }
885         }
886
887         fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
888             match v {
889                 Some(s) => { slot.push(PathBuf::from(s)); true },
890                 None => false,
891             }
892         }
893
894         fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
895                       -> bool {
896             match v {
897                 Some(s) => {
898                     slot.extend(s.split_whitespace().map(|s| s.to_string()));
899                     true
900                 },
901                 None => false,
902             }
903         }
904
905         fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
906                       -> bool {
907             match v {
908                 Some(s) => {
909                     let v = s.split_whitespace().map(|s| s.to_string()).collect();
910                     *slot = Some(v);
911                     true
912                 },
913                 None => false,
914             }
915         }
916
917         fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
918             match v.and_then(|s| s.parse().ok()) {
919                 Some(i) => { *slot = i; true },
920                 None => false
921             }
922         }
923
924         fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
925             match v {
926                 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
927                 None => { *slot = None; false }
928             }
929         }
930
931         fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
932             match v {
933                 Some("all") => {
934                     *slot = Passes::All;
935                     true
936                 }
937                 v => {
938                     let mut passes = vec![];
939                     if parse_list(&mut passes, v) {
940                         *slot = Passes::Some(passes);
941                         true
942                     } else {
943                         false
944                     }
945                 }
946             }
947         }
948
949         fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
950             match v {
951                 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
952                 Some("abort") => *slot = Some(PanicStrategy::Abort),
953                 _ => return false
954             }
955             true
956         }
957
958         fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
959             match v {
960                 Some(s) => {
961                     match s.parse::<RelroLevel>() {
962                         Ok(level) => *slot = Some(level),
963                         _ => return false
964                     }
965                 },
966                 _ => return false
967             }
968             true
969         }
970
971         fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
972             match v {
973                 Some("address") => *slote = Some(Sanitizer::Address),
974                 Some("leak") => *slote = Some(Sanitizer::Leak),
975                 Some("memory") => *slote = Some(Sanitizer::Memory),
976                 Some("thread") => *slote = Some(Sanitizer::Thread),
977                 _ => return false,
978             }
979             true
980         }
981
982         fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
983             match v.and_then(LinkerFlavor::from_str) {
984                 Some(lf) => *slote = Some(lf),
985                 _ => return false,
986             }
987             true
988         }
989
990         fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
991             match v {
992                 None => false,
993                 Some(s) => {
994                     let parts = s.split('=').collect::<Vec<_>>();
995                     if parts.len() != 2 { return false; }
996                     let crate_name = parts[0].to_string();
997                     let fuel = parts[1].parse::<u64>();
998                     if fuel.is_err() { return false; }
999                     *slot = Some((crate_name, fuel.unwrap()));
1000                     true
1001                 }
1002             }
1003         }
1004
1005         fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1006             match v {
1007                 None => false,
1008                 Some(s) if s.split('=').count() <= 2 => {
1009                     *slot = Some(s.to_string());
1010                     true
1011                 }
1012                 _ => false,
1013             }
1014         }
1015
1016         fn parse_lto(slot: &mut Lto, v: Option<&str>) -> bool {
1017             *slot = match v {
1018                 None => Lto::Yes,
1019                 Some("thin") => Lto::Thin,
1020                 Some("fat") => Lto::Fat,
1021                 Some(_) => return false,
1022             };
1023             true
1024         }
1025
1026         fn parse_cross_lang_lto(slot: &mut CrossLangLto, v: Option<&str>) -> bool {
1027             if v.is_some() {
1028                 let mut bool_arg = None;
1029                 if parse_opt_bool(&mut bool_arg, v) {
1030                     *slot = if bool_arg.unwrap() {
1031                         CrossLangLto::LinkerPluginAuto
1032                     } else {
1033                         CrossLangLto::Disabled
1034                     };
1035                     return true
1036                 }
1037             }
1038
1039             *slot = match v {
1040                 None => CrossLangLto::LinkerPluginAuto,
1041                 Some(path) => CrossLangLto::LinkerPlugin(PathBuf::from(path)),
1042             };
1043             true
1044         }
1045     }
1046 ) }
1047
1048 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1049          build_codegen_options, "C", "codegen",
1050          CG_OPTIONS, cg_type_desc, cgsetters,
1051     ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1052         "this option is deprecated and does nothing"),
1053     linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1054         "system linker to link outputs with"),
1055     link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1056         "a single extra argument to append to the linker invocation (can be used several times)"),
1057     link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1058         "extra arguments to append to the linker invocation (space separated)"),
1059     link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1060         "don't let linker strip dead code (turning it on can be used for code coverage)"),
1061     lto: Lto = (Lto::No, parse_lto, [TRACKED],
1062         "perform LLVM link-time optimizations"),
1063     target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1064         "select target processor (rustc --print target-cpus for details)"),
1065     target_feature: String = ("".to_string(), parse_string, [TRACKED],
1066         "target specific attributes (rustc --print target-features for details)"),
1067     passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1068         "a list of extra LLVM passes to run (space separated)"),
1069     llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1070         "a list of arguments to pass to llvm (space separated)"),
1071     save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1072         "`-C save-temps` might not produce all requested temporary products \
1073          when incremental compilation is enabled.")],
1074         "save all temporary output files during compilation"),
1075     rpath: bool = (false, parse_bool, [UNTRACKED],
1076         "set rpath values in libs/exes"),
1077     overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1078         "use overflow checks for integer arithmetic"),
1079     no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1080         "don't pre-populate the pass manager with a list of passes"),
1081     no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1082         "don't run the loop vectorization optimization passes"),
1083     no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1084         "don't run LLVM's SLP vectorization pass"),
1085     soft_float: bool = (false, parse_bool, [TRACKED],
1086         "use soft float ABI (*eabihf targets only)"),
1087     prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1088         "prefer dynamic linking to static linking"),
1089     no_integrated_as: bool = (false, parse_bool, [TRACKED],
1090         "use an external assembler rather than LLVM's integrated one"),
1091     no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1092         "disable the use of the redzone"),
1093     relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1094          "choose the relocation model to use (rustc --print relocation-models for details)"),
1095     code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1096          "choose the code model to use (rustc --print code-models for details)"),
1097     metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1098          "metadata to mangle symbol names with"),
1099     extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
1100          "extra data to put in each output filename"),
1101     codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1102         "divide crate into N units to optimize in parallel"),
1103     remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1104         "print remarks for these optimization passes (space separated, or \"all\")"),
1105     no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1106         "the --no-stack-check flag is deprecated and does nothing"),
1107     debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1108         "debug info emission level, 0 = no debug info, 1 = line tables only, \
1109          2 = full debug info with variable and type information"),
1110     opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1111         "optimize with possible levels 0-3, s, or z"),
1112     force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1113         "force use of the frame pointers"),
1114     debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1115         "explicitly enable the cfg(debug_assertions) directive"),
1116     inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1117         "set the threshold for inlining a function (default: 225)"),
1118     panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1119         [TRACKED], "panic strategy to compile crate with"),
1120     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1121           "enable incremental compilation"),
1122 }
1123
1124 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1125          build_debugging_options, "Z", "debugging",
1126          DB_OPTIONS, db_type_desc, dbsetters,
1127     codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1128         "the backend to use"),
1129     verbose: bool = (false, parse_bool, [UNTRACKED],
1130         "in general, enable more debug printouts"),
1131     span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1132         "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1133     identify_regions: bool = (false, parse_bool, [UNTRACKED],
1134         "make unnamed regions display as '# (where # is some non-ident unique id)"),
1135     emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
1136         "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
1137     borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1138         "select which borrowck is used (`ast`, `mir`, `migrate`, or `compare`)"),
1139     two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1140         "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1141     two_phase_beyond_autoref: bool = (false, parse_bool, [UNTRACKED],
1142         "when using two-phase-borrows, allow two phases even for non-autoref `&mut` borrows"),
1143     time_passes: bool = (false, parse_bool, [UNTRACKED],
1144         "measure time of each rustc pass"),
1145     count_llvm_insns: bool = (false, parse_bool,
1146         [UNTRACKED_WITH_WARNING(true,
1147         "The output generated by `-Z count_llvm_insns` might not be reliable \
1148          when used with incremental compilation")],
1149         "count where LLVM instrs originate"),
1150     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1151         "The output of `-Z time-llvm-passes` will only reflect timings of \
1152          re-codegened modules when used with incremental compilation" )],
1153         "measure time of each LLVM pass"),
1154     input_stats: bool = (false, parse_bool, [UNTRACKED],
1155         "gather statistics about the input"),
1156     codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1157         "The output of `-Z codegen-stats` might not be accurate when incremental \
1158          compilation is enabled")],
1159         "gather codegen statistics"),
1160     asm_comments: bool = (false, parse_bool, [TRACKED],
1161         "generate comments into the assembly (may change behavior)"),
1162     verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1163         "verify LLVM IR"),
1164     borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1165         "gather borrowck statistics"),
1166     no_landing_pads: bool = (false, parse_bool, [TRACKED],
1167         "omit landing pads for unwinding"),
1168     fewer_names: bool = (false, parse_bool, [TRACKED],
1169         "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1170     meta_stats: bool = (false, parse_bool, [UNTRACKED],
1171         "gather metadata statistics"),
1172     print_link_args: bool = (false, parse_bool, [UNTRACKED],
1173         "print the arguments passed to the linker"),
1174     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1175         "prints the llvm optimization passes being run"),
1176     ast_json: bool = (false, parse_bool, [UNTRACKED],
1177         "print the AST as JSON and halt"),
1178     query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1179         "execute queries on a thread pool with N threads"),
1180     ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1181         "print the pre-expansion AST as JSON and halt"),
1182     ls: bool = (false, parse_bool, [UNTRACKED],
1183         "list the symbols defined by a library crate"),
1184     save_analysis: bool = (false, parse_bool, [UNTRACKED],
1185         "write syntax and type analysis (in JSON format) information, in \
1186          addition to normal output"),
1187     flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1188         "include loan analysis data in -Z unpretty flowgraph output"),
1189     flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1190         "include move analysis data in -Z unpretty flowgraph output"),
1191     flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1192         "include assignment analysis data in -Z unpretty flowgraph output"),
1193     flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1194         "include all dataflow analysis data in -Z unpretty flowgraph output"),
1195     print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1196          "prints region inference graph. \
1197           Use with RUST_REGION_GRAPH=help for more info"),
1198     parse_only: bool = (false, parse_bool, [UNTRACKED],
1199           "parse only; do not compile, assemble, or link"),
1200     no_codegen: bool = (false, parse_bool, [TRACKED],
1201           "run all passes except codegen; no output"),
1202     treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1203           "treat all errors that occur as bugs"),
1204     report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1205           "immediately print bugs registered with `delay_span_bug`"),
1206     external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1207           "show macro backtraces even for non-local macros"),
1208     teach: bool = (false, parse_bool, [TRACKED],
1209           "show extended diagnostic help"),
1210     continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1211           "attempt to recover from parse errors (experimental)"),
1212     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1213           "enable incremental compilation (experimental)"),
1214     incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1215           "enable incremental compilation support for queries (experimental)"),
1216     incremental_info: bool = (false, parse_bool, [UNTRACKED],
1217         "print high-level information about incremental reuse (or the lack thereof)"),
1218     incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1219         "dump hash information in textual format to stdout"),
1220     incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1221         "verify incr. comp. hashes of green query instances"),
1222     incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1223         "ignore spans during ICH computation -- used for testing"),
1224     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1225           "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1226     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1227           "enable queries of the dependency graph for regression testing"),
1228     profile_queries: bool = (false, parse_bool, [UNTRACKED],
1229           "trace and profile the queries of the incremental compilation framework"),
1230     profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1231           "trace and profile the queries and keys of the incremental compilation framework"),
1232     no_analysis: bool = (false, parse_bool, [UNTRACKED],
1233           "parse and expand the source, but run no analysis"),
1234     extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1235         "load extra plugins"),
1236     unstable_options: bool = (false, parse_bool, [UNTRACKED],
1237           "adds unstable command line options to rustc interface"),
1238     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1239           "force overflow checks on or off"),
1240     trace_macros: bool = (false, parse_bool, [UNTRACKED],
1241           "for every macro invocation, print its name and arguments"),
1242     debug_macros: bool = (false, parse_bool, [TRACKED],
1243           "emit line numbers debug info inside macros"),
1244     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1245           "don't clear the hygiene data after analysis"),
1246     keep_ast: bool = (false, parse_bool, [UNTRACKED],
1247           "keep the AST after lowering it to HIR"),
1248     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1249           "show spans for compiler debugging (expr|pat|ty)"),
1250     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1251           "print layout information for each type encountered"),
1252     print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1253           "print the result of the monomorphization collection pass"),
1254     mir_opt_level: usize = (1, parse_uint, [TRACKED],
1255           "set the MIR optimization level (0-3, default: 1)"),
1256     mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1257           "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1258     arg_align_attributes: bool = (false, parse_bool, [TRACKED],
1259           "emit align metadata for reference arguments"),
1260     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1261           "dump MIR state at various points in transforms"),
1262     dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1263           "the directory the MIR is dumped into"),
1264     dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1265           "in addition to `.mir` files, create graphviz `.dot` files"),
1266     dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1267           "if set, exclude the pass number when dumping MIR (used in tests)"),
1268     mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1269           "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1270            contains unsafe block, only validate arguments; 2: always emit full validation)"),
1271     perf_stats: bool = (false, parse_bool, [UNTRACKED],
1272           "print some performance-related statistics"),
1273     hir_stats: bool = (false, parse_bool, [UNTRACKED],
1274           "print some statistics about AST and HIR"),
1275     mir_stats: bool = (false, parse_bool, [UNTRACKED],
1276           "print some statistics about MIR"),
1277     always_encode_mir: bool = (false, parse_bool, [TRACKED],
1278           "encode MIR of all functions into the crate metadata"),
1279     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1280           "pass `-install_name @rpath/...` to the macOS linker"),
1281     sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1282                                    "Use a sanitizer"),
1283     linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1284                                            "Linker flavor"),
1285     fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1286         "set the optimization fuel quota for a crate"),
1287     print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1288         "make Rustc print the total optimization fuel used by a crate"),
1289     force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1290         "force all crates to be `rustc_private` unstable"),
1291     pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1292         "a single extra argument to prepend the linker invocation (can be used several times)"),
1293     pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1294         "extra arguments to prepend to the linker invocation (space separated)"),
1295     profile: bool = (false, parse_bool, [TRACKED],
1296                      "insert profiling code"),
1297     pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
1298         "Generate PGO profile data, to a given file, or to the default \
1299          location if it's empty."),
1300     pgo_use: String = (String::new(), parse_string, [TRACKED],
1301         "Use PGO profile data from the given profile file."),
1302     disable_instrumentation_preinliner: bool =
1303         (false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \
1304         useful for profiling / PGO."),
1305     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1306         "choose which RELRO level to use"),
1307     disable_ast_check_for_mutation_in_guard: bool = (false, parse_bool, [UNTRACKED],
1308         "skip AST-based mutation-in-guard check (mir-borrowck provides more precise check)"),
1309     nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED],
1310         "when tracking region error causes, accept subminimal results for faster execution."),
1311     nll_facts: bool = (false, parse_bool, [UNTRACKED],
1312                        "dump facts from NLL analysis into side files"),
1313     disable_nll_user_type_assert: bool = (false, parse_bool, [UNTRACKED],
1314         "disable user provided type assertion in NLL"),
1315     nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1316         "in match codegen, do not include ReadForMatch statements (used by mir-borrowck)"),
1317     polonius: bool = (false, parse_bool, [UNTRACKED],
1318         "enable polonius-based borrow-checker"),
1319     codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1320         "generate a graphical HTML report of time spent in codegen and LLVM"),
1321     thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1322         "enable ThinLTO when possible"),
1323     inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1324         "control whether #[inline] functions are in all cgus"),
1325     tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1326          "choose the TLS model to use (rustc --print tls-models for details)"),
1327     saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1328         "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1329          the max/min integer respectively, and NaN is mapped to 0"),
1330     lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1331         "rewrite operators on i128 and u128 into lang item calls (typically provided \
1332          by compiler-builtins) so codegen doesn't need to support them,
1333          overriding the default for the current target"),
1334     human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1335         "generate human-readable, predictable names for codegen units"),
1336     dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1337         "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1338          themselves"),
1339     unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1340         "Present the input source, unstable (and less-pretty) variants;
1341         valid types are any of the types for `--pretty`, as well as:
1342         `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1343         `everybody_loops` (all function bodies replaced with `loop {}`),
1344         `hir` (the HIR), `hir,identified`, or
1345         `hir,typed` (HIR with types for each node)."),
1346     run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1347           "run `dsymutil` and delete intermediate object files"),
1348     ui_testing: bool = (false, parse_bool, [UNTRACKED],
1349           "format compiler diagnostics in a way that's better suitable for UI testing"),
1350     embed_bitcode: bool = (false, parse_bool, [TRACKED],
1351           "embed LLVM bitcode in object files"),
1352     strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1353         "tell the linker to strip debuginfo when building without debuginfo enabled."),
1354     share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1355           "make the current crate share its generic instantiations"),
1356     chalk: bool = (false, parse_bool, [TRACKED],
1357           "enable the experimental Chalk-based trait solving engine"),
1358     cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED],
1359           "generate build artifacts that are compatible with linker-based LTO."),
1360     no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1361           "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1362     no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1363         "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1364     crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1365         "inject the given attribute in the crate"),
1366     self_profile: bool = (false, parse_bool, [UNTRACKED],
1367           "run the self profiler"),
1368     profile_json: bool = (false, parse_bool, [UNTRACKED],
1369           "output a json file with profiler results"),
1370 }
1371
1372 pub fn default_lib_output() -> CrateType {
1373     CrateType::Rlib
1374 }
1375
1376 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1377     let end = &sess.target.target.target_endian;
1378     let arch = &sess.target.target.arch;
1379     let wordsz = &sess.target.target.target_pointer_width;
1380     let os = &sess.target.target.target_os;
1381     let env = &sess.target.target.target_env;
1382     let vendor = &sess.target.target.target_vendor;
1383     let min_atomic_width = sess.target.target.min_atomic_width();
1384     let max_atomic_width = sess.target.target.max_atomic_width();
1385     let atomic_cas = sess.target.target.options.atomic_cas;
1386
1387     let mut ret = HashSet::new();
1388     // Target bindings.
1389     ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1390     if let Some(ref fam) = sess.target.target.options.target_family {
1391         ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1392         if fam == "windows" || fam == "unix" {
1393             ret.insert((Symbol::intern(fam), None));
1394         }
1395     }
1396     ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1397     ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1398     ret.insert((
1399         Symbol::intern("target_pointer_width"),
1400         Some(Symbol::intern(wordsz)),
1401     ));
1402     ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1403     ret.insert((
1404         Symbol::intern("target_vendor"),
1405         Some(Symbol::intern(vendor)),
1406     ));
1407     if sess.target.target.options.has_elf_tls {
1408         ret.insert((Symbol::intern("target_thread_local"), None));
1409     }
1410     for &i in &[8, 16, 32, 64, 128] {
1411         if i >= min_atomic_width && i <= max_atomic_width {
1412             let s = i.to_string();
1413             ret.insert((
1414                 Symbol::intern("target_has_atomic"),
1415                 Some(Symbol::intern(&s)),
1416             ));
1417             if &s == wordsz {
1418                 ret.insert((
1419                     Symbol::intern("target_has_atomic"),
1420                     Some(Symbol::intern("ptr")),
1421                 ));
1422             }
1423         }
1424     }
1425     if atomic_cas {
1426         ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("cas"))));
1427     }
1428     if sess.opts.debug_assertions {
1429         ret.insert((Symbol::intern("debug_assertions"), None));
1430     }
1431     if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1432         ret.insert((Symbol::intern("proc_macro"), None));
1433     }
1434     return ret;
1435 }
1436
1437 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1438     // Combine the configuration requested by the session (command line) with
1439     // some default and generated configuration items
1440     let default_cfg = default_configuration(sess);
1441     // If the user wants a test runner, then add the test cfg
1442     if sess.opts.test {
1443         user_cfg.insert((Symbol::intern("test"), None));
1444     }
1445     user_cfg.extend(default_cfg.iter().cloned());
1446     user_cfg
1447 }
1448
1449 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1450     let target = match Target::search(&opts.target_triple) {
1451         Ok(t) => t,
1452         Err(e) => {
1453             sp.struct_fatal(&format!("Error loading target specification: {}", e))
1454                 .help("Use `--print target-list` for a list of built-in targets")
1455                 .emit();
1456             FatalError.raise();
1457         }
1458     };
1459
1460     let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1461         "16" => (ast::IntTy::I16, ast::UintTy::U16),
1462         "32" => (ast::IntTy::I32, ast::UintTy::U32),
1463         "64" => (ast::IntTy::I64, ast::UintTy::U64),
1464         w => sp.fatal(&format!(
1465             "target specification was invalid: \
1466              unrecognized target-pointer-width {}",
1467             w
1468         )).raise(),
1469     };
1470
1471     Config {
1472         target,
1473         isize_ty,
1474         usize_ty,
1475     }
1476 }
1477
1478 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1479 pub enum OptionStability {
1480     Stable,
1481
1482     Unstable,
1483 }
1484
1485 pub struct RustcOptGroup {
1486     pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1487     pub name: &'static str,
1488     pub stability: OptionStability,
1489 }
1490
1491 impl RustcOptGroup {
1492     pub fn is_stable(&self) -> bool {
1493         self.stability == OptionStability::Stable
1494     }
1495
1496     pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1497     where
1498         F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1499     {
1500         RustcOptGroup {
1501             name,
1502             apply: Box::new(f),
1503             stability: OptionStability::Stable,
1504         }
1505     }
1506
1507     pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1508     where
1509         F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1510     {
1511         RustcOptGroup {
1512             name,
1513             apply: Box::new(f),
1514             stability: OptionStability::Unstable,
1515         }
1516     }
1517 }
1518
1519 // The `opt` local module holds wrappers around the `getopts` API that
1520 // adds extra rustc-specific metadata to each option; such metadata
1521 // is exposed by .  The public
1522 // functions below ending with `_u` are the functions that return
1523 // *unstable* options, i.e. options that are only enabled when the
1524 // user also passes the `-Z unstable-options` debugging flag.
1525 mod opt {
1526     // The `fn opt_u` etc below are written so that we can use them
1527     // in the future; do not warn about them not being used right now.
1528     #![allow(dead_code)]
1529
1530     use getopts;
1531     use super::RustcOptGroup;
1532
1533     pub type R = RustcOptGroup;
1534     pub type S = &'static str;
1535
1536     fn stable<F>(name: S, f: F) -> R
1537     where
1538         F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1539     {
1540         RustcOptGroup::stable(name, f)
1541     }
1542
1543     fn unstable<F>(name: S, f: F) -> R
1544     where
1545         F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1546     {
1547         RustcOptGroup::unstable(name, f)
1548     }
1549
1550     fn longer(a: S, b: S) -> S {
1551         if a.len() > b.len() {
1552             a
1553         } else {
1554             b
1555         }
1556     }
1557
1558     pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1559         stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1560     }
1561     pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1562         stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1563     }
1564     pub fn flag_s(a: S, b: S, c: S) -> R {
1565         stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1566     }
1567     pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1568         stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1569     }
1570     pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1571         stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1572     }
1573
1574     pub fn opt(a: S, b: S, c: S, d: S) -> R {
1575         unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1576     }
1577     pub fn multi(a: S, b: S, c: S, d: S) -> R {
1578         unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1579     }
1580     pub fn flag(a: S, b: S, c: S) -> R {
1581         unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1582     }
1583     pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1584         unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1585     }
1586     pub fn flagmulti(a: S, b: S, c: S) -> R {
1587         unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1588     }
1589 }
1590
1591 /// Returns the "short" subset of the rustc command line options,
1592 /// including metadata for each option, such as whether the option is
1593 /// part of the stable long-term interface for rustc.
1594 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1595     vec![
1596         opt::flag_s("h", "help", "Display this message"),
1597         opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1598         opt::multi_s(
1599             "L",
1600             "",
1601             "Add a directory to the library search path. The
1602                              optional KIND can be one of dependency, crate, native,
1603                              framework or all (the default).",
1604             "[KIND=]PATH",
1605         ),
1606         opt::multi_s(
1607             "l",
1608             "",
1609             "Link the generated crate(s) to the specified native
1610                              library NAME. The optional KIND can be one of
1611                              static, dylib, or framework. If omitted, dylib is
1612                              assumed.",
1613             "[KIND=]NAME",
1614         ),
1615         opt::multi_s(
1616             "",
1617             "crate-type",
1618             "Comma separated list of types of crates
1619                                     for the compiler to emit",
1620             "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1621         ),
1622         opt::opt_s(
1623             "",
1624             "crate-name",
1625             "Specify the name of the crate being built",
1626             "NAME",
1627         ),
1628         opt::multi_s(
1629             "",
1630             "emit",
1631             "Comma separated list of types of output for \
1632              the compiler to emit",
1633             "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1634         ),
1635         opt::multi_s(
1636             "",
1637             "print",
1638             "Comma separated list of compiler information to \
1639              print on stdout",
1640             "[crate-name|file-names|sysroot|cfg|target-list|\
1641              target-cpus|target-features|relocation-models|\
1642              code-models|tls-models|target-spec-json|native-static-libs]",
1643         ),
1644         opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1645         opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1646         opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1647         opt::opt_s(
1648             "",
1649             "out-dir",
1650             "Write output to compiler-chosen filename \
1651              in <dir>",
1652             "DIR",
1653         ),
1654         opt::opt_s(
1655             "",
1656             "explain",
1657             "Provide a detailed explanation of an error \
1658              message",
1659             "OPT",
1660         ),
1661         opt::flag_s("", "test", "Build a test harness"),
1662         opt::opt_s(
1663             "",
1664             "target",
1665             "Target triple for which the code is compiled",
1666             "TARGET",
1667         ),
1668         opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1669         opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1670         opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1671         opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1672         opt::multi_s(
1673             "",
1674             "cap-lints",
1675             "Set the most restrictive lint level. \
1676              More restrictive lints are capped at this \
1677              level",
1678             "LEVEL",
1679         ),
1680         opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1681         opt::flag_s("V", "version", "Print version info and exit"),
1682         opt::flag_s("v", "verbose", "Use verbose output"),
1683     ]
1684 }
1685
1686 /// Returns all rustc command line options, including metadata for
1687 /// each option, such as whether the option is part of the stable
1688 /// long-term interface for rustc.
1689 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1690     let mut opts = rustc_short_optgroups();
1691     opts.extend(vec![
1692         opt::multi_s(
1693             "",
1694             "extern",
1695             "Specify where an external rust library is located",
1696             "NAME=PATH",
1697         ),
1698         opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1699         opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1700         opt::opt_s(
1701             "",
1702             "error-format",
1703             "How errors and other messages are produced",
1704             "human|json|short",
1705         ),
1706         opt::opt_s(
1707             "",
1708             "color",
1709             "Configure coloring of output:
1710                                  auto   = colorize, if output goes to a tty (default);
1711                                  always = always colorize output;
1712                                  never  = never colorize output",
1713             "auto|always|never",
1714         ),
1715         opt::opt(
1716             "",
1717             "pretty",
1718             "Pretty-print the input instead of compiling;
1719                   valid types are: `normal` (un-annotated source),
1720                   `expanded` (crates expanded), or
1721                   `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1722             "TYPE",
1723         ),
1724         opt::opt_s(
1725             "",
1726             "edition",
1727             "Specify which edition of the compiler to use when compiling code.",
1728             EDITION_NAME_LIST,
1729         ),
1730         opt::multi_s(
1731             "",
1732             "remap-path-prefix",
1733             "Remap source names in all output (compiler messages and output files)",
1734             "FROM=TO",
1735         ),
1736     ]);
1737     opts
1738 }
1739
1740 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1741 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
1742     cfgspecs
1743         .into_iter()
1744         .map(|s| {
1745             let sess = parse::ParseSess::new(FilePathMapping::empty());
1746             let mut parser =
1747                 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1748
1749             let meta_item = panictry!(parser.parse_meta_item());
1750
1751             if parser.token != token::Eof {
1752                 early_error(
1753                     ErrorOutputType::default(),
1754                     &format!("invalid --cfg argument: {}", s),
1755                 )
1756             } else if meta_item.is_meta_item_list() {
1757                 let msg = format!(
1758                     "invalid predicate in --cfg command line argument: `{}`",
1759                     meta_item.ident
1760                 );
1761                 early_error(ErrorOutputType::default(), &msg)
1762             }
1763
1764             (meta_item.name(), meta_item.value_str())
1765         })
1766         .collect::<ast::CrateConfig>()
1767 }
1768
1769 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1770                             error_format: ErrorOutputType)
1771                             -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1772     let mut lint_opts = vec![];
1773     let mut describe_lints = false;
1774
1775     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1776         for lint_name in matches.opt_strs(level.as_str()) {
1777             if lint_name == "help" {
1778                 describe_lints = true;
1779             } else {
1780                 lint_opts.push((lint_name.replace("-", "_"), level));
1781             }
1782         }
1783     }
1784
1785     let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1786         lint::Level::from_str(&cap)
1787             .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1788     });
1789     (lint_opts, describe_lints, lint_cap)
1790 }
1791
1792 pub fn build_session_options_and_crate_config(
1793     matches: &getopts::Matches,
1794 ) -> (Options, ast::CrateConfig) {
1795     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1796         Some("auto") => ColorConfig::Auto,
1797         Some("always") => ColorConfig::Always,
1798         Some("never") => ColorConfig::Never,
1799
1800         None => ColorConfig::Auto,
1801
1802         Some(arg) => early_error(
1803             ErrorOutputType::default(),
1804             &format!(
1805                 "argument for --color must be auto, \
1806                  always or never (instead was `{}`)",
1807                 arg
1808             ),
1809         ),
1810     };
1811
1812     let edition = match matches.opt_str("edition") {
1813         Some(arg) => match Edition::from_str(&arg){
1814             Ok(edition) => edition,
1815             Err(_) => early_error(
1816                 ErrorOutputType::default(),
1817                 &format!(
1818                     "argument for --edition must be one of: \
1819                     {}. (instead was `{}`)",
1820                     EDITION_NAME_LIST,
1821                     arg
1822                 ),
1823             ),
1824         }
1825         None => DEFAULT_EDITION,
1826     };
1827
1828     if !edition.is_stable() && !nightly_options::is_nightly_build() {
1829         early_error(
1830                 ErrorOutputType::default(),
1831                 &format!(
1832                     "Edition {} is unstable and only \
1833                     available for nightly builds of rustc.",
1834                     edition,
1835                 )
1836         )
1837     }
1838
1839
1840     // We need the opts_present check because the driver will send us Matches
1841     // with only stable options if no unstable options are used. Since error-format
1842     // is unstable, it will not be present. We have to use opts_present not
1843     // opt_present because the latter will panic.
1844     let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1845         match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1846             Some("human") => ErrorOutputType::HumanReadable(color),
1847             Some("json") => ErrorOutputType::Json(false),
1848             Some("pretty-json") => ErrorOutputType::Json(true),
1849             Some("short") => ErrorOutputType::Short(color),
1850             None => ErrorOutputType::HumanReadable(color),
1851
1852             Some(arg) => early_error(
1853                 ErrorOutputType::HumanReadable(color),
1854                 &format!(
1855                     "argument for --error-format must be `human`, `json` or \
1856                      `short` (instead was `{}`)",
1857                     arg
1858                 ),
1859             ),
1860         }
1861     } else {
1862         ErrorOutputType::HumanReadable(color)
1863     };
1864
1865     let unparsed_crate_types = matches.opt_strs("crate-type");
1866     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1867         .unwrap_or_else(|e| early_error(error_format, &e[..]));
1868
1869     let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
1870
1871     let mut debugging_opts = build_debugging_options(matches, error_format);
1872
1873     if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1874         early_error(
1875             ErrorOutputType::Json(false),
1876             "--error-format=pretty-json is unstable",
1877         );
1878     }
1879
1880     if debugging_opts.pgo_gen.is_some() && !debugging_opts.pgo_use.is_empty() {
1881         early_error(
1882             error_format,
1883             "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
1884         );
1885     }
1886
1887     let mut output_types = BTreeMap::new();
1888     if !debugging_opts.parse_only {
1889         for list in matches.opt_strs("emit") {
1890             for output_type in list.split(',') {
1891                 let mut parts = output_type.splitn(2, '=');
1892                 let shorthand = parts.next().unwrap();
1893                 let output_type = match OutputType::from_shorthand(shorthand) {
1894                     Some(output_type) => output_type,
1895                     None => early_error(
1896                         error_format,
1897                         &format!(
1898                             "unknown emission type: `{}` - expected one of: {}",
1899                             shorthand,
1900                             OutputType::shorthands_display(),
1901                         ),
1902                     ),
1903                 };
1904                 let path = parts.next().map(PathBuf::from);
1905                 output_types.insert(output_type, path);
1906             }
1907         }
1908     };
1909     if output_types.is_empty() {
1910         output_types.insert(OutputType::Exe, None);
1911     }
1912
1913     let mut cg = build_codegen_options(matches, error_format);
1914     let mut codegen_units = cg.codegen_units;
1915     let mut disable_thinlto = false;
1916
1917     // Issue #30063: if user requests llvm-related output to one
1918     // particular path, disable codegen-units.
1919     let incompatible: Vec<_> = output_types
1920         .iter()
1921         .map(|ot_path| ot_path.0)
1922         .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
1923         .map(|ot| ot.shorthand())
1924         .collect();
1925     if !incompatible.is_empty() {
1926         match codegen_units {
1927             Some(n) if n > 1 => {
1928                 if matches.opt_present("o") {
1929                     for ot in &incompatible {
1930                         early_warn(
1931                             error_format,
1932                             &format!(
1933                                 "--emit={} with -o incompatible with \
1934                                  -C codegen-units=N for N > 1",
1935                                 ot
1936                             ),
1937                         );
1938                     }
1939                     early_warn(error_format, "resetting to default -C codegen-units=1");
1940                     codegen_units = Some(1);
1941                     disable_thinlto = true;
1942                 }
1943             }
1944             _ => {
1945                 codegen_units = Some(1);
1946                 disable_thinlto = true;
1947             }
1948         }
1949     }
1950
1951     if debugging_opts.query_threads == Some(0) {
1952         early_error(
1953             error_format,
1954             "Value for query threads must be a positive nonzero integer",
1955         );
1956     }
1957
1958     if debugging_opts.query_threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
1959         early_error(
1960             error_format,
1961             "Optimization fuel is incompatible with multiple query threads",
1962         );
1963     }
1964
1965     if codegen_units == Some(0) {
1966         early_error(
1967             error_format,
1968             "Value for codegen units must be a positive nonzero integer",
1969         );
1970     }
1971
1972     let incremental = match (&debugging_opts.incremental, &cg.incremental) {
1973         (&Some(ref path1), &Some(ref path2)) => {
1974             if path1 != path2 {
1975                 early_error(
1976                     error_format,
1977                     &format!(
1978                         "conflicting paths for `-Z incremental` and \
1979                          `-C incremental` specified: {} versus {}",
1980                         path1, path2
1981                     ),
1982                 );
1983             } else {
1984                 Some(path1)
1985             }
1986         }
1987         (&Some(ref path), &None) => Some(path),
1988         (&None, &Some(ref path)) => Some(path),
1989         (&None, &None) => None,
1990     }.map(|m| PathBuf::from(m));
1991
1992     if cg.lto != Lto::No && incremental.is_some() {
1993         early_error(
1994             error_format,
1995             "can't perform LTO when compiling incrementally",
1996         );
1997     }
1998
1999     if debugging_opts.profile && incremental.is_some() {
2000         early_error(
2001             error_format,
2002             "can't instrument with gcov profiling when compiling incrementally",
2003         );
2004     }
2005
2006     let mut prints = Vec::<PrintRequest>::new();
2007     if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2008         prints.push(PrintRequest::TargetCPUs);
2009         cg.target_cpu = None;
2010     };
2011     if cg.target_feature == "help" {
2012         prints.push(PrintRequest::TargetFeatures);
2013         cg.target_feature = "".to_string();
2014     }
2015     if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2016         prints.push(PrintRequest::RelocationModels);
2017         cg.relocation_model = None;
2018     }
2019     if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2020         prints.push(PrintRequest::CodeModels);
2021         cg.code_model = None;
2022     }
2023     if debugging_opts
2024         .tls_model
2025         .as_ref()
2026         .map_or(false, |s| s == "help")
2027     {
2028         prints.push(PrintRequest::TlsModels);
2029         debugging_opts.tls_model = None;
2030     }
2031
2032     let cg = cg;
2033
2034     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2035     let target_triple = if let Some(target) = matches.opt_str("target") {
2036         if target.ends_with(".json") {
2037             let path = Path::new(&target);
2038             match TargetTriple::from_path(&path) {
2039                 Ok(triple) => triple,
2040                 Err(_) => {
2041                     early_error(error_format, &format!("target file {:?} does not exist", path))
2042                 }
2043             }
2044         } else {
2045             TargetTriple::TargetTriple(target)
2046         }
2047     } else {
2048         TargetTriple::from_triple(host_triple())
2049     };
2050     let opt_level = {
2051         if matches.opt_present("O") {
2052             if cg.opt_level.is_some() {
2053                 early_error(error_format, "-O and -C opt-level both provided");
2054             }
2055             OptLevel::Default
2056         } else {
2057             match cg.opt_level.as_ref().map(String::as_ref) {
2058                 None => OptLevel::No,
2059                 Some("0") => OptLevel::No,
2060                 Some("1") => OptLevel::Less,
2061                 Some("2") => OptLevel::Default,
2062                 Some("3") => OptLevel::Aggressive,
2063                 Some("s") => OptLevel::Size,
2064                 Some("z") => OptLevel::SizeMin,
2065                 Some(arg) => {
2066                     early_error(
2067                         error_format,
2068                         &format!(
2069                             "optimization level needs to be \
2070                              between 0-3 (instead was `{}`)",
2071                             arg
2072                         ),
2073                     );
2074                 }
2075             }
2076         }
2077     };
2078     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2079     let debuginfo = if matches.opt_present("g") {
2080         if cg.debuginfo.is_some() {
2081             early_error(error_format, "-g and -C debuginfo both provided");
2082         }
2083         FullDebugInfo
2084     } else {
2085         match cg.debuginfo {
2086             None | Some(0) => NoDebugInfo,
2087             Some(1) => LimitedDebugInfo,
2088             Some(2) => FullDebugInfo,
2089             Some(arg) => {
2090                 early_error(
2091                     error_format,
2092                     &format!(
2093                         "debug info level needs to be between \
2094                          0-2 (instead was `{}`)",
2095                         arg
2096                     ),
2097                 );
2098             }
2099         }
2100     };
2101
2102     let mut search_paths = SearchPaths::new();
2103     for s in &matches.opt_strs("L") {
2104         search_paths.add_path(&s[..], error_format);
2105     }
2106
2107     let libs = matches
2108         .opt_strs("l")
2109         .into_iter()
2110         .map(|s| {
2111             // Parse string of the form "[KIND=]lib[:new_name]",
2112             // where KIND is one of "dylib", "framework", "static".
2113             let mut parts = s.splitn(2, '=');
2114             let kind = parts.next().unwrap();
2115             let (name, kind) = match (parts.next(), kind) {
2116                 (None, name) => (name, None),
2117                 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2118                 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2119                 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2120                 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2121                 (_, s) => {
2122                     early_error(
2123                         error_format,
2124                         &format!(
2125                             "unknown library kind `{}`, expected \
2126                              one of dylib, framework, or static",
2127                             s
2128                         ),
2129                     );
2130                 }
2131             };
2132             if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2133                 early_error(
2134                     error_format,
2135                     &format!(
2136                         "the library kind 'static-nobundle' is only \
2137                          accepted on the nightly compiler"
2138                     ),
2139                 );
2140             }
2141             let mut name_parts = name.splitn(2, ':');
2142             let name = name_parts.next().unwrap();
2143             let new_name = name_parts.next();
2144             (name.to_string(), new_name.map(|n| n.to_string()), kind)
2145         })
2146         .collect();
2147
2148     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2149     let test = matches.opt_present("test");
2150
2151     prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2152         "crate-name" => PrintRequest::CrateName,
2153         "file-names" => PrintRequest::FileNames,
2154         "sysroot" => PrintRequest::Sysroot,
2155         "cfg" => PrintRequest::Cfg,
2156         "target-list" => PrintRequest::TargetList,
2157         "target-cpus" => PrintRequest::TargetCPUs,
2158         "target-features" => PrintRequest::TargetFeatures,
2159         "relocation-models" => PrintRequest::RelocationModels,
2160         "code-models" => PrintRequest::CodeModels,
2161         "tls-models" => PrintRequest::TlsModels,
2162         "native-static-libs" => PrintRequest::NativeStaticLibs,
2163         "target-spec-json" => {
2164             if nightly_options::is_unstable_enabled(matches) {
2165                 PrintRequest::TargetSpec
2166             } else {
2167                 early_error(
2168                     error_format,
2169                     &format!(
2170                         "the `-Z unstable-options` flag must also be passed to \
2171                          enable the target-spec-json print option"
2172                     ),
2173                 );
2174             }
2175         }
2176         req => early_error(error_format, &format!("unknown print request `{}`", req)),
2177     }));
2178
2179     let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2180         None | Some("ast") => BorrowckMode::Ast,
2181         Some("mir") => BorrowckMode::Mir,
2182         Some("compare") => BorrowckMode::Compare,
2183         Some("migrate") => BorrowckMode::Migrate,
2184         Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2185     };
2186
2187     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
2188         early_warn(
2189             error_format,
2190             "-C remark will not show source locations without \
2191              --debuginfo",
2192         );
2193     }
2194
2195     let mut externs = BTreeMap::new();
2196     for arg in &matches.opt_strs("extern") {
2197         let mut parts = arg.splitn(2, '=');
2198         let name = match parts.next() {
2199             Some(s) => s,
2200             None => early_error(error_format, "--extern value must not be empty"),
2201         };
2202         let location = match parts.next() {
2203             Some(s) => s,
2204             None => early_error(
2205                 error_format,
2206                 "--extern value must be of the format `foo=bar`",
2207             ),
2208         };
2209
2210         externs
2211             .entry(name.to_string())
2212             .or_insert_with(BTreeSet::new)
2213             .insert(location.to_string());
2214     }
2215
2216     let crate_name = matches.opt_str("crate-name");
2217
2218     let remap_path_prefix = matches
2219         .opt_strs("remap-path-prefix")
2220         .into_iter()
2221         .map(|remap| {
2222             let mut parts = remap.rsplitn(2, '='); // reverse iterator
2223             let to = parts.next();
2224             let from = parts.next();
2225             match (from, to) {
2226                 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2227                 _ => early_error(
2228                     error_format,
2229                     "--remap-path-prefix must contain '=' between FROM and TO",
2230                 ),
2231             }
2232         })
2233         .collect();
2234
2235     (
2236         Options {
2237             crate_types,
2238             optimize: opt_level,
2239             debuginfo,
2240             lint_opts,
2241             lint_cap,
2242             describe_lints,
2243             output_types: OutputTypes(output_types),
2244             search_paths,
2245             maybe_sysroot: sysroot_opt,
2246             target_triple,
2247             test,
2248             incremental,
2249             debugging_opts,
2250             prints,
2251             borrowck_mode,
2252             cg,
2253             error_format,
2254             externs: Externs(externs),
2255             crate_name,
2256             alt_std_name: None,
2257             libs,
2258             unstable_features: UnstableFeatures::from_environment(),
2259             debug_assertions,
2260             actually_rustdoc: false,
2261             cli_forced_codegen_units: codegen_units,
2262             cli_forced_thinlto_off: disable_thinlto,
2263             remap_path_prefix,
2264             edition,
2265         },
2266         cfg,
2267     )
2268 }
2269
2270 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2271     let mut crate_types: Vec<CrateType> = Vec::new();
2272     for unparsed_crate_type in &list_list {
2273         for part in unparsed_crate_type.split(',') {
2274             let new_part = match part {
2275                 "lib" => default_lib_output(),
2276                 "rlib" => CrateType::Rlib,
2277                 "staticlib" => CrateType::Staticlib,
2278                 "dylib" => CrateType::Dylib,
2279                 "cdylib" => CrateType::Cdylib,
2280                 "bin" => CrateType::Executable,
2281                 "proc-macro" => CrateType::ProcMacro,
2282                 _ => {
2283                     return Err(format!("unknown crate type: `{}`", part));
2284                 }
2285             };
2286             if !crate_types.contains(&new_part) {
2287                 crate_types.push(new_part)
2288             }
2289         }
2290     }
2291
2292     Ok(crate_types)
2293 }
2294
2295 pub mod nightly_options {
2296     use getopts;
2297     use syntax::feature_gate::UnstableFeatures;
2298     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2299     use session::early_error;
2300
2301     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2302         is_nightly_build()
2303             && matches
2304                 .opt_strs("Z")
2305                 .iter()
2306                 .any(|x| *x == "unstable-options")
2307     }
2308
2309     pub fn is_nightly_build() -> bool {
2310         UnstableFeatures::from_environment().is_nightly_build()
2311     }
2312
2313     pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2314         let has_z_unstable_option = matches
2315             .opt_strs("Z")
2316             .iter()
2317             .any(|x| *x == "unstable-options");
2318         let really_allows_unstable_options =
2319             UnstableFeatures::from_environment().is_nightly_build();
2320
2321         for opt in flags.iter() {
2322             if opt.stability == OptionStability::Stable {
2323                 continue;
2324             }
2325             if !matches.opt_present(opt.name) {
2326                 continue;
2327             }
2328             if opt.name != "Z" && !has_z_unstable_option {
2329                 early_error(
2330                     ErrorOutputType::default(),
2331                     &format!(
2332                         "the `-Z unstable-options` flag must also be passed to enable \
2333                          the flag `{}`",
2334                         opt.name
2335                     ),
2336                 );
2337             }
2338             if really_allows_unstable_options {
2339                 continue;
2340             }
2341             match opt.stability {
2342                 OptionStability::Unstable => {
2343                     let msg = format!(
2344                         "the option `{}` is only accepted on the \
2345                          nightly compiler",
2346                         opt.name
2347                     );
2348                     early_error(ErrorOutputType::default(), &msg);
2349                 }
2350                 OptionStability::Stable => {}
2351             }
2352         }
2353     }
2354 }
2355
2356 impl fmt::Display for CrateType {
2357     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2358         match *self {
2359             CrateType::Executable => "bin".fmt(f),
2360             CrateType::Dylib => "dylib".fmt(f),
2361             CrateType::Rlib => "rlib".fmt(f),
2362             CrateType::Staticlib => "staticlib".fmt(f),
2363             CrateType::Cdylib => "cdylib".fmt(f),
2364             CrateType::ProcMacro => "proc-macro".fmt(f),
2365         }
2366     }
2367 }
2368
2369 /// Commandline arguments passed to the compiler have to be incorporated with
2370 /// the dependency tracking system for incremental compilation. This module
2371 /// provides some utilities to make this more convenient.
2372 ///
2373 /// The values of all commandline arguments that are relevant for dependency
2374 /// tracking are hashed into a single value that determines whether the
2375 /// incremental compilation cache can be re-used or not. This hashing is done
2376 /// via the DepTrackingHash trait defined below, since the standard Hash
2377 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2378 /// the hash of which is order dependent, but we might not want the order of
2379 /// arguments to make a difference for the hash).
2380 ///
2381 /// However, since the value provided by Hash::hash often *is* suitable,
2382 /// especially for primitive types, there is the
2383 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2384 /// Hash implementation for DepTrackingHash. It's important though that
2385 /// we have an opt-in scheme here, so one is hopefully forced to think about
2386 /// how the hash should be calculated when adding a new commandline argument.
2387 mod dep_tracking {
2388     use lint;
2389     use middle::cstore;
2390     use std::collections::BTreeMap;
2391     use std::hash::Hash;
2392     use std::path::PathBuf;
2393     use std::collections::hash_map::DefaultHasher;
2394     use super::{CrateType, DebugInfoLevel, ErrorOutputType, Lto, OptLevel, OutputTypes,
2395                 Passes, Sanitizer, CrossLangLto};
2396     use syntax::feature_gate::UnstableFeatures;
2397     use rustc_target::spec::{PanicStrategy, RelroLevel, TargetTriple};
2398     use syntax::edition::Edition;
2399
2400     pub trait DepTrackingHash {
2401         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2402     }
2403
2404     macro_rules! impl_dep_tracking_hash_via_hash {
2405         ($t:ty) => (
2406             impl DepTrackingHash for $t {
2407                 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2408                     Hash::hash(self, hasher);
2409                 }
2410             }
2411         )
2412     }
2413
2414     macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2415         ($t:ty) => (
2416             impl DepTrackingHash for Vec<$t> {
2417                 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2418                     let mut elems: Vec<&$t> = self.iter().collect();
2419                     elems.sort();
2420                     Hash::hash(&elems.len(), hasher);
2421                     for (index, elem) in elems.iter().enumerate() {
2422                         Hash::hash(&index, hasher);
2423                         DepTrackingHash::hash(*elem, hasher, error_format);
2424                     }
2425                 }
2426             }
2427         );
2428     }
2429
2430     impl_dep_tracking_hash_via_hash!(bool);
2431     impl_dep_tracking_hash_via_hash!(usize);
2432     impl_dep_tracking_hash_via_hash!(u64);
2433     impl_dep_tracking_hash_via_hash!(String);
2434     impl_dep_tracking_hash_via_hash!(PathBuf);
2435     impl_dep_tracking_hash_via_hash!(lint::Level);
2436     impl_dep_tracking_hash_via_hash!(Option<bool>);
2437     impl_dep_tracking_hash_via_hash!(Option<usize>);
2438     impl_dep_tracking_hash_via_hash!(Option<String>);
2439     impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2440     impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2441     impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2442     impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2443     impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2444     impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2445     impl_dep_tracking_hash_via_hash!(CrateType);
2446     impl_dep_tracking_hash_via_hash!(PanicStrategy);
2447     impl_dep_tracking_hash_via_hash!(RelroLevel);
2448     impl_dep_tracking_hash_via_hash!(Passes);
2449     impl_dep_tracking_hash_via_hash!(OptLevel);
2450     impl_dep_tracking_hash_via_hash!(Lto);
2451     impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
2452     impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2453     impl_dep_tracking_hash_via_hash!(OutputTypes);
2454     impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2455     impl_dep_tracking_hash_via_hash!(Sanitizer);
2456     impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2457     impl_dep_tracking_hash_via_hash!(TargetTriple);
2458     impl_dep_tracking_hash_via_hash!(Edition);
2459     impl_dep_tracking_hash_via_hash!(CrossLangLto);
2460
2461     impl_dep_tracking_hash_for_sortable_vec_of!(String);
2462     impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2463     impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2464     impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2465     impl_dep_tracking_hash_for_sortable_vec_of!((
2466         String,
2467         Option<String>,
2468         Option<cstore::NativeLibraryKind>
2469     ));
2470     impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2471
2472     impl<T1, T2> DepTrackingHash for (T1, T2)
2473     where
2474         T1: DepTrackingHash,
2475         T2: DepTrackingHash,
2476     {
2477         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2478             Hash::hash(&0, hasher);
2479             DepTrackingHash::hash(&self.0, hasher, error_format);
2480             Hash::hash(&1, hasher);
2481             DepTrackingHash::hash(&self.1, hasher, error_format);
2482         }
2483     }
2484
2485     impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2486     where
2487         T1: DepTrackingHash,
2488         T2: DepTrackingHash,
2489         T3: DepTrackingHash,
2490     {
2491         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2492             Hash::hash(&0, hasher);
2493             DepTrackingHash::hash(&self.0, hasher, error_format);
2494             Hash::hash(&1, hasher);
2495             DepTrackingHash::hash(&self.1, hasher, error_format);
2496             Hash::hash(&2, hasher);
2497             DepTrackingHash::hash(&self.2, hasher, error_format);
2498         }
2499     }
2500
2501     // This is a stable hash because BTreeMap is a sorted container
2502     pub fn stable_hash(
2503         sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2504         hasher: &mut DefaultHasher,
2505         error_format: ErrorOutputType,
2506     ) {
2507         for (key, sub_hash) in sub_hashes {
2508             // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2509             // the keys, as they are just plain strings
2510             Hash::hash(&key.len(), hasher);
2511             Hash::hash(key, hasher);
2512             sub_hash.hash(hasher, error_format);
2513         }
2514     }
2515 }
2516
2517 #[cfg(test)]
2518 mod tests {
2519     use errors;
2520     use getopts;
2521     use lint;
2522     use middle::cstore;
2523     use session::config::{build_configuration, build_session_options_and_crate_config};
2524     use session::config::{Lto, CrossLangLto};
2525     use session::build_session;
2526     use std::collections::{BTreeMap, BTreeSet};
2527     use std::iter::FromIterator;
2528     use std::path::PathBuf;
2529     use super::{Externs, OutputType, OutputTypes};
2530     use rustc_target::spec::{PanicStrategy, RelroLevel};
2531     use syntax::symbol::Symbol;
2532     use syntax::edition::{Edition, DEFAULT_EDITION};
2533     use syntax;
2534
2535     fn optgroups() -> getopts::Options {
2536         let mut opts = getopts::Options::new();
2537         for group in super::rustc_optgroups() {
2538             (group.apply)(&mut opts);
2539         }
2540         return opts;
2541     }
2542
2543     fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2544         BTreeMap::from_iter(entries.into_iter())
2545     }
2546
2547     fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2548         BTreeSet::from_iter(entries.into_iter())
2549     }
2550
2551     // When the user supplies --test we should implicitly supply --cfg test
2552     #[test]
2553     fn test_switch_implies_cfg_test() {
2554         syntax::with_globals(|| {
2555             let matches = &match optgroups().parse(&["--test".to_string()]) {
2556                 Ok(m) => m,
2557                 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2558             };
2559             let registry = errors::registry::Registry::new(&[]);
2560             let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2561             let sess = build_session(sessopts, None, registry);
2562             let cfg = build_configuration(&sess, cfg);
2563             assert!(cfg.contains(&(Symbol::intern("test"), None)));
2564         });
2565     }
2566
2567     // When the user supplies --test and --cfg test, don't implicitly add
2568     // another --cfg test
2569     #[test]
2570     fn test_switch_implies_cfg_test_unless_cfg_test() {
2571         syntax::with_globals(|| {
2572             let matches = &match optgroups().parse(&["--test".to_string(),
2573                                                      "--cfg=test".to_string()]) {
2574                 Ok(m) => m,
2575                 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2576             };
2577             let registry = errors::registry::Registry::new(&[]);
2578             let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2579             let sess = build_session(sessopts, None, registry);
2580             let cfg = build_configuration(&sess, cfg);
2581             let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2582             assert!(test_items.next().is_some());
2583             assert!(test_items.next().is_none());
2584         });
2585     }
2586
2587     #[test]
2588     fn test_can_print_warnings() {
2589         syntax::with_globals(|| {
2590             let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2591             let registry = errors::registry::Registry::new(&[]);
2592             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2593             let sess = build_session(sessopts, None, registry);
2594             assert!(!sess.diagnostic().flags.can_emit_warnings);
2595         });
2596
2597         syntax::with_globals(|| {
2598             let matches = optgroups()
2599                 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2600                 .unwrap();
2601             let registry = errors::registry::Registry::new(&[]);
2602             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2603             let sess = build_session(sessopts, None, registry);
2604             assert!(sess.diagnostic().flags.can_emit_warnings);
2605         });
2606
2607         syntax::with_globals(|| {
2608             let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2609             let registry = errors::registry::Registry::new(&[]);
2610             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2611             let sess = build_session(sessopts, None, registry);
2612             assert!(sess.diagnostic().flags.can_emit_warnings);
2613         });
2614     }
2615
2616     #[test]
2617     fn test_output_types_tracking_hash_different_paths() {
2618         let mut v1 = super::basic_options();
2619         let mut v2 = super::basic_options();
2620         let mut v3 = super::basic_options();
2621
2622         v1.output_types =
2623             OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2624         v2.output_types =
2625             OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2626         v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2627
2628         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2629         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2630         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2631
2632         // Check clone
2633         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2634         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2635         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2636     }
2637
2638     #[test]
2639     fn test_output_types_tracking_hash_different_construction_order() {
2640         let mut v1 = super::basic_options();
2641         let mut v2 = super::basic_options();
2642
2643         v1.output_types = OutputTypes::new(&[
2644             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2645             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2646         ]);
2647
2648         v2.output_types = OutputTypes::new(&[
2649             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2650             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2651         ]);
2652
2653         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2654
2655         // Check clone
2656         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2657     }
2658
2659     #[test]
2660     fn test_externs_tracking_hash_different_construction_order() {
2661         let mut v1 = super::basic_options();
2662         let mut v2 = super::basic_options();
2663         let mut v3 = super::basic_options();
2664
2665         v1.externs = Externs::new(mk_map(vec![
2666             (
2667                 String::from("a"),
2668                 mk_set(vec![String::from("b"), String::from("c")]),
2669             ),
2670             (
2671                 String::from("d"),
2672                 mk_set(vec![String::from("e"), String::from("f")]),
2673             ),
2674         ]));
2675
2676         v2.externs = Externs::new(mk_map(vec![
2677             (
2678                 String::from("d"),
2679                 mk_set(vec![String::from("e"), String::from("f")]),
2680             ),
2681             (
2682                 String::from("a"),
2683                 mk_set(vec![String::from("b"), String::from("c")]),
2684             ),
2685         ]));
2686
2687         v3.externs = Externs::new(mk_map(vec![
2688             (
2689                 String::from("a"),
2690                 mk_set(vec![String::from("b"), String::from("c")]),
2691             ),
2692             (
2693                 String::from("d"),
2694                 mk_set(vec![String::from("f"), String::from("e")]),
2695             ),
2696         ]));
2697
2698         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2699         assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2700         assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2701
2702         // Check clone
2703         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2704         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2705         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2706     }
2707
2708     #[test]
2709     fn test_lints_tracking_hash_different_values() {
2710         let mut v1 = super::basic_options();
2711         let mut v2 = super::basic_options();
2712         let mut v3 = super::basic_options();
2713
2714         v1.lint_opts = vec![
2715             (String::from("a"), lint::Allow),
2716             (String::from("b"), lint::Warn),
2717             (String::from("c"), lint::Deny),
2718             (String::from("d"), lint::Forbid),
2719         ];
2720
2721         v2.lint_opts = vec![
2722             (String::from("a"), lint::Allow),
2723             (String::from("b"), lint::Warn),
2724             (String::from("X"), lint::Deny),
2725             (String::from("d"), lint::Forbid),
2726         ];
2727
2728         v3.lint_opts = vec![
2729             (String::from("a"), lint::Allow),
2730             (String::from("b"), lint::Warn),
2731             (String::from("c"), lint::Forbid),
2732             (String::from("d"), lint::Deny),
2733         ];
2734
2735         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2736         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2737         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2738
2739         // Check clone
2740         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2741         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2742         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2743     }
2744
2745     #[test]
2746     fn test_lints_tracking_hash_different_construction_order() {
2747         let mut v1 = super::basic_options();
2748         let mut v2 = super::basic_options();
2749
2750         v1.lint_opts = vec![
2751             (String::from("a"), lint::Allow),
2752             (String::from("b"), lint::Warn),
2753             (String::from("c"), lint::Deny),
2754             (String::from("d"), lint::Forbid),
2755         ];
2756
2757         v2.lint_opts = vec![
2758             (String::from("a"), lint::Allow),
2759             (String::from("c"), lint::Deny),
2760             (String::from("b"), lint::Warn),
2761             (String::from("d"), lint::Forbid),
2762         ];
2763
2764         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2765
2766         // Check clone
2767         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2768         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2769     }
2770
2771     #[test]
2772     fn test_search_paths_tracking_hash_different_order() {
2773         let mut v1 = super::basic_options();
2774         let mut v2 = super::basic_options();
2775         let mut v3 = super::basic_options();
2776         let mut v4 = super::basic_options();
2777
2778         // Reference
2779         v1.search_paths
2780             .add_path("native=abc", super::ErrorOutputType::Json(false));
2781         v1.search_paths
2782             .add_path("crate=def", super::ErrorOutputType::Json(false));
2783         v1.search_paths
2784             .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2785         v1.search_paths
2786             .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2787         v1.search_paths
2788             .add_path("all=mno", super::ErrorOutputType::Json(false));
2789
2790         v2.search_paths
2791             .add_path("native=abc", super::ErrorOutputType::Json(false));
2792         v2.search_paths
2793             .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2794         v2.search_paths
2795             .add_path("crate=def", super::ErrorOutputType::Json(false));
2796         v2.search_paths
2797             .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2798         v2.search_paths
2799             .add_path("all=mno", super::ErrorOutputType::Json(false));
2800
2801         v3.search_paths
2802             .add_path("crate=def", super::ErrorOutputType::Json(false));
2803         v3.search_paths
2804             .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2805         v3.search_paths
2806             .add_path("native=abc", super::ErrorOutputType::Json(false));
2807         v3.search_paths
2808             .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2809         v3.search_paths
2810             .add_path("all=mno", super::ErrorOutputType::Json(false));
2811
2812         v4.search_paths
2813             .add_path("all=mno", super::ErrorOutputType::Json(false));
2814         v4.search_paths
2815             .add_path("native=abc", super::ErrorOutputType::Json(false));
2816         v4.search_paths
2817             .add_path("crate=def", super::ErrorOutputType::Json(false));
2818         v4.search_paths
2819             .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2820         v4.search_paths
2821             .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2822
2823         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2824         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2825         assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2826
2827         // Check clone
2828         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2829         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2830         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2831         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2832     }
2833
2834     #[test]
2835     fn test_native_libs_tracking_hash_different_values() {
2836         let mut v1 = super::basic_options();
2837         let mut v2 = super::basic_options();
2838         let mut v3 = super::basic_options();
2839         let mut v4 = super::basic_options();
2840
2841         // Reference
2842         v1.libs = vec![
2843             (String::from("a"), None, Some(cstore::NativeStatic)),
2844             (String::from("b"), None, Some(cstore::NativeFramework)),
2845             (String::from("c"), None, Some(cstore::NativeUnknown)),
2846         ];
2847
2848         // Change label
2849         v2.libs = vec![
2850             (String::from("a"), None, Some(cstore::NativeStatic)),
2851             (String::from("X"), None, Some(cstore::NativeFramework)),
2852             (String::from("c"), None, Some(cstore::NativeUnknown)),
2853         ];
2854
2855         // Change kind
2856         v3.libs = vec![
2857             (String::from("a"), None, Some(cstore::NativeStatic)),
2858             (String::from("b"), None, Some(cstore::NativeStatic)),
2859             (String::from("c"), None, Some(cstore::NativeUnknown)),
2860         ];
2861
2862         // Change new-name
2863         v4.libs = vec![
2864             (String::from("a"), None, Some(cstore::NativeStatic)),
2865             (
2866                 String::from("b"),
2867                 Some(String::from("X")),
2868                 Some(cstore::NativeFramework),
2869             ),
2870             (String::from("c"), None, Some(cstore::NativeUnknown)),
2871         ];
2872
2873         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2874         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2875         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2876
2877         // Check clone
2878         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2879         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2880         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2881         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2882     }
2883
2884     #[test]
2885     fn test_native_libs_tracking_hash_different_order() {
2886         let mut v1 = super::basic_options();
2887         let mut v2 = super::basic_options();
2888         let mut v3 = super::basic_options();
2889
2890         // Reference
2891         v1.libs = vec![
2892             (String::from("a"), None, Some(cstore::NativeStatic)),
2893             (String::from("b"), None, Some(cstore::NativeFramework)),
2894             (String::from("c"), None, Some(cstore::NativeUnknown)),
2895         ];
2896
2897         v2.libs = vec![
2898             (String::from("b"), None, Some(cstore::NativeFramework)),
2899             (String::from("a"), None, Some(cstore::NativeStatic)),
2900             (String::from("c"), None, Some(cstore::NativeUnknown)),
2901         ];
2902
2903         v3.libs = vec![
2904             (String::from("c"), None, Some(cstore::NativeUnknown)),
2905             (String::from("a"), None, Some(cstore::NativeStatic)),
2906             (String::from("b"), None, Some(cstore::NativeFramework)),
2907         ];
2908
2909         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2910         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2911         assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2912
2913         // Check clone
2914         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2915         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2916         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2917     }
2918
2919     #[test]
2920     fn test_codegen_options_tracking_hash() {
2921         let reference = super::basic_options();
2922         let mut opts = super::basic_options();
2923
2924         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2925         opts.cg.ar = Some(String::from("abc"));
2926         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2927
2928         opts.cg.linker = Some(PathBuf::from("linker"));
2929         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2930
2931         opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2932         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2933
2934         opts.cg.link_dead_code = true;
2935         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2936
2937         opts.cg.rpath = true;
2938         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2939
2940         opts.cg.extra_filename = String::from("extra-filename");
2941         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2942
2943         opts.cg.codegen_units = Some(42);
2944         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2945
2946         opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
2947         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2948
2949         opts.cg.save_temps = true;
2950         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2951
2952         opts.cg.incremental = Some(String::from("abc"));
2953         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2954
2955         // Make sure changing a [TRACKED] option changes the hash
2956         opts = reference.clone();
2957         opts.cg.lto = Lto::Fat;
2958         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2959
2960         opts = reference.clone();
2961         opts.cg.target_cpu = Some(String::from("abc"));
2962         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2963
2964         opts = reference.clone();
2965         opts.cg.target_feature = String::from("all the features, all of them");
2966         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2967
2968         opts = reference.clone();
2969         opts.cg.passes = vec![String::from("1"), String::from("2")];
2970         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2971
2972         opts = reference.clone();
2973         opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2974         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2975
2976         opts = reference.clone();
2977         opts.cg.overflow_checks = Some(true);
2978         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2979
2980         opts = reference.clone();
2981         opts.cg.no_prepopulate_passes = true;
2982         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2983
2984         opts = reference.clone();
2985         opts.cg.no_vectorize_loops = true;
2986         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2987
2988         opts = reference.clone();
2989         opts.cg.no_vectorize_slp = true;
2990         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2991
2992         opts = reference.clone();
2993         opts.cg.soft_float = true;
2994         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2995
2996         opts = reference.clone();
2997         opts.cg.prefer_dynamic = true;
2998         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2999
3000         opts = reference.clone();
3001         opts.cg.no_integrated_as = true;
3002         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3003
3004         opts = reference.clone();
3005         opts.cg.no_redzone = Some(true);
3006         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3007
3008         opts = reference.clone();
3009         opts.cg.relocation_model = Some(String::from("relocation model"));
3010         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3011
3012         opts = reference.clone();
3013         opts.cg.code_model = Some(String::from("code model"));
3014         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3015
3016         opts = reference.clone();
3017         opts.debugging_opts.tls_model = Some(String::from("tls model"));
3018         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3019
3020         opts = reference.clone();
3021         opts.debugging_opts.pgo_gen = Some(String::from("abc"));
3022         assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3023
3024         opts = reference.clone();
3025         opts.debugging_opts.pgo_use = String::from("abc");
3026         assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3027
3028         opts = reference.clone();
3029         opts.cg.metadata = vec![String::from("A"), String::from("B")];
3030         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3031
3032         opts = reference.clone();
3033         opts.cg.debuginfo = Some(0xdeadbeef);
3034         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3035
3036         opts = reference.clone();
3037         opts.cg.debuginfo = Some(0xba5eba11);
3038         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3039
3040         opts = reference.clone();
3041         opts.cg.force_frame_pointers = Some(false);
3042         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3043
3044         opts = reference.clone();
3045         opts.cg.debug_assertions = Some(true);
3046         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3047
3048         opts = reference.clone();
3049         opts.cg.inline_threshold = Some(0xf007ba11);
3050         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3051
3052         opts = reference.clone();
3053         opts.cg.panic = Some(PanicStrategy::Abort);
3054         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3055     }
3056
3057     #[test]
3058     fn test_debugging_options_tracking_hash() {
3059         let reference = super::basic_options();
3060         let mut opts = super::basic_options();
3061
3062         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3063         opts.debugging_opts.verbose = true;
3064         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3065         opts.debugging_opts.time_passes = true;
3066         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3067         opts.debugging_opts.count_llvm_insns = true;
3068         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3069         opts.debugging_opts.time_llvm_passes = true;
3070         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3071         opts.debugging_opts.input_stats = true;
3072         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3073         opts.debugging_opts.codegen_stats = true;
3074         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3075         opts.debugging_opts.borrowck_stats = true;
3076         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3077         opts.debugging_opts.meta_stats = true;
3078         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3079         opts.debugging_opts.print_link_args = true;
3080         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3081         opts.debugging_opts.print_llvm_passes = true;
3082         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3083         opts.debugging_opts.ast_json = true;
3084         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3085         opts.debugging_opts.ast_json_noexpand = true;
3086         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3087         opts.debugging_opts.ls = true;
3088         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3089         opts.debugging_opts.save_analysis = true;
3090         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3091         opts.debugging_opts.flowgraph_print_loans = true;
3092         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3093         opts.debugging_opts.flowgraph_print_moves = true;
3094         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3095         opts.debugging_opts.flowgraph_print_assigns = true;
3096         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3097         opts.debugging_opts.flowgraph_print_all = true;
3098         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3099         opts.debugging_opts.print_region_graph = true;
3100         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3101         opts.debugging_opts.parse_only = true;
3102         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3103         opts.debugging_opts.incremental = Some(String::from("abc"));
3104         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3105         opts.debugging_opts.dump_dep_graph = true;
3106         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3107         opts.debugging_opts.query_dep_graph = true;
3108         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3109         opts.debugging_opts.no_analysis = true;
3110         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3111         opts.debugging_opts.unstable_options = true;
3112         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3113         opts.debugging_opts.trace_macros = true;
3114         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3115         opts.debugging_opts.keep_hygiene_data = true;
3116         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3117         opts.debugging_opts.keep_ast = true;
3118         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3119         opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3120         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3121         opts.debugging_opts.dump_mir = Some(String::from("abc"));
3122         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3123         opts.debugging_opts.dump_mir_dir = String::from("abc");
3124         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3125         opts.debugging_opts.dump_mir_graphviz = true;
3126         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3127
3128         // Make sure changing a [TRACKED] option changes the hash
3129         opts = reference.clone();
3130         opts.debugging_opts.asm_comments = true;
3131         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3132
3133         opts = reference.clone();
3134         opts.debugging_opts.verify_llvm_ir = true;
3135         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3136
3137         opts = reference.clone();
3138         opts.debugging_opts.no_landing_pads = true;
3139         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3140
3141         opts = reference.clone();
3142         opts.debugging_opts.fewer_names = true;
3143         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3144
3145         opts = reference.clone();
3146         opts.debugging_opts.no_codegen = true;
3147         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3148
3149         opts = reference.clone();
3150         opts.debugging_opts.treat_err_as_bug = true;
3151         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3152
3153         opts = reference.clone();
3154         opts.debugging_opts.report_delayed_bugs = true;
3155         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3156
3157         opts = reference.clone();
3158         opts.debugging_opts.continue_parse_after_error = true;
3159         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3160
3161         opts = reference.clone();
3162         opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3163         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3164
3165         opts = reference.clone();
3166         opts.debugging_opts.force_overflow_checks = Some(true);
3167         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3168
3169         opts = reference.clone();
3170         opts.debugging_opts.show_span = Some(String::from("abc"));
3171         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3172
3173         opts = reference.clone();
3174         opts.debugging_opts.mir_opt_level = 3;
3175         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3176
3177         opts = reference.clone();
3178         opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3179         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3180
3181         opts = reference.clone();
3182         opts.debugging_opts.cross_lang_lto = CrossLangLto::LinkerPluginAuto;
3183         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3184     }
3185
3186     #[test]
3187     fn test_edition_parsing() {
3188         // test default edition
3189         let options = super::basic_options();
3190         assert!(options.edition == DEFAULT_EDITION);
3191
3192         let matches = optgroups()
3193             .parse(&["--edition=2018".to_string()])
3194             .unwrap();
3195         let (sessopts, _) = build_session_options_and_crate_config(&matches);
3196         assert!(sessopts.edition == Edition::Edition2018)
3197     }
3198 }