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