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