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