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