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