]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/options.rs
Reenable feature(nll) in alloc.
[rust.git] / compiler / rustc_session / src / options.rs
1 use crate::config::*;
2
3 use crate::early_error;
4 use crate::lint;
5 use crate::search_paths::SearchPath;
6 use crate::utils::NativeLib;
7
8 use rustc_target::spec::{CodeModel, LinkerFlavor, MergeFunctions, PanicStrategy, SanitizerSet};
9 use rustc_target::spec::{RelocModel, RelroLevel, SplitDebuginfo, TargetTriple, TlsModel};
10
11 use rustc_feature::UnstableFeatures;
12 use rustc_span::edition::Edition;
13 use rustc_span::RealFileName;
14 use rustc_span::SourceFileHashAlgorithm;
15
16 use std::collections::BTreeMap;
17
18 use std::collections::hash_map::DefaultHasher;
19 use std::hash::Hasher;
20 use std::num::NonZeroUsize;
21 use std::path::PathBuf;
22 use std::str;
23
24 macro_rules! insert {
25     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => {
26         if $sub_hashes
27             .insert(stringify!($opt_name), $opt_expr as &dyn dep_tracking::DepTrackingHash)
28             .is_some()
29         {
30             panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
31         }
32     };
33 }
34
35 macro_rules! hash_opt {
36     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [UNTRACKED]) => {{}};
37     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [TRACKED]) => {{ insert!($opt_name, $opt_expr, $sub_hashes) }};
38     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $for_crate_hash: ident, [TRACKED_NO_CRATE_HASH]) => {{
39         if !$for_crate_hash {
40             insert!($opt_name, $opt_expr, $sub_hashes)
41         }
42     }};
43     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [SUBSTRUCT]) => {{}};
44 }
45
46 macro_rules! hash_substruct {
47     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [UNTRACKED]) => {{}};
48     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED]) => {{}};
49     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED_NO_CRATE_HASH]) => {{}};
50     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [SUBSTRUCT]) => {
51         use crate::config::dep_tracking::DepTrackingHash;
52         $opt_expr.dep_tracking_hash($for_crate_hash, $error_format).hash(
53             $hasher,
54             $error_format,
55             $for_crate_hash,
56         );
57     };
58 }
59
60 macro_rules! top_level_options {
61     ( $( #[$top_level_attr:meta] )* pub struct Options { $(
62         $( #[$attr:meta] )*
63         $opt:ident : $t:ty [$dep_tracking_marker:ident],
64     )* } ) => (
65         #[derive(Clone)]
66         $( #[$top_level_attr] )*
67         pub struct Options {
68             $(
69                 $( #[$attr] )*
70                 pub $opt: $t
71             ),*
72         }
73
74         impl Options {
75             pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> u64 {
76                 let mut sub_hashes = BTreeMap::new();
77                 $({
78                     hash_opt!($opt,
79                                 &self.$opt,
80                                 &mut sub_hashes,
81                                 for_crate_hash,
82                                 [$dep_tracking_marker]);
83                 })*
84                 let mut hasher = DefaultHasher::new();
85                 dep_tracking::stable_hash(sub_hashes,
86                                           &mut hasher,
87                                           self.error_format,
88                                           for_crate_hash);
89                 $({
90                     hash_substruct!($opt,
91                         &self.$opt,
92                         self.error_format,
93                         for_crate_hash,
94                         &mut hasher,
95                         [$dep_tracking_marker]);
96                 })*
97                 hasher.finish()
98             }
99         }
100     );
101 }
102
103 top_level_options!(
104     /// The top-level command-line options struct.
105     ///
106     /// For each option, one has to specify how it behaves with regard to the
107     /// dependency tracking system of incremental compilation. This is done via the
108     /// square-bracketed directive after the field type. The options are:
109     ///
110     /// - `[TRACKED]`
111     /// A change in the given field will cause the compiler to completely clear the
112     /// incremental compilation cache before proceeding.
113     ///
114     /// - `[TRACKED_NO_CRATE_HASH]`
115     /// Same as `[TRACKED]`, but will not affect the crate hash. This is useful for options that only
116     /// affect the incremental cache.
117     ///
118     /// - `[UNTRACKED]`
119     /// Incremental compilation is not influenced by this option.
120     ///
121     /// - `[SUBSTRUCT]`
122     /// Second-level sub-structs containing more options.
123     ///
124     /// If you add a new option to this struct or one of the sub-structs like
125     /// `CodegenOptions`, think about how it influences incremental compilation. If in
126     /// doubt, specify `[TRACKED]`, which is always "correct" but might lead to
127     /// unnecessary re-compilation.
128     pub struct Options {
129         /// The crate config requested for the session, which may be combined
130         /// with additional crate configurations during the compile process.
131         crate_types: Vec<CrateType> [TRACKED],
132         optimize: OptLevel [TRACKED],
133         /// Include the `debug_assertions` flag in dependency tracking, since it
134         /// can influence whether overflow checks are done or not.
135         debug_assertions: bool [TRACKED],
136         debuginfo: DebugInfo [TRACKED],
137         lint_opts: Vec<(String, lint::Level)> [TRACKED_NO_CRATE_HASH],
138         lint_cap: Option<lint::Level> [TRACKED_NO_CRATE_HASH],
139         describe_lints: bool [UNTRACKED],
140         output_types: OutputTypes [TRACKED],
141         search_paths: Vec<SearchPath> [UNTRACKED],
142         libs: Vec<NativeLib> [TRACKED],
143         maybe_sysroot: Option<PathBuf> [UNTRACKED],
144
145         target_triple: TargetTriple [TRACKED],
146
147         test: bool [TRACKED],
148         error_format: ErrorOutputType [UNTRACKED],
149
150         /// If `Some`, enable incremental compilation, using the given
151         /// directory to store intermediate results.
152         incremental: Option<PathBuf> [UNTRACKED],
153
154         debugging_opts: DebuggingOptions [SUBSTRUCT],
155         prints: Vec<PrintRequest> [UNTRACKED],
156         /// Determines which borrow checker(s) to run. This is the parsed, sanitized
157         /// version of `debugging_opts.borrowck`, which is just a plain string.
158         borrowck_mode: BorrowckMode [UNTRACKED],
159         cg: CodegenOptions [SUBSTRUCT],
160         externs: Externs [UNTRACKED],
161         extern_dep_specs: ExternDepSpecs [UNTRACKED],
162         crate_name: Option<String> [TRACKED],
163         /// An optional name to use as the crate for std during std injection,
164         /// written `extern crate name as std`. Defaults to `std`. Used by
165         /// out-of-tree drivers.
166         alt_std_name: Option<String> [TRACKED],
167         /// Indicates how the compiler should treat unstable features.
168         unstable_features: UnstableFeatures [TRACKED],
169
170         /// Indicates whether this run of the compiler is actually rustdoc. This
171         /// is currently just a hack and will be removed eventually, so please
172         /// try to not rely on this too much.
173         actually_rustdoc: bool [TRACKED],
174
175         /// Control path trimming.
176         trimmed_def_paths: TrimmedDefPaths [TRACKED],
177
178         /// Specifications of codegen units / ThinLTO which are forced as a
179         /// result of parsing command line options. These are not necessarily
180         /// what rustc was invoked with, but massaged a bit to agree with
181         /// commands like `--emit llvm-ir` which they're often incompatible with
182         /// if we otherwise use the defaults of rustc.
183         cli_forced_codegen_units: Option<usize> [UNTRACKED],
184         cli_forced_thinlto_off: bool [UNTRACKED],
185
186         /// Remap source path prefixes in all output (messages, object files, debug, etc.).
187         remap_path_prefix: Vec<(PathBuf, PathBuf)> [TRACKED_NO_CRATE_HASH],
188         /// Base directory containing the `src/` for the Rust standard library, and
189         /// potentially `rustc` as well, if we can can find it. Right now it's always
190         /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
191         ///
192         /// This directory is what the virtual `/rustc/$hash` is translated back to,
193         /// if Rust was built with path remapping to `/rustc/$hash` enabled
194         /// (the `rust.remap-debuginfo` option in `config.toml`).
195         real_rust_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
196
197         edition: Edition [TRACKED],
198
199         /// `true` if we're emitting JSON blobs about each artifact produced
200         /// by the compiler.
201         json_artifact_notifications: bool [TRACKED],
202
203         /// `true` if we're emitting a JSON blob containing the unused externs
204         json_unused_externs: bool [UNTRACKED],
205
206         pretty: Option<PpMode> [UNTRACKED],
207
208         /// The (potentially remapped) working directory
209         working_dir: RealFileName [TRACKED],
210     }
211 );
212
213 /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
214 /// macro is to define an interface that can be programmatically used by the option parser
215 /// to initialize the struct without hardcoding field names all over the place.
216 ///
217 /// The goal is to invoke this macro once with the correct fields, and then this macro generates all
218 /// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
219 /// generated code to parse an option into its respective field in the struct. There are a few
220 /// hand-written parsers for parsing specific types of values in this module.
221 macro_rules! options {
222     ($struct_name:ident, $stat:ident, $prefix:expr, $outputname:expr,
223      $($( #[$attr:meta] )* $opt:ident : $t:ty = (
224         $init:expr,
225         $parse:ident,
226         [$dep_tracking_marker:ident],
227         $desc:expr)
228      ),* ,) =>
229 (
230     #[derive(Clone)]
231     pub struct $struct_name { $(pub $opt: $t),* }
232
233     impl Default for $struct_name {
234         fn default() -> $struct_name {
235             $struct_name { $( $( #[$attr] )* $opt: $init),* }
236         }
237     }
238
239     impl $struct_name {
240         pub fn build(
241             matches: &getopts::Matches,
242             error_format: ErrorOutputType,
243         ) -> $struct_name {
244             build_options(matches, $stat, $prefix, $outputname, error_format)
245         }
246
247         fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 {
248             let mut sub_hashes = BTreeMap::new();
249             $({
250                 hash_opt!($opt,
251                             &self.$opt,
252                             &mut sub_hashes,
253                             for_crate_hash,
254                             [$dep_tracking_marker]);
255             })*
256             let mut hasher = DefaultHasher::new();
257             dep_tracking::stable_hash(sub_hashes,
258                                         &mut hasher,
259                                         error_format,
260                                         for_crate_hash
261                                         );
262             hasher.finish()
263         }
264     }
265
266     pub const $stat: OptionDescrs<$struct_name> =
267         &[ $( (stringify!($opt), $opt, desc::$parse, $desc) ),* ];
268
269     $(
270         fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
271             parse::$parse(&mut redirect_field!(cg.$opt), v)
272         }
273     )*
274
275 ) }
276
277 // Sometimes different options need to build a common structure.
278 // That structure can be kept in one of the options' fields, the others become dummy.
279 macro_rules! redirect_field {
280     ($cg:ident.link_arg) => {
281         $cg.link_args
282     };
283     ($cg:ident.pre_link_arg) => {
284         $cg.pre_link_args
285     };
286     ($cg:ident.$field:ident) => {
287         $cg.$field
288     };
289 }
290
291 type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
292 type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)];
293
294 fn build_options<O: Default>(
295     matches: &getopts::Matches,
296     descrs: OptionDescrs<O>,
297     prefix: &str,
298     outputname: &str,
299     error_format: ErrorOutputType,
300 ) -> O {
301     let mut op = O::default();
302     for option in matches.opt_strs(prefix) {
303         let (key, value) = match option.split_once('=') {
304             None => (option, None),
305             Some((k, v)) => (k.to_string(), Some(v)),
306         };
307
308         let option_to_lookup = key.replace("-", "_");
309         match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
310             Some((_, setter, type_desc, _)) => {
311                 if !setter(&mut op, value) {
312                     match value {
313                         None => early_error(
314                             error_format,
315                             &format!(
316                                 "{0} option `{1}` requires {2} ({3} {1}=<value>)",
317                                 outputname, key, type_desc, prefix
318                             ),
319                         ),
320                         Some(value) => early_error(
321                             error_format,
322                             &format!(
323                                 "incorrect value `{}` for {} option `{}` - {} was expected",
324                                 value, outputname, key, type_desc
325                             ),
326                         ),
327                     }
328                 }
329             }
330             None => early_error(error_format, &format!("unknown {} option: `{}`", outputname, key)),
331         }
332     }
333     return op;
334 }
335
336 #[allow(non_upper_case_globals)]
337 mod desc {
338     pub const parse_no_flag: &str = "no value";
339     pub const parse_bool: &str = "one of: `y`, `yes`, `on`, `n`, `no`, or `off`";
340     pub const parse_opt_bool: &str = parse_bool;
341     pub const parse_string: &str = "a string";
342     pub const parse_opt_string: &str = parse_string;
343     pub const parse_string_push: &str = parse_string;
344     pub const parse_opt_pathbuf: &str = "a path";
345     pub const parse_list: &str = "a space-separated list of strings";
346     pub const parse_opt_comma_list: &str = "a comma-separated list of strings";
347     pub const parse_number: &str = "a number";
348     pub const parse_opt_number: &str = parse_number;
349     pub const parse_threads: &str = parse_number;
350     pub const parse_passes: &str = "a space-separated list of passes, or `all`";
351     pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
352     pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
353     pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
354     pub const parse_sanitizers: &str =
355         "comma separated list of sanitizers: `address`, `hwaddress`, `leak`, `memory` or `thread`";
356     pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
357     pub const parse_cfguard: &str =
358         "either a boolean (`yes`, `no`, `on`, `off`, etc), `checks`, or `nochecks`";
359     pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
360     pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavor::one_of();
361     pub const parse_optimization_fuel: &str = "crate=integer";
362     pub const parse_mir_spanview: &str = "`statement` (default), `terminator`, or `block`";
363     pub const parse_instrument_coverage: &str =
364         "`all` (default), `except-unused-generics`, `except-unused-functions`, or `off`";
365     pub const parse_unpretty: &str = "`string` or `string=string`";
366     pub const parse_treat_err_as_bug: &str = "either no value or a number bigger than 0";
367     pub const parse_lto: &str =
368         "either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
369     pub const parse_linker_plugin_lto: &str =
370         "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
371     pub const parse_switch_with_opt_path: &str =
372         "an optional path to the profiling data output directory";
373     pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
374     pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
375     pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
376     pub const parse_relocation_model: &str =
377         "one of supported relocation models (`rustc --print relocation-models`)";
378     pub const parse_code_model: &str = "one of supported code models (`rustc --print code-models`)";
379     pub const parse_tls_model: &str = "one of supported TLS models (`rustc --print tls-models`)";
380     pub const parse_target_feature: &str = parse_string;
381     pub const parse_wasi_exec_model: &str = "either `command` or `reactor`";
382     pub const parse_split_debuginfo: &str =
383         "one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)";
384     pub const parse_gcc_ld: &str = "one of: no value, `lld`";
385 }
386
387 mod parse {
388     crate use super::*;
389     use std::str::FromStr;
390
391     /// This is for boolean options that don't take a value and start with
392     /// `no-`. This style of option is deprecated.
393     crate fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool {
394         match v {
395             None => {
396                 *slot = true;
397                 true
398             }
399             Some(_) => false,
400         }
401     }
402
403     /// Use this for any boolean option that has a static default.
404     crate fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
405         match v {
406             Some("y") | Some("yes") | Some("on") | None => {
407                 *slot = true;
408                 true
409             }
410             Some("n") | Some("no") | Some("off") => {
411                 *slot = false;
412                 true
413             }
414             _ => false,
415         }
416     }
417
418     /// Use this for any boolean option that lacks a static default. (The
419     /// actions taken when such an option is not specified will depend on
420     /// other factors, such as other options, or target options.)
421     crate fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
422         match v {
423             Some("y") | Some("yes") | Some("on") | None => {
424                 *slot = Some(true);
425                 true
426             }
427             Some("n") | Some("no") | Some("off") => {
428                 *slot = Some(false);
429                 true
430             }
431             _ => false,
432         }
433     }
434
435     /// Use this for any string option that has a static default.
436     crate fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
437         match v {
438             Some(s) => {
439                 *slot = s.to_string();
440                 true
441             }
442             None => false,
443         }
444     }
445
446     /// Use this for any string option that lacks a static default.
447     crate fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
448         match v {
449             Some(s) => {
450                 *slot = Some(s.to_string());
451                 true
452             }
453             None => false,
454         }
455     }
456
457     crate fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
458         match v {
459             Some(s) => {
460                 *slot = Some(PathBuf::from(s));
461                 true
462             }
463             None => false,
464         }
465     }
466
467     crate fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
468         match v {
469             Some(s) => {
470                 slot.push(s.to_string());
471                 true
472             }
473             None => false,
474         }
475     }
476
477     crate fn parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
478         match v {
479             Some(s) => {
480                 slot.extend(s.split_whitespace().map(|s| s.to_string()));
481                 true
482             }
483             None => false,
484         }
485     }
486
487     crate fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
488         match v {
489             Some(s) => {
490                 let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
491                 v.sort_unstable();
492                 *slot = Some(v);
493                 true
494             }
495             None => false,
496         }
497     }
498
499     crate fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
500         match v.and_then(|s| s.parse().ok()) {
501             Some(0) => {
502                 *slot = ::num_cpus::get();
503                 true
504             }
505             Some(i) => {
506                 *slot = i;
507                 true
508             }
509             None => false,
510         }
511     }
512
513     /// Use this for any numeric option that has a static default.
514     crate fn parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool {
515         match v.and_then(|s| s.parse().ok()) {
516             Some(i) => {
517                 *slot = i;
518                 true
519             }
520             None => false,
521         }
522     }
523
524     /// Use this for any numeric option that lacks a static default.
525     crate fn parse_opt_number<T: Copy + FromStr>(slot: &mut Option<T>, v: Option<&str>) -> bool {
526         match v {
527             Some(s) => {
528                 *slot = s.parse().ok();
529                 slot.is_some()
530             }
531             None => false,
532         }
533     }
534
535     crate fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
536         match v {
537             Some("all") => {
538                 *slot = Passes::All;
539                 true
540             }
541             v => {
542                 let mut passes = vec![];
543                 if parse_list(&mut passes, v) {
544                     *slot = Passes::Some(passes);
545                     true
546                 } else {
547                     false
548                 }
549             }
550         }
551     }
552
553     crate fn parse_opt_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
554         match v {
555             Some("unwind") => *slot = Some(PanicStrategy::Unwind),
556             Some("abort") => *slot = Some(PanicStrategy::Abort),
557             _ => return false,
558         }
559         true
560     }
561
562     crate fn parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool {
563         match v {
564             Some("unwind") => *slot = PanicStrategy::Unwind,
565             Some("abort") => *slot = PanicStrategy::Abort,
566             _ => return false,
567         }
568         true
569     }
570
571     crate fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
572         match v {
573             Some(s) => match s.parse::<RelroLevel>() {
574                 Ok(level) => *slot = Some(level),
575                 _ => return false,
576             },
577             _ => return false,
578         }
579         true
580     }
581
582     crate fn parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool {
583         if let Some(v) = v {
584             for s in v.split(',') {
585                 *slot |= match s {
586                     "address" => SanitizerSet::ADDRESS,
587                     "leak" => SanitizerSet::LEAK,
588                     "memory" => SanitizerSet::MEMORY,
589                     "thread" => SanitizerSet::THREAD,
590                     "hwaddress" => SanitizerSet::HWADDRESS,
591                     _ => return false,
592                 }
593             }
594             true
595         } else {
596             false
597         }
598     }
599
600     crate fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
601         match v {
602             Some("2") | None => {
603                 *slot = 2;
604                 true
605             }
606             Some("1") => {
607                 *slot = 1;
608                 true
609             }
610             Some("0") => {
611                 *slot = 0;
612                 true
613             }
614             Some(_) => false,
615         }
616     }
617
618     crate fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
619         match v {
620             Some("none") => *slot = Strip::None,
621             Some("debuginfo") => *slot = Strip::Debuginfo,
622             Some("symbols") => *slot = Strip::Symbols,
623             _ => return false,
624         }
625         true
626     }
627
628     crate fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
629         if v.is_some() {
630             let mut bool_arg = None;
631             if parse_opt_bool(&mut bool_arg, v) {
632                 *slot = if bool_arg.unwrap() { CFGuard::Checks } else { CFGuard::Disabled };
633                 return true;
634             }
635         }
636
637         *slot = match v {
638             None => CFGuard::Checks,
639             Some("checks") => CFGuard::Checks,
640             Some("nochecks") => CFGuard::NoChecks,
641             Some(_) => return false,
642         };
643         true
644     }
645
646     crate fn parse_linker_flavor(slot: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
647         match v.and_then(LinkerFlavor::from_str) {
648             Some(lf) => *slot = Some(lf),
649             _ => return false,
650         }
651         true
652     }
653
654     crate fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
655         match v {
656             None => false,
657             Some(s) => {
658                 let parts = s.split('=').collect::<Vec<_>>();
659                 if parts.len() != 2 {
660                     return false;
661                 }
662                 let crate_name = parts[0].to_string();
663                 let fuel = parts[1].parse::<u64>();
664                 if fuel.is_err() {
665                     return false;
666                 }
667                 *slot = Some((crate_name, fuel.unwrap()));
668                 true
669             }
670         }
671     }
672
673     crate fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
674         match v {
675             None => false,
676             Some(s) if s.split('=').count() <= 2 => {
677                 *slot = Some(s.to_string());
678                 true
679             }
680             _ => false,
681         }
682     }
683
684     crate fn parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>) -> bool {
685         if v.is_some() {
686             let mut bool_arg = None;
687             if parse_opt_bool(&mut bool_arg, v) {
688                 *slot = if bool_arg.unwrap() { Some(MirSpanview::Statement) } else { None };
689                 return true;
690             }
691         }
692
693         let v = match v {
694             None => {
695                 *slot = Some(MirSpanview::Statement);
696                 return true;
697             }
698             Some(v) => v,
699         };
700
701         *slot = Some(match v.trim_end_matches('s') {
702             "statement" | "stmt" => MirSpanview::Statement,
703             "terminator" | "term" => MirSpanview::Terminator,
704             "block" | "basicblock" => MirSpanview::Block,
705             _ => return false,
706         });
707         true
708     }
709
710     crate fn parse_instrument_coverage(
711         slot: &mut Option<InstrumentCoverage>,
712         v: Option<&str>,
713     ) -> bool {
714         if v.is_some() {
715             let mut bool_arg = None;
716             if parse_opt_bool(&mut bool_arg, v) {
717                 *slot = if bool_arg.unwrap() { Some(InstrumentCoverage::All) } else { None };
718                 return true;
719             }
720         }
721
722         let v = match v {
723             None => {
724                 *slot = Some(InstrumentCoverage::All);
725                 return true;
726             }
727             Some(v) => v,
728         };
729
730         *slot = Some(match v {
731             "all" => InstrumentCoverage::All,
732             "except-unused-generics" | "except_unused_generics" => {
733                 InstrumentCoverage::ExceptUnusedGenerics
734             }
735             "except-unused-functions" | "except_unused_functions" => {
736                 InstrumentCoverage::ExceptUnusedFunctions
737             }
738             "off" | "no" | "n" | "false" | "0" => InstrumentCoverage::Off,
739             _ => return false,
740         });
741         true
742     }
743
744     crate fn parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool {
745         match v {
746             Some(s) => {
747                 *slot = s.parse().ok();
748                 slot.is_some()
749             }
750             None => {
751                 *slot = NonZeroUsize::new(1);
752                 true
753             }
754         }
755     }
756
757     crate fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
758         if v.is_some() {
759             let mut bool_arg = None;
760             if parse_opt_bool(&mut bool_arg, v) {
761                 *slot = if bool_arg.unwrap() { LtoCli::Yes } else { LtoCli::No };
762                 return true;
763             }
764         }
765
766         *slot = match v {
767             None => LtoCli::NoParam,
768             Some("thin") => LtoCli::Thin,
769             Some("fat") => LtoCli::Fat,
770             Some(_) => return false,
771         };
772         true
773     }
774
775     crate fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
776         if v.is_some() {
777             let mut bool_arg = None;
778             if parse_opt_bool(&mut bool_arg, v) {
779                 *slot = if bool_arg.unwrap() {
780                     LinkerPluginLto::LinkerPluginAuto
781                 } else {
782                     LinkerPluginLto::Disabled
783                 };
784                 return true;
785             }
786         }
787
788         *slot = match v {
789             None => LinkerPluginLto::LinkerPluginAuto,
790             Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
791         };
792         true
793     }
794
795     crate fn parse_switch_with_opt_path(slot: &mut SwitchWithOptPath, v: Option<&str>) -> bool {
796         *slot = match v {
797             None => SwitchWithOptPath::Enabled(None),
798             Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
799         };
800         true
801     }
802
803     crate fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
804         match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
805             Some(mergefunc) => *slot = Some(mergefunc),
806             _ => return false,
807         }
808         true
809     }
810
811     crate fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
812         match v.and_then(|s| RelocModel::from_str(s).ok()) {
813             Some(relocation_model) => *slot = Some(relocation_model),
814             None if v == Some("default") => *slot = None,
815             _ => return false,
816         }
817         true
818     }
819
820     crate fn parse_code_model(slot: &mut Option<CodeModel>, v: Option<&str>) -> bool {
821         match v.and_then(|s| CodeModel::from_str(s).ok()) {
822             Some(code_model) => *slot = Some(code_model),
823             _ => return false,
824         }
825         true
826     }
827
828     crate fn parse_tls_model(slot: &mut Option<TlsModel>, v: Option<&str>) -> bool {
829         match v.and_then(|s| TlsModel::from_str(s).ok()) {
830             Some(tls_model) => *slot = Some(tls_model),
831             _ => return false,
832         }
833         true
834     }
835
836     crate fn parse_symbol_mangling_version(
837         slot: &mut Option<SymbolManglingVersion>,
838         v: Option<&str>,
839     ) -> bool {
840         *slot = match v {
841             Some("legacy") => Some(SymbolManglingVersion::Legacy),
842             Some("v0") => Some(SymbolManglingVersion::V0),
843             _ => return false,
844         };
845         true
846     }
847
848     crate fn parse_src_file_hash(
849         slot: &mut Option<SourceFileHashAlgorithm>,
850         v: Option<&str>,
851     ) -> bool {
852         match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
853             Some(hash_kind) => *slot = Some(hash_kind),
854             _ => return false,
855         }
856         true
857     }
858
859     crate fn parse_target_feature(slot: &mut String, v: Option<&str>) -> bool {
860         match v {
861             Some(s) => {
862                 if !slot.is_empty() {
863                     slot.push_str(",");
864                 }
865                 slot.push_str(s);
866                 true
867             }
868             None => false,
869         }
870     }
871
872     crate fn parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool {
873         match v {
874             Some("command") => *slot = Some(WasiExecModel::Command),
875             Some("reactor") => *slot = Some(WasiExecModel::Reactor),
876             _ => return false,
877         }
878         true
879     }
880
881     crate fn parse_split_debuginfo(slot: &mut Option<SplitDebuginfo>, v: Option<&str>) -> bool {
882         match v.and_then(|s| SplitDebuginfo::from_str(s).ok()) {
883             Some(e) => *slot = Some(e),
884             _ => return false,
885         }
886         true
887     }
888
889     crate fn parse_gcc_ld(slot: &mut Option<LdImpl>, v: Option<&str>) -> bool {
890         match v {
891             None => *slot = None,
892             Some("lld") => *slot = Some(LdImpl::Lld),
893             _ => return false,
894         }
895         true
896     }
897 }
898
899 options! {
900     CodegenOptions, CG_OPTIONS, "C", "codegen",
901
902     // This list is in alphabetical order.
903     //
904     // If you add a new option, please update:
905     // - compiler/rustc_interface/src/tests.rs
906     // - src/doc/rustc/src/codegen-options/index.md
907
908     ar: String = (String::new(), parse_string, [UNTRACKED],
909         "this option is deprecated and does nothing"),
910     code_model: Option<CodeModel> = (None, parse_code_model, [TRACKED],
911         "choose the code model to use (`rustc --print code-models` for details)"),
912     codegen_units: Option<usize> = (None, parse_opt_number, [UNTRACKED],
913         "divide crate into N units to optimize in parallel"),
914     control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [TRACKED],
915         "use Windows Control Flow Guard (default: no)"),
916     debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
917         "explicitly enable the `cfg(debug_assertions)` directive"),
918     debuginfo: usize = (0, parse_number, [TRACKED],
919         "debug info emission level (0 = no debug info, 1 = line tables only, \
920         2 = full debug info with variable and type information; default: 0)"),
921     default_linker_libraries: bool = (false, parse_bool, [UNTRACKED],
922         "allow the linker to link its default libraries (default: no)"),
923     embed_bitcode: bool = (true, parse_bool, [TRACKED],
924         "emit bitcode in rlibs (default: yes)"),
925     extra_filename: String = (String::new(), parse_string, [UNTRACKED],
926         "extra data to put in each output filename"),
927     force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
928         "force use of the frame pointers"),
929     force_unwind_tables: Option<bool> = (None, parse_opt_bool, [TRACKED],
930         "force use of unwind tables"),
931     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
932         "enable incremental compilation"),
933     inline_threshold: Option<u32> = (None, parse_opt_number, [TRACKED],
934         "set the threshold for inlining a function"),
935     link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
936         "a single extra argument to append to the linker invocation (can be used several times)"),
937     link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
938         "extra arguments to append to the linker invocation (space separated)"),
939     link_dead_code: Option<bool> = (None, parse_opt_bool, [TRACKED],
940         "keep dead code at link time (useful for code coverage) (default: no)"),
941     link_self_contained: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
942         "control whether to link Rust provided C objects/libraries or rely
943         on C toolchain installed in the system"),
944     linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
945         "system linker to link outputs with"),
946     linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
947         "linker flavor"),
948     linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
949         parse_linker_plugin_lto, [TRACKED],
950         "generate build artifacts that are compatible with linker-based LTO"),
951     llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
952         "a list of arguments to pass to LLVM (space separated)"),
953     lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
954         "perform LLVM link-time optimizations"),
955     metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
956         "metadata to mangle symbol names with"),
957     no_prepopulate_passes: bool = (false, parse_no_flag, [TRACKED],
958         "give an empty list of passes to the pass manager"),
959     no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
960         "disable the use of the redzone"),
961     no_stack_check: bool = (false, parse_no_flag, [UNTRACKED],
962         "this option is deprecated and does nothing"),
963     no_vectorize_loops: bool = (false, parse_no_flag, [TRACKED],
964         "disable loop vectorization optimization passes"),
965     no_vectorize_slp: bool = (false, parse_no_flag, [TRACKED],
966         "disable LLVM's SLP vectorization pass"),
967     opt_level: String = ("0".to_string(), parse_string, [TRACKED],
968         "optimization level (0-3, s, or z; default: 0)"),
969     overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
970         "use overflow checks for integer arithmetic"),
971     panic: Option<PanicStrategy> = (None, parse_opt_panic_strategy, [TRACKED],
972         "panic strategy to compile crate with"),
973     passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
974         "a list of extra LLVM passes to run (space separated)"),
975     prefer_dynamic: bool = (false, parse_bool, [TRACKED],
976         "prefer dynamic linking to static linking (default: no)"),
977     profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
978         parse_switch_with_opt_path, [TRACKED],
979         "compile the program with profiling instrumentation"),
980     profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
981         "use the given `.profdata` file for profile-guided optimization"),
982     relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
983         "control generation of position-independent code (PIC) \
984         (`rustc --print relocation-models` for details)"),
985     remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
986         "print remarks for these optimization passes (space separated, or \"all\")"),
987     rpath: bool = (false, parse_bool, [UNTRACKED],
988         "set rpath values in libs/exes (default: no)"),
989     save_temps: bool = (false, parse_bool, [UNTRACKED],
990         "save all temporary output files during compilation (default: no)"),
991     soft_float: bool = (false, parse_bool, [TRACKED],
992         "use soft float ABI (*eabihf targets only) (default: no)"),
993     split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
994         "how to handle split-debuginfo, a platform-specific option"),
995     target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
996         "select target processor (`rustc --print target-cpus` for details)"),
997     target_feature: String = (String::new(), parse_target_feature, [TRACKED],
998         "target specific attributes. (`rustc --print target-features` for details). \
999         This feature is unsafe."),
1000
1001     // This list is in alphabetical order.
1002     //
1003     // If you add a new option, please update:
1004     // - compiler/rustc_interface/src/tests.rs
1005     // - src/doc/rustc/src/codegen-options/index.md
1006 }
1007
1008 options! {
1009     DebuggingOptions, DB_OPTIONS, "Z", "debugging",
1010
1011     // This list is in alphabetical order.
1012     //
1013     // If you add a new option, please update:
1014     // - compiler/rustc_interface/src/tests.rs
1015
1016     allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1017         "only allow the listed language features to be enabled in code (space separated)"),
1018     always_encode_mir: bool = (false, parse_bool, [TRACKED],
1019         "encode MIR of all functions into the crate metadata (default: no)"),
1020     assume_incomplete_release: bool = (false, parse_bool, [TRACKED],
1021         "make cfg(version) treat the current version as incomplete (default: no)"),
1022     asm_comments: bool = (false, parse_bool, [TRACKED],
1023         "generate comments into the assembly (may change behavior) (default: no)"),
1024     ast_json: bool = (false, parse_bool, [UNTRACKED],
1025         "print the AST as JSON and halt (default: no)"),
1026     ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1027         "print the pre-expansion AST as JSON and halt (default: no)"),
1028     binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
1029         "include artifacts (sysroot, crate dependencies) used during compilation in dep-info \
1030         (default: no)"),
1031     borrowck: String = ("migrate".to_string(), parse_string, [UNTRACKED],
1032         "select which borrowck is used (`mir` or `migrate`) (default: `migrate`)"),
1033     cgu_partitioning_strategy: Option<String> = (None, parse_opt_string, [TRACKED],
1034         "the codegen unit partitioning strategy to use"),
1035     chalk: bool = (false, parse_bool, [TRACKED],
1036         "enable the experimental Chalk-based trait solving engine"),
1037     codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1038         "the backend to use"),
1039     combine_cgu: bool = (false, parse_bool, [TRACKED],
1040         "combine CGUs into a single one"),
1041     crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1042         "inject the given attribute in the crate"),
1043     debug_info_for_profiling: bool = (false, parse_bool, [TRACKED],
1044         "emit discriminators and other data necessary for AutoFDO"),
1045     debug_macros: bool = (false, parse_bool, [TRACKED],
1046         "emit line numbers debug info inside macros (default: no)"),
1047     deduplicate_diagnostics: bool = (true, parse_bool, [UNTRACKED],
1048         "deduplicate identical diagnostics (default: yes)"),
1049     dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1050         "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1051         themselves (default: no)"),
1052     dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1053         "print tasks that execute and the color their dep node gets (requires debug build) \
1054         (default: no)"),
1055     dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1056         "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) \
1057         (default: no)"),
1058     dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1059         "load proc macros for both target and host, but only link to the target (default: no)"),
1060     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1061         "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) \
1062         (default: no)"),
1063     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1064         "dump MIR state to file.
1065         `val` is used to select which passes and functions to dump. For example:
1066         `all` matches all passes and functions,
1067         `foo` matches all passes for functions whose name contains 'foo',
1068         `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1069         `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1070     dump_mir_dataflow: bool = (false, parse_bool, [UNTRACKED],
1071         "in addition to `.mir` files, create graphviz `.dot` files with dataflow results \
1072         (default: no)"),
1073     dump_mir_dir: String = ("mir_dump".to_string(), parse_string, [UNTRACKED],
1074         "the directory the MIR is dumped into (default: `mir_dump`)"),
1075     dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1076         "exclude the pass number when dumping MIR (used in tests) (default: no)"),
1077     dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1078         "in addition to `.mir` files, create graphviz `.dot` files (and with \
1079         `-Z instrument-coverage`, also create a `.dot` file for the MIR-derived \
1080         coverage graph) (default: no)"),
1081     dump_mir_spanview: Option<MirSpanview> = (None, parse_mir_spanview, [UNTRACKED],
1082         "in addition to `.mir` files, create `.html` files to view spans for \
1083         all `statement`s (including terminators), only `terminator` spans, or \
1084         computed `block` spans (one span encompassing a block's terminator and \
1085         all statements). If `-Z instrument-coverage` is also enabled, create \
1086         an additional `.html` file showing the computed coverage spans."),
1087     emit_future_incompat_report: bool = (false, parse_bool, [UNTRACKED],
1088         "emits a future-incompatibility report for lints (RFC 2834)"),
1089     emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1090         "emit a section containing stack size metadata (default: no)"),
1091     fewer_names: Option<bool> = (None, parse_opt_bool, [TRACKED],
1092         "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \
1093         (default: no)"),
1094     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1095         "force overflow checks on or off"),
1096     force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1097         "force all crates to be `rustc_private` unstable (default: no)"),
1098     fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1099         "set the optimization fuel quota for a crate"),
1100     function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
1101         "whether each function should go in its own section"),
1102     future_incompat_test: bool = (false, parse_bool, [UNTRACKED],
1103         "forces all lints to be future incompatible, used for internal testing (default: no)"),
1104     gcc_ld: Option<LdImpl> = (None, parse_gcc_ld, [TRACKED], "implementation of ld used by cc"),
1105     graphviz_dark_mode: bool = (false, parse_bool, [UNTRACKED],
1106         "use dark-themed colors in graphviz output (default: no)"),
1107     graphviz_font: String = ("Courier, monospace".to_string(), parse_string, [UNTRACKED],
1108         "use the given `fontname` in graphviz output; can be overridden by setting \
1109         environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`)"),
1110     hir_stats: bool = (false, parse_bool, [UNTRACKED],
1111         "print some statistics about AST and HIR (default: no)"),
1112     human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1113         "generate human-readable, predictable names for codegen units (default: no)"),
1114     identify_regions: bool = (false, parse_bool, [UNTRACKED],
1115         "display unnamed regions as `'<id>`, using a non-ident unique id (default: no)"),
1116     incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1117         "ignore spans during ICH computation -- used for testing (default: no)"),
1118     incremental_info: bool = (false, parse_bool, [UNTRACKED],
1119         "print high-level information about incremental reuse (or the lack thereof) \
1120         (default: no)"),
1121     incremental_relative_spans: bool = (false, parse_bool, [TRACKED],
1122         "hash spans relative to their parent item for incr. comp. (default: no)"),
1123     incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1124         "verify incr. comp. hashes of green query instances (default: no)"),
1125     inline_mir: Option<bool> = (None, parse_opt_bool, [TRACKED],
1126         "enable MIR inlining (default: no)"),
1127     inline_mir_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1128         "a default MIR inlining threshold (default: 50)"),
1129     inline_mir_hint_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1130         "inlining threshold for functions with inline hint (default: 100)"),
1131     inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1132         "control whether `#[inline]` functions are in all CGUs"),
1133     input_stats: bool = (false, parse_bool, [UNTRACKED],
1134         "gather statistics about the input (default: no)"),
1135     instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
1136         "instrument the generated code to support LLVM source-based code coverage \
1137         reports (note, the compiler build config must include `profiler = true`); \
1138         implies `-Z symbol-mangling-version=v0`. Optional values are:
1139         `=all` (implicit value)
1140         `=except-unused-generics`
1141         `=except-unused-functions`
1142         `=off` (default)"),
1143     instrument_mcount: bool = (false, parse_bool, [TRACKED],
1144         "insert function instrument code for mcount-based tracing (default: no)"),
1145     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1146         "keep hygiene data after analysis (default: no)"),
1147     link_native_libraries: bool = (true, parse_bool, [UNTRACKED],
1148         "link native libraries in the linker invocation (default: yes)"),
1149     link_only: bool = (false, parse_bool, [TRACKED],
1150         "link the `.rlink` file generated by `-Z no-link` (default: no)"),
1151     llvm_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1152         "a list LLVM plugins to enable (space separated)"),
1153     llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
1154         "generate JSON tracing data file from LLVM data (default: no)"),
1155     ls: bool = (false, parse_bool, [UNTRACKED],
1156         "list the symbols defined by a library crate (default: no)"),
1157     macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1158         "show macro backtraces (default: no)"),
1159     merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1160         "control the operation of the MergeFunctions LLVM pass, taking \
1161         the same values as the target option of the same name"),
1162     meta_stats: bool = (false, parse_bool, [UNTRACKED],
1163         "gather metadata statistics (default: no)"),
1164     mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1165         "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
1166         (default: no)"),
1167     mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
1168         "MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),
1169     move_size_limit: Option<usize> = (None, parse_opt_number, [TRACKED],
1170         "the size at which the `large_assignments` lint starts to be emitted"),
1171     mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1172         "emit noalias metadata for mutable references (default: yes for LLVM >= 12, otherwise no)"),
1173     new_llvm_pass_manager: Option<bool> = (None, parse_opt_bool, [TRACKED],
1174         "use new LLVM pass manager (default: no)"),
1175     nll_facts: bool = (false, parse_bool, [UNTRACKED],
1176         "dump facts from NLL analysis into side files (default: no)"),
1177     nll_facts_dir: String = ("nll-facts".to_string(), parse_string, [UNTRACKED],
1178         "the directory the NLL facts are dumped into (default: `nll-facts`)"),
1179     no_analysis: bool = (false, parse_no_flag, [UNTRACKED],
1180         "parse and expand the source, but run no analysis"),
1181     no_codegen: bool = (false, parse_no_flag, [TRACKED_NO_CRATE_HASH],
1182         "run all passes except codegen; no output"),
1183     no_generate_arange_section: bool = (false, parse_no_flag, [TRACKED],
1184         "omit DWARF address ranges that give faster lookups"),
1185     no_interleave_lints: bool = (false, parse_no_flag, [UNTRACKED],
1186         "execute lints separately; allows benchmarking individual lints"),
1187     no_leak_check: bool = (false, parse_no_flag, [UNTRACKED],
1188         "disable the 'leak check' for subtyping; unsound, but useful for tests"),
1189     no_link: bool = (false, parse_no_flag, [TRACKED],
1190         "compile without linking"),
1191     no_parallel_llvm: bool = (false, parse_no_flag, [UNTRACKED],
1192         "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"),
1193     no_profiler_runtime: bool = (false, parse_no_flag, [TRACKED],
1194         "prevent automatic injection of the profiler_builtins crate"),
1195     normalize_docs: bool = (false, parse_bool, [TRACKED],
1196         "normalize associated items in rustdoc when generating documentation"),
1197     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1198         "pass `-install_name @rpath/...` to the macOS linker (default: no)"),
1199     panic_abort_tests: bool = (false, parse_bool, [TRACKED],
1200         "support compiling tests with panic=abort (default: no)"),
1201     panic_in_drop: PanicStrategy = (PanicStrategy::Unwind, parse_panic_strategy, [TRACKED],
1202         "panic strategy for panics in drops"),
1203     parse_only: bool = (false, parse_bool, [UNTRACKED],
1204         "parse only; do not compile, assemble, or link (default: no)"),
1205     partially_uninit_const_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1206         "allow generating const initializers with mixed init/uninit bytes, \
1207         and set the maximum total size of a const allocation for which this is allowed (default: never)"),
1208     perf_stats: bool = (false, parse_bool, [UNTRACKED],
1209         "print some performance-related statistics (default: no)"),
1210     plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1211         "whether to use the PLT when calling into shared libraries;
1212         only has effect for PIC code on systems with ELF binaries
1213         (default: PLT is disabled if full relro is enabled)"),
1214     polonius: bool = (false, parse_bool, [TRACKED],
1215         "enable polonius-based borrow-checker (default: no)"),
1216     polymorphize: bool = (false, parse_bool, [TRACKED],
1217           "perform polymorphization analysis"),
1218     pre_link_arg: (/* redirected to pre_link_args */) = ((), parse_string_push, [UNTRACKED],
1219         "a single extra argument to prepend the linker invocation (can be used several times)"),
1220     pre_link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
1221         "extra arguments to prepend to the linker invocation (space separated)"),
1222     precise_enum_drop_elaboration: bool = (true, parse_bool, [TRACKED],
1223         "use a more precise version of drop elaboration for matches on enums (default: yes). \
1224         This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
1225         See #77382 and #74551."),
1226     print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1227         "make rustc print the total optimization fuel used by a crate"),
1228     print_link_args: bool = (false, parse_bool, [UNTRACKED],
1229         "print the arguments passed to the linker (default: no)"),
1230     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1231         "print the LLVM optimization passes being run (default: no)"),
1232     print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1233         "print the result of the monomorphization collection pass"),
1234     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1235         "print layout information for each type encountered (default: no)"),
1236     proc_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1237          "show backtraces for panics during proc-macro execution (default: no)"),
1238     profile: bool = (false, parse_bool, [TRACKED],
1239         "insert profiling code (default: no)"),
1240     profile_closures: bool = (false, parse_no_flag, [UNTRACKED],
1241         "profile size of closures"),
1242     profile_emit: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1243         "file path to emit profiling data at runtime when using 'profile' \
1244         (default based on relative source path)"),
1245     profiler_runtime: String = (String::from("profiler_builtins"), parse_string, [TRACKED],
1246         "name of the profiler runtime crate to automatically inject (default: `profiler_builtins`)"),
1247     profile_sample_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1248         "use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO)"),
1249     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1250         "enable queries of the dependency graph for regression testing (default: no)"),
1251     query_stats: bool = (false, parse_bool, [UNTRACKED],
1252         "print some statistics about the query system (default: no)"),
1253     randomize_layout: bool = (false, parse_bool, [TRACKED],
1254         "randomize the layout of types (default: no)"),
1255     relax_elf_relocations: Option<bool> = (None, parse_opt_bool, [TRACKED],
1256         "whether ELF relocations can be relaxed"),
1257     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1258         "choose which RELRO level to use"),
1259     remap_cwd_prefix: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1260         "remap paths under the current working directory to this path prefix"),
1261     simulate_remapped_rust_src_base: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1262         "simulate the effect of remap-debuginfo = true at bootstrapping by remapping path \
1263         to rust's source base directory. only meant for testing purposes"),
1264     report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1265         "immediately print bugs registered with `delay_span_bug` (default: no)"),
1266     sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1267         "use a sanitizer"),
1268     sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED],
1269         "enable origins tracking in MemorySanitizer"),
1270     sanitizer_recover: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1271         "enable recovery for selected sanitizers"),
1272     saturating_float_casts: Option<bool> = (None, parse_opt_bool, [TRACKED],
1273         "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1274         the max/min integer respectively, and NaN is mapped to 0 (default: yes)"),
1275     save_analysis: bool = (false, parse_bool, [UNTRACKED],
1276         "write syntax and type analysis (in JSON format) information, in \
1277         addition to normal output (default: no)"),
1278     self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1279         parse_switch_with_opt_path, [UNTRACKED],
1280         "run the self profiler and output the raw event data"),
1281     /// keep this in sync with the event filter names in librustc_data_structures/profiling.rs
1282     self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1283         "specify the events recorded by the self profiler;
1284         for example: `-Z self-profile-events=default,query-keys`
1285         all options: none, all, default, generic-activity, query-provider, query-cache-hit
1286                      query-blocked, incr-cache-load, incr-result-hashing, query-keys, function-args, args, llvm"),
1287     share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1288         "make the current crate share its generic instantiations"),
1289     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1290         "show spans for compiler debugging (expr|pat|ty)"),
1291     span_debug: bool = (false, parse_bool, [UNTRACKED],
1292         "forward proc_macro::Span's `Debug` impl to `Span`"),
1293     /// o/w tests have closure@path
1294     span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1295         "exclude spans when debug-printing compiler state (default: no)"),
1296     src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
1297         "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
1298     strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
1299         "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
1300     split_dwarf_inlining: bool = (true, parse_bool, [UNTRACKED],
1301         "provide minimal debug info in the object/executable to facilitate online \
1302          symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF"),
1303     symbol_mangling_version: Option<SymbolManglingVersion> = (None,
1304         parse_symbol_mangling_version, [TRACKED],
1305         "which mangling version to use for symbol names ('legacy' (default) or 'v0')"),
1306     teach: bool = (false, parse_bool, [TRACKED],
1307         "show extended diagnostic help (default: no)"),
1308     terminal_width: Option<usize> = (None, parse_opt_number, [UNTRACKED],
1309         "set the current terminal width"),
1310     tune_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1311         "select processor to schedule for (`rustc --print target-cpus` for details)"),
1312     thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1313         "enable ThinLTO when possible"),
1314     thir_unsafeck: bool = (false, parse_bool, [TRACKED],
1315         "use the THIR unsafety checker (default: no)"),
1316     /// We default to 1 here since we want to behave like
1317     /// a sequential compiler for now. This'll likely be adjusted
1318     /// in the future. Note that -Zthreads=0 is the way to get
1319     /// the num_cpus behavior.
1320     threads: usize = (1, parse_threads, [UNTRACKED],
1321         "use a thread pool with N threads"),
1322     time: bool = (false, parse_bool, [UNTRACKED],
1323         "measure time of rustc processes (default: no)"),
1324     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1325         "measure time of each LLVM pass (default: no)"),
1326     time_passes: bool = (false, parse_bool, [UNTRACKED],
1327         "measure time of each rustc pass (default: no)"),
1328     tls_model: Option<TlsModel> = (None, parse_tls_model, [TRACKED],
1329         "choose the TLS model to use (`rustc --print tls-models` for details)"),
1330     trace_macros: bool = (false, parse_bool, [UNTRACKED],
1331         "for every macro invocation, print its name and arguments (default: no)"),
1332     trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED],
1333         "generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"),
1334     treat_err_as_bug: Option<NonZeroUsize> = (None, parse_treat_err_as_bug, [TRACKED],
1335         "treat error number `val` that occurs as bug"),
1336     trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED],
1337         "in diagnostics, use heuristics to shorten paths referring to items"),
1338     ui_testing: bool = (false, parse_bool, [UNTRACKED],
1339         "emit compiler diagnostics in a form suitable for UI testing (default: no)"),
1340     unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1341         "take the brakes off const evaluation. NOTE: this is unsound (default: no)"),
1342     unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1343         "present the input source, unstable (and less-pretty) variants;
1344         `normal`, `identified`,
1345         `expanded`, `expanded,identified`,
1346         `expanded,hygiene` (with internal representations),
1347         `everybody_loops` (all function bodies replaced with `loop {}`),
1348         `ast-tree` (raw AST before expansion),
1349         `ast-tree,expanded` (raw AST after expansion),
1350         `hir` (the HIR), `hir,identified`,
1351         `hir,typed` (HIR with types for each node),
1352         `hir-tree` (dump the raw HIR),
1353         `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1354     unsound_mir_opts: bool = (false, parse_bool, [TRACKED],
1355         "enable unsound and buggy MIR optimizations (default: no)"),
1356     unstable_options: bool = (false, parse_bool, [UNTRACKED],
1357         "adds unstable command line options to rustc interface (default: no)"),
1358     use_ctors_section: Option<bool> = (None, parse_opt_bool, [TRACKED],
1359         "use legacy .ctors section for initializers rather than .init_array"),
1360     validate_mir: bool = (false, parse_bool, [UNTRACKED],
1361         "validate MIR after each transformation"),
1362     verbose: bool = (false, parse_bool, [UNTRACKED],
1363         "in general, enable more debug printouts (default: no)"),
1364     verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1365         "verify LLVM IR (default: no)"),
1366     wasi_exec_model: Option<WasiExecModel> = (None, parse_wasi_exec_model, [TRACKED],
1367         "whether to build a wasi command or reactor"),
1368
1369     // This list is in alphabetical order.
1370     //
1371     // If you add a new option, please update:
1372     // - compiler/rustc_interface/src/tests.rs
1373 }
1374
1375 #[derive(Clone, Hash, PartialEq, Eq, Debug)]
1376 pub enum WasiExecModel {
1377     Command,
1378     Reactor,
1379 }
1380
1381 #[derive(Clone, Copy, Hash)]
1382 pub enum LdImpl {
1383     Lld,
1384 }