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