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