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