]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
d8efa17defe3d06e6bed593c225a2f65a89548ff
[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("json") => ErrorOutputType::Json { pretty: false, json_rendered },
2006             Some("pretty-json") => ErrorOutputType::Json { pretty: true, json_rendered },
2007             Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
2008
2009             Some(arg) => early_error(
2010                 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
2011                 &format!(
2012                     "argument for --error-format must be `human`, `json` or \
2013                      `short` (instead was `{}`)",
2014                     arg
2015                 ),
2016             ),
2017         }
2018     } else {
2019         ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
2020     };
2021
2022     let unparsed_crate_types = matches.opt_strs("crate-type");
2023     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
2024         .unwrap_or_else(|e| early_error(error_format, &e[..]));
2025
2026
2027     let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
2028
2029     let mut debugging_opts = build_debugging_options(matches, error_format);
2030
2031     if !debugging_opts.unstable_options {
2032         if matches.opt_str("json-rendered").is_some() {
2033             early_error(error_format, "`--json-rendered=x` is unstable");
2034         }
2035         if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format {
2036             early_error(
2037                 ErrorOutputType::Json { pretty: false, json_rendered },
2038                 "--error-format=pretty-json is unstable",
2039             );
2040         }
2041     }
2042
2043     if debugging_opts.pgo_gen.enabled() && debugging_opts.pgo_use.is_some() {
2044         early_error(
2045             error_format,
2046             "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
2047         );
2048     }
2049
2050     let mut output_types = BTreeMap::new();
2051     if !debugging_opts.parse_only {
2052         for list in matches.opt_strs("emit") {
2053             for output_type in list.split(',') {
2054                 let mut parts = output_type.splitn(2, '=');
2055                 let shorthand = parts.next().unwrap();
2056                 let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
2057                     early_error(
2058                         error_format,
2059                         &format!(
2060                             "unknown emission type: `{}` - expected one of: {}",
2061                             shorthand,
2062                             OutputType::shorthands_display(),
2063                         ),
2064                     ),
2065                 );
2066                 let path = parts.next().map(PathBuf::from);
2067                 output_types.insert(output_type, path);
2068             }
2069         }
2070     };
2071     if output_types.is_empty() {
2072         output_types.insert(OutputType::Exe, None);
2073     }
2074
2075     let mut cg = build_codegen_options(matches, error_format);
2076     let mut codegen_units = cg.codegen_units;
2077     let mut disable_thinlto = false;
2078
2079     // Issue #30063: if user requests llvm-related output to one
2080     // particular path, disable codegen-units.
2081     let incompatible: Vec<_> = output_types
2082         .iter()
2083         .map(|ot_path| ot_path.0)
2084         .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
2085         .map(|ot| ot.shorthand())
2086         .collect();
2087     if !incompatible.is_empty() {
2088         match codegen_units {
2089             Some(n) if n > 1 => {
2090                 if matches.opt_present("o") {
2091                     for ot in &incompatible {
2092                         early_warn(
2093                             error_format,
2094                             &format!(
2095                                 "--emit={} with -o incompatible with \
2096                                  -C codegen-units=N for N > 1",
2097                                 ot
2098                             ),
2099                         );
2100                     }
2101                     early_warn(error_format, "resetting to default -C codegen-units=1");
2102                     codegen_units = Some(1);
2103                     disable_thinlto = true;
2104                 }
2105             }
2106             _ => {
2107                 codegen_units = Some(1);
2108                 disable_thinlto = true;
2109             }
2110         }
2111     }
2112
2113     if debugging_opts.threads == Some(0) {
2114         early_error(
2115             error_format,
2116             "Value for threads must be a positive nonzero integer",
2117         );
2118     }
2119
2120     if debugging_opts.threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
2121         early_error(
2122             error_format,
2123             "Optimization fuel is incompatible with multiple threads",
2124         );
2125     }
2126
2127     if codegen_units == Some(0) {
2128         early_error(
2129             error_format,
2130             "Value for codegen units must be a positive nonzero integer",
2131         );
2132     }
2133
2134     let incremental = match (&debugging_opts.incremental, &cg.incremental) {
2135         (&Some(ref path1), &Some(ref path2)) => {
2136             if path1 != path2 {
2137                 early_error(
2138                     error_format,
2139                     &format!(
2140                         "conflicting paths for `-Z incremental` and \
2141                          `-C incremental` specified: {} versus {}",
2142                         path1, path2
2143                     ),
2144                 );
2145             } else {
2146                 Some(path1)
2147             }
2148         }
2149         (&Some(ref path), &None) => Some(path),
2150         (&None, &Some(ref path)) => Some(path),
2151         (&None, &None) => None,
2152     }.map(|m| PathBuf::from(m));
2153
2154     if debugging_opts.profile && incremental.is_some() {
2155         early_error(
2156             error_format,
2157             "can't instrument with gcov profiling when compiling incrementally",
2158         );
2159     }
2160
2161     let mut prints = Vec::<PrintRequest>::new();
2162     if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2163         prints.push(PrintRequest::TargetCPUs);
2164         cg.target_cpu = None;
2165     };
2166     if cg.target_feature == "help" {
2167         prints.push(PrintRequest::TargetFeatures);
2168         cg.target_feature = String::new();
2169     }
2170     if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2171         prints.push(PrintRequest::RelocationModels);
2172         cg.relocation_model = None;
2173     }
2174     if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2175         prints.push(PrintRequest::CodeModels);
2176         cg.code_model = None;
2177     }
2178     if debugging_opts
2179         .tls_model
2180         .as_ref()
2181         .map_or(false, |s| s == "help")
2182     {
2183         prints.push(PrintRequest::TlsModels);
2184         debugging_opts.tls_model = None;
2185     }
2186
2187     let cg = cg;
2188
2189     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2190     let target_triple = if let Some(target) = matches.opt_str("target") {
2191         if target.ends_with(".json") {
2192             let path = Path::new(&target);
2193             TargetTriple::from_path(&path).unwrap_or_else(|_|
2194                 early_error(error_format, &format!("target file {:?} does not exist", path)))
2195         } else {
2196             TargetTriple::TargetTriple(target)
2197         }
2198     } else {
2199         TargetTriple::from_triple(host_triple())
2200     };
2201     let opt_level = {
2202         // The `-O` and `-C opt-level` flags specify the same setting, so we want to be able
2203         // to use them interchangeably. However, because they're technically different flags,
2204         // we need to work out manually which should take precedence if both are supplied (i.e.
2205         // the rightmost flag). We do this by finding the (rightmost) position of both flags and
2206         // comparing them. Note that if a flag is not found, its position will be `None`, which
2207         // always compared less than `Some(_)`.
2208         let max_o = matches.opt_positions("O").into_iter().max();
2209         let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2210             if let Some("opt-level") = s.splitn(2, '=').next() {
2211                 Some(i)
2212             } else {
2213                 None
2214             }
2215         }).max();
2216         if max_o > max_c {
2217             OptLevel::Default
2218         } else {
2219             match cg.opt_level.as_ref().map(String::as_ref) {
2220                 None => OptLevel::No,
2221                 Some("0") => OptLevel::No,
2222                 Some("1") => OptLevel::Less,
2223                 Some("2") => OptLevel::Default,
2224                 Some("3") => OptLevel::Aggressive,
2225                 Some("s") => OptLevel::Size,
2226                 Some("z") => OptLevel::SizeMin,
2227                 Some(arg) => {
2228                     early_error(
2229                         error_format,
2230                         &format!(
2231                             "optimization level needs to be \
2232                              between 0-3, s or z (instead was `{}`)",
2233                             arg
2234                         ),
2235                     );
2236                 }
2237             }
2238         }
2239     };
2240     // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able
2241     // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`)
2242     // for more details.
2243     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2244     let max_g = matches.opt_positions("g").into_iter().max();
2245     let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2246         if let Some("debuginfo") = s.splitn(2, '=').next() {
2247             Some(i)
2248         } else {
2249             None
2250         }
2251     }).max();
2252     let debuginfo = if max_g > max_c {
2253         DebugInfo::Full
2254     } else {
2255         match cg.debuginfo {
2256             None | Some(0) => DebugInfo::None,
2257             Some(1) => DebugInfo::Limited,
2258             Some(2) => DebugInfo::Full,
2259             Some(arg) => {
2260                 early_error(
2261                     error_format,
2262                     &format!(
2263                         "debug info level needs to be between \
2264                          0-2 (instead was `{}`)",
2265                         arg
2266                     ),
2267                 );
2268             }
2269         }
2270     };
2271
2272     let mut search_paths = vec![];
2273     for s in &matches.opt_strs("L") {
2274         search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
2275     }
2276
2277     let libs = matches
2278         .opt_strs("l")
2279         .into_iter()
2280         .map(|s| {
2281             // Parse string of the form "[KIND=]lib[:new_name]",
2282             // where KIND is one of "dylib", "framework", "static".
2283             let mut parts = s.splitn(2, '=');
2284             let kind = parts.next().unwrap();
2285             let (name, kind) = match (parts.next(), kind) {
2286                 (None, name) => (name, None),
2287                 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2288                 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2289                 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2290                 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2291                 (_, s) => {
2292                     early_error(
2293                         error_format,
2294                         &format!(
2295                             "unknown library kind `{}`, expected \
2296                              one of dylib, framework, or static",
2297                             s
2298                         ),
2299                     );
2300                 }
2301             };
2302             if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2303                 early_error(
2304                     error_format,
2305                     &format!(
2306                         "the library kind 'static-nobundle' is only \
2307                          accepted on the nightly compiler"
2308                     ),
2309                 );
2310             }
2311             let mut name_parts = name.splitn(2, ':');
2312             let name = name_parts.next().unwrap();
2313             let new_name = name_parts.next();
2314             (name.to_owned(), new_name.map(|n| n.to_owned()), kind)
2315         })
2316         .collect();
2317
2318     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2319     let test = matches.opt_present("test");
2320
2321     let is_unstable_enabled = nightly_options::is_unstable_enabled(matches);
2322
2323     prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2324         "crate-name" => PrintRequest::CrateName,
2325         "file-names" => PrintRequest::FileNames,
2326         "sysroot" => PrintRequest::Sysroot,
2327         "cfg" => PrintRequest::Cfg,
2328         "target-list" => PrintRequest::TargetList,
2329         "target-cpus" => PrintRequest::TargetCPUs,
2330         "target-features" => PrintRequest::TargetFeatures,
2331         "relocation-models" => PrintRequest::RelocationModels,
2332         "code-models" => PrintRequest::CodeModels,
2333         "tls-models" => PrintRequest::TlsModels,
2334         "native-static-libs" => PrintRequest::NativeStaticLibs,
2335         "target-spec-json" => {
2336             if is_unstable_enabled {
2337                 PrintRequest::TargetSpec
2338             } else {
2339                 early_error(
2340                     error_format,
2341                     "the `-Z unstable-options` flag must also be passed to \
2342                      enable the target-spec-json print option",
2343                 );
2344             }
2345         }
2346         req => early_error(error_format, &format!("unknown print request `{}`", req)),
2347     }));
2348
2349     let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2350         None | Some("migrate") => BorrowckMode::Migrate,
2351         Some("mir") => BorrowckMode::Mir,
2352         Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2353     };
2354
2355     if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2356         early_warn(
2357             error_format,
2358             "-C remark requires \"-C debuginfo=n\" to show source locations",
2359         );
2360     }
2361
2362     if matches.opt_present("extern-private") && !debugging_opts.unstable_options {
2363         early_error(
2364             ErrorOutputType::default(),
2365             "'--extern-private' is unstable and only \
2366             available for nightly builds of rustc."
2367         )
2368     }
2369
2370     // We start out with a Vec<(Option<String>, bool)>>,
2371     // and later convert it into a BTreeSet<(Option<String>, bool)>
2372     // This allows to modify entries in-place to set their correct
2373     // 'public' value
2374     let mut externs: BTreeMap<String, ExternEntry> = BTreeMap::new();
2375     for (arg, private) in matches.opt_strs("extern").into_iter().map(|v| (v, false))
2376         .chain(matches.opt_strs("extern-private").into_iter().map(|v| (v, true))) {
2377
2378         let mut parts = arg.splitn(2, '=');
2379         let name = parts.next().unwrap_or_else(||
2380             early_error(error_format, "--extern value must not be empty"));
2381         let location = parts.next().map(|s| s.to_string());
2382         if location.is_none() && !is_unstable_enabled {
2383             early_error(
2384                 error_format,
2385                 "the `-Z unstable-options` flag must also be passed to \
2386                  enable `--extern crate_name` without `=path`",
2387             );
2388         };
2389
2390         let entry = externs
2391             .entry(name.to_owned())
2392             .or_default();
2393
2394
2395         entry.locations.insert(location.clone());
2396
2397         // Crates start out being not private,
2398         // and go to being private if we see an '--extern-private'
2399         // flag
2400         entry.is_private_dep |= private;
2401     }
2402
2403     let crate_name = matches.opt_str("crate-name");
2404
2405     let remap_path_prefix = matches
2406         .opt_strs("remap-path-prefix")
2407         .into_iter()
2408         .map(|remap| {
2409             let mut parts = remap.rsplitn(2, '='); // reverse iterator
2410             let to = parts.next();
2411             let from = parts.next();
2412             match (from, to) {
2413                 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2414                 _ => early_error(
2415                     error_format,
2416                     "--remap-path-prefix must contain '=' between FROM and TO",
2417                 ),
2418             }
2419         })
2420         .collect();
2421
2422     (
2423         Options {
2424             crate_types,
2425             optimize: opt_level,
2426             debuginfo,
2427             lint_opts,
2428             lint_cap,
2429             describe_lints,
2430             output_types: OutputTypes(output_types),
2431             search_paths,
2432             maybe_sysroot: sysroot_opt,
2433             target_triple,
2434             test,
2435             incremental,
2436             debugging_opts,
2437             prints,
2438             borrowck_mode,
2439             cg,
2440             error_format,
2441             externs: Externs(externs),
2442             crate_name,
2443             alt_std_name: None,
2444             libs,
2445             unstable_features: UnstableFeatures::from_environment(),
2446             debug_assertions,
2447             actually_rustdoc: false,
2448             cli_forced_codegen_units: codegen_units,
2449             cli_forced_thinlto_off: disable_thinlto,
2450             remap_path_prefix,
2451             edition,
2452         },
2453         cfg,
2454     )
2455 }
2456
2457 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2458     let mut crate_types: Vec<CrateType> = Vec::new();
2459     for unparsed_crate_type in &list_list {
2460         for part in unparsed_crate_type.split(',') {
2461             let new_part = match part {
2462                 "lib" => default_lib_output(),
2463                 "rlib" => CrateType::Rlib,
2464                 "staticlib" => CrateType::Staticlib,
2465                 "dylib" => CrateType::Dylib,
2466                 "cdylib" => CrateType::Cdylib,
2467                 "bin" => CrateType::Executable,
2468                 "proc-macro" => CrateType::ProcMacro,
2469                 _ => return Err(format!("unknown crate type: `{}`", part))
2470             };
2471             if !crate_types.contains(&new_part) {
2472                 crate_types.push(new_part)
2473             }
2474         }
2475     }
2476
2477     Ok(crate_types)
2478 }
2479
2480 pub mod nightly_options {
2481     use getopts;
2482     use syntax::feature_gate::UnstableFeatures;
2483     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2484     use crate::session::early_error;
2485
2486     pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2487         is_nightly_build()
2488             && matches
2489                 .opt_strs("Z")
2490                 .iter()
2491                 .any(|x| *x == "unstable-options")
2492     }
2493
2494     pub fn is_nightly_build() -> bool {
2495         UnstableFeatures::from_environment().is_nightly_build()
2496     }
2497
2498     pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2499         let has_z_unstable_option = matches
2500             .opt_strs("Z")
2501             .iter()
2502             .any(|x| *x == "unstable-options");
2503         let really_allows_unstable_options =
2504             UnstableFeatures::from_environment().is_nightly_build();
2505
2506         for opt in flags.iter() {
2507             if opt.stability == OptionStability::Stable {
2508                 continue;
2509             }
2510             if !matches.opt_present(opt.name) {
2511                 continue;
2512             }
2513             if opt.name != "Z" && !has_z_unstable_option {
2514                 early_error(
2515                     ErrorOutputType::default(),
2516                     &format!(
2517                         "the `-Z unstable-options` flag must also be passed to enable \
2518                          the flag `{}`",
2519                         opt.name
2520                     ),
2521                 );
2522             }
2523             if really_allows_unstable_options {
2524                 continue;
2525             }
2526             match opt.stability {
2527                 OptionStability::Unstable => {
2528                     let msg = format!(
2529                         "the option `{}` is only accepted on the \
2530                          nightly compiler",
2531                         opt.name
2532                     );
2533                     early_error(ErrorOutputType::default(), &msg);
2534                 }
2535                 OptionStability::Stable => {}
2536             }
2537         }
2538     }
2539 }
2540
2541 impl fmt::Display for CrateType {
2542     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2543         match *self {
2544             CrateType::Executable => "bin".fmt(f),
2545             CrateType::Dylib => "dylib".fmt(f),
2546             CrateType::Rlib => "rlib".fmt(f),
2547             CrateType::Staticlib => "staticlib".fmt(f),
2548             CrateType::Cdylib => "cdylib".fmt(f),
2549             CrateType::ProcMacro => "proc-macro".fmt(f),
2550         }
2551     }
2552 }
2553
2554 /// Command-line arguments passed to the compiler have to be incorporated with
2555 /// the dependency tracking system for incremental compilation. This module
2556 /// provides some utilities to make this more convenient.
2557 ///
2558 /// The values of all command-line arguments that are relevant for dependency
2559 /// tracking are hashed into a single value that determines whether the
2560 /// incremental compilation cache can be re-used or not. This hashing is done
2561 /// via the DepTrackingHash trait defined below, since the standard Hash
2562 /// implementation might not be suitable (e.g., arguments are stored in a Vec,
2563 /// the hash of which is order dependent, but we might not want the order of
2564 /// arguments to make a difference for the hash).
2565 ///
2566 /// However, since the value provided by Hash::hash often *is* suitable,
2567 /// especially for primitive types, there is the
2568 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2569 /// Hash implementation for DepTrackingHash. It's important though that
2570 /// we have an opt-in scheme here, so one is hopefully forced to think about
2571 /// how the hash should be calculated when adding a new command-line argument.
2572 mod dep_tracking {
2573     use crate::lint;
2574     use crate::middle::cstore;
2575     use std::collections::BTreeMap;
2576     use std::hash::Hash;
2577     use std::path::PathBuf;
2578     use std::collections::hash_map::DefaultHasher;
2579     use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2580                 Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
2581                 SymbolManglingVersion};
2582     use syntax::feature_gate::UnstableFeatures;
2583     use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2584     use syntax::edition::Edition;
2585
2586     pub trait DepTrackingHash {
2587         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2588     }
2589
2590     macro_rules! impl_dep_tracking_hash_via_hash {
2591         ($t:ty) => (
2592             impl DepTrackingHash for $t {
2593                 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2594                     Hash::hash(self, hasher);
2595                 }
2596             }
2597         )
2598     }
2599
2600     macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2601         ($t:ty) => (
2602             impl DepTrackingHash for Vec<$t> {
2603                 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2604                     let mut elems: Vec<&$t> = self.iter().collect();
2605                     elems.sort();
2606                     Hash::hash(&elems.len(), hasher);
2607                     for (index, elem) in elems.iter().enumerate() {
2608                         Hash::hash(&index, hasher);
2609                         DepTrackingHash::hash(*elem, hasher, error_format);
2610                     }
2611                 }
2612             }
2613         );
2614     }
2615
2616     impl_dep_tracking_hash_via_hash!(bool);
2617     impl_dep_tracking_hash_via_hash!(usize);
2618     impl_dep_tracking_hash_via_hash!(u64);
2619     impl_dep_tracking_hash_via_hash!(String);
2620     impl_dep_tracking_hash_via_hash!(PathBuf);
2621     impl_dep_tracking_hash_via_hash!(lint::Level);
2622     impl_dep_tracking_hash_via_hash!(Option<bool>);
2623     impl_dep_tracking_hash_via_hash!(Option<usize>);
2624     impl_dep_tracking_hash_via_hash!(Option<String>);
2625     impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2626     impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
2627     impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2628     impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2629     impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2630     impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2631     impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2632     impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2633     impl_dep_tracking_hash_via_hash!(CrateType);
2634     impl_dep_tracking_hash_via_hash!(MergeFunctions);
2635     impl_dep_tracking_hash_via_hash!(PanicStrategy);
2636     impl_dep_tracking_hash_via_hash!(RelroLevel);
2637     impl_dep_tracking_hash_via_hash!(Passes);
2638     impl_dep_tracking_hash_via_hash!(OptLevel);
2639     impl_dep_tracking_hash_via_hash!(LtoCli);
2640     impl_dep_tracking_hash_via_hash!(DebugInfo);
2641     impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2642     impl_dep_tracking_hash_via_hash!(OutputTypes);
2643     impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2644     impl_dep_tracking_hash_via_hash!(Sanitizer);
2645     impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2646     impl_dep_tracking_hash_via_hash!(TargetTriple);
2647     impl_dep_tracking_hash_via_hash!(Edition);
2648     impl_dep_tracking_hash_via_hash!(LinkerPluginLto);
2649     impl_dep_tracking_hash_via_hash!(SwitchWithOptPath);
2650     impl_dep_tracking_hash_via_hash!(SymbolManglingVersion);
2651
2652     impl_dep_tracking_hash_for_sortable_vec_of!(String);
2653     impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2654     impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2655     impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2656     impl_dep_tracking_hash_for_sortable_vec_of!((
2657         String,
2658         Option<String>,
2659         Option<cstore::NativeLibraryKind>
2660     ));
2661     impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2662
2663     impl<T1, T2> DepTrackingHash for (T1, T2)
2664     where
2665         T1: DepTrackingHash,
2666         T2: DepTrackingHash,
2667     {
2668         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2669             Hash::hash(&0, hasher);
2670             DepTrackingHash::hash(&self.0, hasher, error_format);
2671             Hash::hash(&1, hasher);
2672             DepTrackingHash::hash(&self.1, hasher, error_format);
2673         }
2674     }
2675
2676     impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2677     where
2678         T1: DepTrackingHash,
2679         T2: DepTrackingHash,
2680         T3: DepTrackingHash,
2681     {
2682         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2683             Hash::hash(&0, hasher);
2684             DepTrackingHash::hash(&self.0, hasher, error_format);
2685             Hash::hash(&1, hasher);
2686             DepTrackingHash::hash(&self.1, hasher, error_format);
2687             Hash::hash(&2, hasher);
2688             DepTrackingHash::hash(&self.2, hasher, error_format);
2689         }
2690     }
2691
2692     // This is a stable hash because BTreeMap is a sorted container
2693     pub fn stable_hash(
2694         sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2695         hasher: &mut DefaultHasher,
2696         error_format: ErrorOutputType,
2697     ) {
2698         for (key, sub_hash) in sub_hashes {
2699             // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2700             // the keys, as they are just plain strings
2701             Hash::hash(&key.len(), hasher);
2702             Hash::hash(key, hasher);
2703             sub_hash.hash(hasher, error_format);
2704         }
2705     }
2706 }
2707
2708 #[cfg(test)]
2709 mod tests {
2710     use getopts;
2711     use crate::lint;
2712     use crate::middle::cstore;
2713     use crate::session::config::{
2714         build_configuration,
2715         build_session_options_and_crate_config,
2716         to_crate_config
2717     };
2718     use crate::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry};
2719     use crate::session::build_session;
2720     use crate::session::search_paths::SearchPath;
2721     use std::collections::{BTreeMap, BTreeSet};
2722     use std::iter::FromIterator;
2723     use std::path::PathBuf;
2724     use super::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
2725     use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};
2726     use syntax::symbol::sym;
2727     use syntax::edition::{Edition, DEFAULT_EDITION};
2728     use syntax;
2729     use super::Options;
2730
2731     impl ExternEntry {
2732         fn new_public<S: Into<String>,
2733                       I: IntoIterator<Item = Option<S>>>(locations: I) -> ExternEntry {
2734             let locations: BTreeSet<_> = locations.into_iter().map(|o| o.map(|s| s.into()))
2735                 .collect();
2736
2737             ExternEntry {
2738                 locations,
2739                 is_private_dep: false
2740             }
2741         }
2742     }
2743
2744     fn optgroups() -> getopts::Options {
2745         let mut opts = getopts::Options::new();
2746         for group in super::rustc_optgroups() {
2747             (group.apply)(&mut opts);
2748         }
2749         return opts;
2750     }
2751
2752     fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2753         BTreeMap::from_iter(entries.into_iter())
2754     }
2755
2756     // When the user supplies --test we should implicitly supply --cfg test
2757     #[test]
2758     fn test_switch_implies_cfg_test() {
2759         syntax::with_default_globals(|| {
2760             let matches = &match optgroups().parse(&["--test".to_string()]) {
2761                 Ok(m) => m,
2762                 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2763             };
2764             let registry = errors::registry::Registry::new(&[]);
2765             let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2766             let sess = build_session(sessopts, None, registry);
2767             let cfg = build_configuration(&sess, to_crate_config(cfg));
2768             assert!(cfg.contains(&(sym::test, None)));
2769         });
2770     }
2771
2772     // When the user supplies --test and --cfg test, don't implicitly add
2773     // another --cfg test
2774     #[test]
2775     fn test_switch_implies_cfg_test_unless_cfg_test() {
2776         syntax::with_default_globals(|| {
2777             let matches = &match optgroups().parse(&["--test".to_string(),
2778                                                      "--cfg=test".to_string()]) {
2779                 Ok(m) => m,
2780                 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2781             };
2782             let registry = errors::registry::Registry::new(&[]);
2783             let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2784             let sess = build_session(sessopts, None, registry);
2785             let cfg = build_configuration(&sess, to_crate_config(cfg));
2786             let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
2787             assert!(test_items.next().is_some());
2788             assert!(test_items.next().is_none());
2789         });
2790     }
2791
2792     #[test]
2793     fn test_can_print_warnings() {
2794         syntax::with_default_globals(|| {
2795             let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2796             let registry = errors::registry::Registry::new(&[]);
2797             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2798             let sess = build_session(sessopts, None, registry);
2799             assert!(!sess.diagnostic().flags.can_emit_warnings);
2800         });
2801
2802         syntax::with_default_globals(|| {
2803             let matches = optgroups()
2804                 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2805                 .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().parse(&["-Adead_code".to_string()]).unwrap();
2814             let registry = errors::registry::Registry::new(&[]);
2815             let (sessopts, _) = build_session_options_and_crate_config(&matches);
2816             let sess = build_session(sessopts, None, registry);
2817             assert!(sess.diagnostic().flags.can_emit_warnings);
2818         });
2819     }
2820
2821     #[test]
2822     fn test_output_types_tracking_hash_different_paths() {
2823         let mut v1 = Options::default();
2824         let mut v2 = Options::default();
2825         let mut v3 = Options::default();
2826
2827         v1.output_types =
2828             OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2829         v2.output_types =
2830             OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2831         v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2832
2833         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2834         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2835         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2836
2837         // Check clone
2838         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2839         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2840         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2841     }
2842
2843     #[test]
2844     fn test_output_types_tracking_hash_different_construction_order() {
2845         let mut v1 = Options::default();
2846         let mut v2 = Options::default();
2847
2848         v1.output_types = OutputTypes::new(&[
2849             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2850             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2851         ]);
2852
2853         v2.output_types = OutputTypes::new(&[
2854             (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2855             (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2856         ]);
2857
2858         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2859
2860         // Check clone
2861         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2862     }
2863
2864     #[test]
2865     fn test_externs_tracking_hash_different_construction_order() {
2866         let mut v1 = Options::default();
2867         let mut v2 = Options::default();
2868         let mut v3 = Options::default();
2869
2870         v1.externs = Externs::new(mk_map(vec![
2871             (
2872                 String::from("a"),
2873                 ExternEntry::new_public(vec![Some("b"), Some("c")])
2874             ),
2875             (
2876                 String::from("d"),
2877                 ExternEntry::new_public(vec![Some("e"), Some("f")])
2878             ),
2879         ]));
2880
2881         v2.externs = Externs::new(mk_map(vec![
2882             (
2883                 String::from("d"),
2884                 ExternEntry::new_public(vec![Some("e"), Some("f")])
2885             ),
2886             (
2887                 String::from("a"),
2888                 ExternEntry::new_public(vec![Some("b"), Some("c")])
2889             ),
2890         ]));
2891
2892         v3.externs = Externs::new(mk_map(vec![
2893             (
2894                 String::from("a"),
2895                 ExternEntry::new_public(vec![Some("b"), Some("c")])
2896             ),
2897             (
2898                 String::from("d"),
2899                 ExternEntry::new_public(vec![Some("f"), Some("e")])
2900             ),
2901         ]));
2902
2903         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2904         assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2905         assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2906
2907         // Check clone
2908         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2909         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2910         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2911     }
2912
2913     #[test]
2914     fn test_lints_tracking_hash_different_values() {
2915         let mut v1 = Options::default();
2916         let mut v2 = Options::default();
2917         let mut v3 = Options::default();
2918
2919         v1.lint_opts = vec![
2920             (String::from("a"), lint::Allow),
2921             (String::from("b"), lint::Warn),
2922             (String::from("c"), lint::Deny),
2923             (String::from("d"), lint::Forbid),
2924         ];
2925
2926         v2.lint_opts = vec![
2927             (String::from("a"), lint::Allow),
2928             (String::from("b"), lint::Warn),
2929             (String::from("X"), lint::Deny),
2930             (String::from("d"), lint::Forbid),
2931         ];
2932
2933         v3.lint_opts = vec![
2934             (String::from("a"), lint::Allow),
2935             (String::from("b"), lint::Warn),
2936             (String::from("c"), lint::Forbid),
2937             (String::from("d"), lint::Deny),
2938         ];
2939
2940         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2941         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2942         assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2943
2944         // Check clone
2945         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2946         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2947         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2948     }
2949
2950     #[test]
2951     fn test_lints_tracking_hash_different_construction_order() {
2952         let mut v1 = Options::default();
2953         let mut v2 = Options::default();
2954
2955         v1.lint_opts = vec![
2956             (String::from("a"), lint::Allow),
2957             (String::from("b"), lint::Warn),
2958             (String::from("c"), lint::Deny),
2959             (String::from("d"), lint::Forbid),
2960         ];
2961
2962         v2.lint_opts = vec![
2963             (String::from("a"), lint::Allow),
2964             (String::from("c"), lint::Deny),
2965             (String::from("b"), lint::Warn),
2966             (String::from("d"), lint::Forbid),
2967         ];
2968
2969         assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2970
2971         // Check clone
2972         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2973         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2974     }
2975
2976     #[test]
2977     fn test_search_paths_tracking_hash_different_order() {
2978         let mut v1 = Options::default();
2979         let mut v2 = Options::default();
2980         let mut v3 = Options::default();
2981         let mut v4 = Options::default();
2982
2983         const JSON: super::ErrorOutputType = super::ErrorOutputType::Json {
2984             pretty: false,
2985             json_rendered: super::HumanReadableErrorType::Default(super::ColorConfig::Never),
2986         };
2987
2988         // Reference
2989         v1.search_paths
2990             .push(SearchPath::from_cli_opt("native=abc", JSON));
2991         v1.search_paths
2992             .push(SearchPath::from_cli_opt("crate=def", JSON));
2993         v1.search_paths
2994             .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
2995         v1.search_paths
2996             .push(SearchPath::from_cli_opt("framework=jkl", JSON));
2997         v1.search_paths
2998             .push(SearchPath::from_cli_opt("all=mno", JSON));
2999
3000         v2.search_paths
3001             .push(SearchPath::from_cli_opt("native=abc", JSON));
3002         v2.search_paths
3003             .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3004         v2.search_paths
3005             .push(SearchPath::from_cli_opt("crate=def", JSON));
3006         v2.search_paths
3007             .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3008         v2.search_paths
3009             .push(SearchPath::from_cli_opt("all=mno", JSON));
3010
3011         v3.search_paths
3012             .push(SearchPath::from_cli_opt("crate=def", JSON));
3013         v3.search_paths
3014             .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3015         v3.search_paths
3016             .push(SearchPath::from_cli_opt("native=abc", JSON));
3017         v3.search_paths
3018             .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3019         v3.search_paths
3020             .push(SearchPath::from_cli_opt("all=mno", JSON));
3021
3022         v4.search_paths
3023             .push(SearchPath::from_cli_opt("all=mno", JSON));
3024         v4.search_paths
3025             .push(SearchPath::from_cli_opt("native=abc", JSON));
3026         v4.search_paths
3027             .push(SearchPath::from_cli_opt("crate=def", JSON));
3028         v4.search_paths
3029             .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3030         v4.search_paths
3031             .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3032
3033         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3034         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3035         assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
3036
3037         // Check clone
3038         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3039         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3040         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3041         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3042     }
3043
3044     #[test]
3045     fn test_native_libs_tracking_hash_different_values() {
3046         let mut v1 = Options::default();
3047         let mut v2 = Options::default();
3048         let mut v3 = Options::default();
3049         let mut v4 = Options::default();
3050
3051         // Reference
3052         v1.libs = vec![
3053             (String::from("a"), None, Some(cstore::NativeStatic)),
3054             (String::from("b"), None, Some(cstore::NativeFramework)),
3055             (String::from("c"), None, Some(cstore::NativeUnknown)),
3056         ];
3057
3058         // Change label
3059         v2.libs = vec![
3060             (String::from("a"), None, Some(cstore::NativeStatic)),
3061             (String::from("X"), None, Some(cstore::NativeFramework)),
3062             (String::from("c"), None, Some(cstore::NativeUnknown)),
3063         ];
3064
3065         // Change kind
3066         v3.libs = vec![
3067             (String::from("a"), None, Some(cstore::NativeStatic)),
3068             (String::from("b"), None, Some(cstore::NativeStatic)),
3069             (String::from("c"), None, Some(cstore::NativeUnknown)),
3070         ];
3071
3072         // Change new-name
3073         v4.libs = vec![
3074             (String::from("a"), None, Some(cstore::NativeStatic)),
3075             (
3076                 String::from("b"),
3077                 Some(String::from("X")),
3078                 Some(cstore::NativeFramework),
3079             ),
3080             (String::from("c"), None, Some(cstore::NativeUnknown)),
3081         ];
3082
3083         assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
3084         assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
3085         assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
3086
3087         // Check clone
3088         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3089         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3090         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3091         assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3092     }
3093
3094     #[test]
3095     fn test_native_libs_tracking_hash_different_order() {
3096         let mut v1 = Options::default();
3097         let mut v2 = Options::default();
3098         let mut v3 = Options::default();
3099
3100         // Reference
3101         v1.libs = vec![
3102             (String::from("a"), None, Some(cstore::NativeStatic)),
3103             (String::from("b"), None, Some(cstore::NativeFramework)),
3104             (String::from("c"), None, Some(cstore::NativeUnknown)),
3105         ];
3106
3107         v2.libs = vec![
3108             (String::from("b"), None, Some(cstore::NativeFramework)),
3109             (String::from("a"), None, Some(cstore::NativeStatic)),
3110             (String::from("c"), None, Some(cstore::NativeUnknown)),
3111         ];
3112
3113         v3.libs = vec![
3114             (String::from("c"), None, Some(cstore::NativeUnknown)),
3115             (String::from("a"), None, Some(cstore::NativeStatic)),
3116             (String::from("b"), None, Some(cstore::NativeFramework)),
3117         ];
3118
3119         assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3120         assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3121         assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
3122
3123         // Check clone
3124         assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3125         assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3126         assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3127     }
3128
3129     #[test]
3130     fn test_codegen_options_tracking_hash() {
3131         let reference = Options::default();
3132         let mut opts = Options::default();
3133
3134         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3135         opts.cg.ar = Some(String::from("abc"));
3136         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3137
3138         opts.cg.linker = Some(PathBuf::from("linker"));
3139         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3140
3141         opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
3142         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3143
3144         opts.cg.link_dead_code = true;
3145         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3146
3147         opts.cg.rpath = true;
3148         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3149
3150         opts.cg.extra_filename = String::from("extra-filename");
3151         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3152
3153         opts.cg.codegen_units = Some(42);
3154         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3155
3156         opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
3157         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3158
3159         opts.cg.save_temps = true;
3160         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3161
3162         opts.cg.incremental = Some(String::from("abc"));
3163         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3164
3165         // Make sure changing a [TRACKED] option changes the hash
3166         opts = reference.clone();
3167         opts.cg.lto = LtoCli::Fat;
3168         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3169
3170         opts = reference.clone();
3171         opts.cg.target_cpu = Some(String::from("abc"));
3172         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3173
3174         opts = reference.clone();
3175         opts.cg.target_feature = String::from("all the features, all of them");
3176         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3177
3178         opts = reference.clone();
3179         opts.cg.passes = vec![String::from("1"), String::from("2")];
3180         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3181
3182         opts = reference.clone();
3183         opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
3184         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3185
3186         opts = reference.clone();
3187         opts.cg.overflow_checks = Some(true);
3188         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3189
3190         opts = reference.clone();
3191         opts.cg.no_prepopulate_passes = true;
3192         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3193
3194         opts = reference.clone();
3195         opts.cg.no_vectorize_loops = true;
3196         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3197
3198         opts = reference.clone();
3199         opts.cg.no_vectorize_slp = true;
3200         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3201
3202         opts = reference.clone();
3203         opts.cg.soft_float = true;
3204         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3205
3206         opts = reference.clone();
3207         opts.cg.prefer_dynamic = true;
3208         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3209
3210         opts = reference.clone();
3211         opts.cg.no_integrated_as = true;
3212         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3213
3214         opts = reference.clone();
3215         opts.cg.no_redzone = Some(true);
3216         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3217
3218         opts = reference.clone();
3219         opts.cg.relocation_model = Some(String::from("relocation model"));
3220         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3221
3222         opts = reference.clone();
3223         opts.cg.code_model = Some(String::from("code model"));
3224         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3225
3226         opts = reference.clone();
3227         opts.debugging_opts.tls_model = Some(String::from("tls model"));
3228         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3229
3230         opts = reference.clone();
3231         opts.debugging_opts.pgo_gen = SwitchWithOptPath::Enabled(None);
3232         assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3233
3234         opts = reference.clone();
3235         opts.debugging_opts.pgo_use = Some(PathBuf::from("abc"));
3236         assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3237
3238         opts = reference.clone();
3239         opts.cg.metadata = vec![String::from("A"), String::from("B")];
3240         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3241
3242         opts = reference.clone();
3243         opts.cg.debuginfo = Some(0xdeadbeef);
3244         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3245
3246         opts = reference.clone();
3247         opts.cg.debuginfo = Some(0xba5eba11);
3248         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3249
3250         opts = reference.clone();
3251         opts.cg.force_frame_pointers = Some(false);
3252         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3253
3254         opts = reference.clone();
3255         opts.cg.debug_assertions = Some(true);
3256         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3257
3258         opts = reference.clone();
3259         opts.cg.inline_threshold = Some(0xf007ba11);
3260         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3261
3262         opts = reference.clone();
3263         opts.cg.panic = Some(PanicStrategy::Abort);
3264         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3265
3266         opts = reference.clone();
3267         opts.cg.linker_plugin_lto = LinkerPluginLto::LinkerPluginAuto;
3268         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3269     }
3270
3271     #[test]
3272     fn test_debugging_options_tracking_hash() {
3273         let reference = Options::default();
3274         let mut opts = Options::default();
3275
3276         // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3277         opts.debugging_opts.verbose = true;
3278         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3279         opts.debugging_opts.time_passes = true;
3280         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3281         opts.debugging_opts.time_llvm_passes = true;
3282         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3283         opts.debugging_opts.input_stats = true;
3284         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3285         opts.debugging_opts.borrowck_stats = true;
3286         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3287         opts.debugging_opts.meta_stats = true;
3288         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3289         opts.debugging_opts.print_link_args = true;
3290         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3291         opts.debugging_opts.print_llvm_passes = true;
3292         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3293         opts.debugging_opts.ast_json = true;
3294         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3295         opts.debugging_opts.ast_json_noexpand = true;
3296         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3297         opts.debugging_opts.ls = true;
3298         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3299         opts.debugging_opts.save_analysis = true;
3300         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3301         opts.debugging_opts.flowgraph_print_loans = true;
3302         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3303         opts.debugging_opts.flowgraph_print_moves = true;
3304         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3305         opts.debugging_opts.flowgraph_print_assigns = true;
3306         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3307         opts.debugging_opts.flowgraph_print_all = true;
3308         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3309         opts.debugging_opts.print_region_graph = true;
3310         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3311         opts.debugging_opts.parse_only = true;
3312         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3313         opts.debugging_opts.incremental = Some(String::from("abc"));
3314         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3315         opts.debugging_opts.dump_dep_graph = true;
3316         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3317         opts.debugging_opts.query_dep_graph = true;
3318         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3319         opts.debugging_opts.no_analysis = true;
3320         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3321         opts.debugging_opts.unstable_options = true;
3322         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3323         opts.debugging_opts.trace_macros = true;
3324         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3325         opts.debugging_opts.keep_hygiene_data = true;
3326         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3327         opts.debugging_opts.keep_ast = true;
3328         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3329         opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3330         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3331         opts.debugging_opts.dump_mir = Some(String::from("abc"));
3332         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3333         opts.debugging_opts.dump_mir_dir = String::from("abc");
3334         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3335         opts.debugging_opts.dump_mir_graphviz = true;
3336         assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3337
3338         // Make sure changing a [TRACKED] option changes the hash
3339         opts = reference.clone();
3340         opts.debugging_opts.asm_comments = true;
3341         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3342
3343         opts = reference.clone();
3344         opts.debugging_opts.verify_llvm_ir = true;
3345         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3346
3347         opts = reference.clone();
3348         opts.debugging_opts.no_landing_pads = true;
3349         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3350
3351         opts = reference.clone();
3352         opts.debugging_opts.fewer_names = true;
3353         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3354
3355         opts = reference.clone();
3356         opts.debugging_opts.no_codegen = true;
3357         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3358
3359         opts = reference.clone();
3360         opts.debugging_opts.treat_err_as_bug = Some(1);
3361         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3362
3363         opts = reference.clone();
3364         opts.debugging_opts.report_delayed_bugs = true;
3365         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3366
3367         opts = reference.clone();
3368         opts.debugging_opts.continue_parse_after_error = true;
3369         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3370
3371         opts = reference.clone();
3372         opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3373         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3374
3375         opts = reference.clone();
3376         opts.debugging_opts.force_overflow_checks = Some(true);
3377         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3378
3379         opts = reference.clone();
3380         opts.debugging_opts.show_span = Some(String::from("abc"));
3381         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3382
3383         opts = reference.clone();
3384         opts.debugging_opts.mir_opt_level = 3;
3385         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3386
3387         opts = reference.clone();
3388         opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3389         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3390
3391         opts = reference.clone();
3392         opts.debugging_opts.merge_functions = Some(MergeFunctions::Disabled);
3393         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3394
3395         opts = reference.clone();
3396         opts.debugging_opts.allow_features = Some(vec![String::from("lang_items")]);
3397         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3398
3399         opts = reference.clone();
3400         opts.debugging_opts.symbol_mangling_version = SymbolManglingVersion::V0;
3401         assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3402     }
3403
3404     #[test]
3405     fn test_edition_parsing() {
3406         // test default edition
3407         let options = Options::default();
3408         assert!(options.edition == DEFAULT_EDITION);
3409
3410         let matches = optgroups()
3411             .parse(&["--edition=2018".to_string()])
3412             .unwrap();
3413         let (sessopts, _) = build_session_options_and_crate_config(&matches);
3414         assert!(sessopts.edition == Edition::Edition2018)
3415     }
3416 }