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