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