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