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