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