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