• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::config::*;
2 
3 use crate::search_paths::SearchPath;
4 use crate::utils::NativeLib;
5 use crate::{lint, EarlyErrorHandler};
6 use rustc_data_structures::profiling::TimePassesFormat;
7 use rustc_errors::ColorConfig;
8 use rustc_errors::{LanguageIdentifier, TerminalUrl};
9 use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, SanitizerSet};
10 use rustc_target::spec::{
11     RelocModel, RelroLevel, SplitDebuginfo, StackProtector, TargetTriple, TlsModel,
12 };
13 
14 use rustc_feature::UnstableFeatures;
15 use rustc_span::edition::Edition;
16 use rustc_span::RealFileName;
17 use rustc_span::SourceFileHashAlgorithm;
18 
19 use std::collections::BTreeMap;
20 
21 use std::collections::hash_map::DefaultHasher;
22 use std::hash::Hasher;
23 use std::num::NonZeroUsize;
24 use std::path::PathBuf;
25 use std::str;
26 
27 macro_rules! insert {
28     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => {
29         if $sub_hashes
30             .insert(stringify!($opt_name), $opt_expr as &dyn dep_tracking::DepTrackingHash)
31             .is_some()
32         {
33             panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
34         }
35     };
36 }
37 
38 macro_rules! hash_opt {
39     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [UNTRACKED]) => {{}};
40     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [TRACKED]) => {{ insert!($opt_name, $opt_expr, $sub_hashes) }};
41     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $for_crate_hash: ident, [TRACKED_NO_CRATE_HASH]) => {{
42         if !$for_crate_hash {
43             insert!($opt_name, $opt_expr, $sub_hashes)
44         }
45     }};
46     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [SUBSTRUCT]) => {{}};
47 }
48 
49 macro_rules! hash_substruct {
50     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [UNTRACKED]) => {{}};
51     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED]) => {{}};
52     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED_NO_CRATE_HASH]) => {{}};
53     ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [SUBSTRUCT]) => {
54         use crate::config::dep_tracking::DepTrackingHash;
55         $opt_expr.dep_tracking_hash($for_crate_hash, $error_format).hash(
56             $hasher,
57             $error_format,
58             $for_crate_hash,
59         );
60     };
61 }
62 
63 macro_rules! top_level_options {
64     ( $( #[$top_level_attr:meta] )* pub struct Options { $(
65         $( #[$attr:meta] )*
66         $opt:ident : $t:ty [$dep_tracking_marker:ident],
67     )* } ) => (
68         #[derive(Clone)]
69         $( #[$top_level_attr] )*
70         pub struct Options {
71             $(
72                 $( #[$attr] )*
73                 pub $opt: $t
74             ),*
75         }
76 
77         impl Options {
78             pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> u64 {
79                 let mut sub_hashes = BTreeMap::new();
80                 $({
81                     hash_opt!($opt,
82                                 &self.$opt,
83                                 &mut sub_hashes,
84                                 for_crate_hash,
85                                 [$dep_tracking_marker]);
86                 })*
87                 let mut hasher = DefaultHasher::new();
88                 dep_tracking::stable_hash(sub_hashes,
89                                           &mut hasher,
90                                           self.error_format,
91                                           for_crate_hash);
92                 $({
93                     hash_substruct!($opt,
94                         &self.$opt,
95                         self.error_format,
96                         for_crate_hash,
97                         &mut hasher,
98                         [$dep_tracking_marker]);
99                 })*
100                 hasher.finish()
101             }
102         }
103     );
104 }
105 
106 top_level_options!(
107     /// The top-level command-line options struct.
108     ///
109     /// For each option, one has to specify how it behaves with regard to the
110     /// dependency tracking system of incremental compilation. This is done via the
111     /// square-bracketed directive after the field type. The options are:
112     ///
113     /// - `[TRACKED]`
114     /// A change in the given field will cause the compiler to completely clear the
115     /// incremental compilation cache before proceeding.
116     ///
117     /// - `[TRACKED_NO_CRATE_HASH]`
118     /// Same as `[TRACKED]`, but will not affect the crate hash. This is useful for options that only
119     /// affect the incremental cache.
120     ///
121     /// - `[UNTRACKED]`
122     /// Incremental compilation is not influenced by this option.
123     ///
124     /// - `[SUBSTRUCT]`
125     /// Second-level sub-structs containing more options.
126     ///
127     /// If you add a new option to this struct or one of the sub-structs like
128     /// `CodegenOptions`, think about how it influences incremental compilation. If in
129     /// doubt, specify `[TRACKED]`, which is always "correct" but might lead to
130     /// unnecessary re-compilation.
131     #[rustc_lint_opt_ty]
132     pub struct Options {
133         /// The crate config requested for the session, which may be combined
134         /// with additional crate configurations during the compile process.
135         #[rustc_lint_opt_deny_field_access("use `Session::crate_types` instead of this field")]
136         crate_types: Vec<CrateType> [TRACKED],
137         optimize: OptLevel [TRACKED],
138         /// Include the `debug_assertions` flag in dependency tracking, since it
139         /// can influence whether overflow checks are done or not.
140         debug_assertions: bool [TRACKED],
141         debuginfo: DebugInfo [TRACKED],
142         lint_opts: Vec<(String, lint::Level)> [TRACKED_NO_CRATE_HASH],
143         lint_cap: Option<lint::Level> [TRACKED_NO_CRATE_HASH],
144         describe_lints: bool [UNTRACKED],
145         output_types: OutputTypes [TRACKED],
146         search_paths: Vec<SearchPath> [UNTRACKED],
147         libs: Vec<NativeLib> [TRACKED],
148         maybe_sysroot: Option<PathBuf> [UNTRACKED],
149 
150         target_triple: TargetTriple [TRACKED],
151 
152         test: bool [TRACKED],
153         error_format: ErrorOutputType [UNTRACKED],
154         diagnostic_width: Option<usize> [UNTRACKED],
155 
156         /// If `Some`, enable incremental compilation, using the given
157         /// directory to store intermediate results.
158         incremental: Option<PathBuf> [UNTRACKED],
159         assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],
160 
161         unstable_opts: UnstableOptions [SUBSTRUCT],
162         prints: Vec<PrintRequest> [UNTRACKED],
163         cg: CodegenOptions [SUBSTRUCT],
164         externs: Externs [UNTRACKED],
165         crate_name: Option<String> [TRACKED],
166         /// Indicates how the compiler should treat unstable features.
167         unstable_features: UnstableFeatures [TRACKED],
168 
169         /// Indicates whether this run of the compiler is actually rustdoc. This
170         /// is currently just a hack and will be removed eventually, so please
171         /// try to not rely on this too much.
172         actually_rustdoc: bool [TRACKED],
173         /// Whether name resolver should resolve documentation links.
174         resolve_doc_links: ResolveDocLinks [TRACKED],
175 
176         /// Control path trimming.
177         trimmed_def_paths: TrimmedDefPaths [TRACKED],
178 
179         /// Specifications of codegen units / ThinLTO which are forced as a
180         /// result of parsing command line options. These are not necessarily
181         /// what rustc was invoked with, but massaged a bit to agree with
182         /// commands like `--emit llvm-ir` which they're often incompatible with
183         /// if we otherwise use the defaults of rustc.
184         #[rustc_lint_opt_deny_field_access("use `Session::codegen_units` instead of this field")]
185         cli_forced_codegen_units: Option<usize> [UNTRACKED],
186         #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
187         cli_forced_local_thinlto_off: bool [UNTRACKED],
188 
189         /// Remap source path prefixes in all output (messages, object files, debug, etc.).
190         remap_path_prefix: Vec<(PathBuf, PathBuf)> [TRACKED_NO_CRATE_HASH],
191         /// Base directory containing the `src/` for the Rust standard library, and
192         /// potentially `rustc` as well, if we can find it. Right now it's always
193         /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
194         ///
195         /// This directory is what the virtual `/rustc/$hash` is translated back to,
196         /// if Rust was built with path remapping to `/rustc/$hash` enabled
197         /// (the `rust.remap-debuginfo` option in `config.toml`).
198         real_rust_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
199 
200         edition: Edition [TRACKED],
201 
202         /// `true` if we're emitting JSON blobs about each artifact produced
203         /// by the compiler.
204         json_artifact_notifications: bool [TRACKED],
205 
206         /// `true` if we're emitting a JSON blob containing the unused externs
207         json_unused_externs: JsonUnusedExterns [UNTRACKED],
208 
209         /// `true` if we're emitting a JSON job containing a future-incompat report for lints
210         json_future_incompat: bool [TRACKED],
211 
212         pretty: Option<PpMode> [UNTRACKED],
213 
214         /// The (potentially remapped) working directory
215         working_dir: RealFileName [TRACKED],
216         color: ColorConfig [UNTRACKED],
217     }
218 );
219 
220 /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
221 /// macro is to define an interface that can be programmatically used by the option parser
222 /// to initialize the struct without hardcoding field names all over the place.
223 ///
224 /// The goal is to invoke this macro once with the correct fields, and then this macro generates all
225 /// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
226 /// generated code to parse an option into its respective field in the struct. There are a few
227 /// hand-written parsers for parsing specific types of values in this module.
228 macro_rules! options {
229     ($struct_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr,
230      $($( #[$attr:meta] )* $opt:ident : $t:ty = (
231         $init:expr,
232         $parse:ident,
233         [$dep_tracking_marker:ident],
234         $desc:expr)
235      ),* ,) =>
236 (
237     #[derive(Clone)]
238     #[rustc_lint_opt_ty]
239     pub struct $struct_name { $( $( #[$attr] )* pub $opt: $t),* }
240 
241     impl Default for $struct_name {
242         fn default() -> $struct_name {
243             $struct_name { $($opt: $init),* }
244         }
245     }
246 
247     impl $struct_name {
248         pub fn build(
249             handler: &EarlyErrorHandler,
250             matches: &getopts::Matches,
251         ) -> $struct_name {
252             build_options(handler, matches, $stat, $prefix, $outputname)
253         }
254 
255         fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 {
256             let mut sub_hashes = BTreeMap::new();
257             $({
258                 hash_opt!($opt,
259                             &self.$opt,
260                             &mut sub_hashes,
261                             for_crate_hash,
262                             [$dep_tracking_marker]);
263             })*
264             let mut hasher = DefaultHasher::new();
265             dep_tracking::stable_hash(sub_hashes,
266                                         &mut hasher,
267                                         error_format,
268                                         for_crate_hash
269                                         );
270             hasher.finish()
271         }
272     }
273 
274     pub const $stat: OptionDescrs<$struct_name> =
275         &[ $( (stringify!($opt), $optmod::$opt, desc::$parse, $desc) ),* ];
276 
277     mod $optmod {
278     $(
279         pub(super) fn $opt(cg: &mut super::$struct_name, v: Option<&str>) -> bool {
280             super::parse::$parse(&mut redirect_field!(cg.$opt), v)
281         }
282     )*
283     }
284 
285 ) }
286 
287 impl CodegenOptions {
288     // JUSTIFICATION: defn of the suggested wrapper fn
289     #[allow(rustc::bad_opt_access)]
instrument_coverage(&self) -> InstrumentCoverage290     pub fn instrument_coverage(&self) -> InstrumentCoverage {
291         self.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
292     }
293 }
294 
295 // Sometimes different options need to build a common structure.
296 // That structure can be kept in one of the options' fields, the others become dummy.
297 macro_rules! redirect_field {
298     ($cg:ident.link_arg) => {
299         $cg.link_args
300     };
301     ($cg:ident.pre_link_arg) => {
302         $cg.pre_link_args
303     };
304     ($cg:ident.$field:ident) => {
305         $cg.$field
306     };
307 }
308 
309 type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
310 type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)];
311 
build_options<O: Default>( handler: &EarlyErrorHandler, matches: &getopts::Matches, descrs: OptionDescrs<O>, prefix: &str, outputname: &str, ) -> O312 fn build_options<O: Default>(
313     handler: &EarlyErrorHandler,
314     matches: &getopts::Matches,
315     descrs: OptionDescrs<O>,
316     prefix: &str,
317     outputname: &str,
318 ) -> O {
319     let mut op = O::default();
320     for option in matches.opt_strs(prefix) {
321         let (key, value) = match option.split_once('=') {
322             None => (option, None),
323             Some((k, v)) => (k.to_string(), Some(v)),
324         };
325 
326         let option_to_lookup = key.replace('-', "_");
327         match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
328             Some((_, setter, type_desc, _)) => {
329                 if !setter(&mut op, value) {
330                     match value {
331                         None => handler.early_error(
332                             format!(
333                                 "{0} option `{1}` requires {2} ({3} {1}=<value>)",
334                                 outputname, key, type_desc, prefix
335                             ),
336                         ),
337                         Some(value) => handler.early_error(
338                             format!(
339                                 "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
340                             ),
341                         ),
342                     }
343                 }
344             }
345             None => handler.early_error(format!("unknown {outputname} option: `{key}`")),
346         }
347     }
348     return op;
349 }
350 
351 #[allow(non_upper_case_globals)]
352 mod desc {
353     pub const parse_no_flag: &str = "no value";
354     pub const parse_bool: &str = "one of: `y`, `yes`, `on`, `true`, `n`, `no`, `off` or `false`";
355     pub const parse_opt_bool: &str = parse_bool;
356     pub const parse_string: &str = "a string";
357     pub const parse_opt_string: &str = parse_string;
358     pub const parse_string_push: &str = parse_string;
359     pub const parse_opt_langid: &str = "a language identifier";
360     pub const parse_opt_pathbuf: &str = "a path";
361     pub const parse_list: &str = "a space-separated list of strings";
362     pub const parse_list_with_polarity: &str =
363         "a comma-separated list of strings, with elements beginning with + or -";
364     pub const parse_opt_comma_list: &str = "a comma-separated list of strings";
365     pub const parse_number: &str = "a number";
366     pub const parse_opt_number: &str = parse_number;
367     pub const parse_threads: &str = parse_number;
368     pub const parse_time_passes_format: &str = "`text` (default) or `json`";
369     pub const parse_passes: &str = "a space-separated list of passes, or `all`";
370     pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
371     pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
372     pub const parse_oom_strategy: &str = "either `panic` or `abort`";
373     pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
374     pub const parse_sanitizers: &str = "comma separated list of sanitizers: `address`, `cfi`, `hwaddress`, `kcfi`, `kernel-address`, `leak`, `memory`, `memtag`, `safestack`, `shadow-call-stack`, or `thread`";
375     pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
376     pub const parse_cfguard: &str =
377         "either a boolean (`yes`, `no`, `on`, `off`, etc), `checks`, or `nochecks`";
378     pub const parse_cfprotection: &str = "`none`|`no`|`n` (default), `branch`, `return`, or `full`|`yes`|`y` (equivalent to `branch` and `return`)";
379     pub const parse_debuginfo: &str = "either an integer (0, 1, 2), `none`, `line-directives-only`, `line-tables-only`, `limited`, or `full`";
380     pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
381     pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
382     pub const parse_optimization_fuel: &str = "crate=integer";
383     pub const parse_mir_spanview: &str = "`statement` (default), `terminator`, or `block`";
384     pub const parse_dump_mono_stats: &str = "`markdown` (default) or `json`";
385     pub const parse_instrument_coverage: &str =
386         "`all` (default), `except-unused-generics`, `except-unused-functions`, or `off`";
387     pub const parse_instrument_xray: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or a comma separated list of settings: `always` or `never` (mutually exclusive), `ignore-loops`, `instruction-threshold=N`, `skip-entry`, `skip-exit`";
388     pub const parse_unpretty: &str = "`string` or `string=string`";
389     pub const parse_treat_err_as_bug: &str = "either no value or a number bigger than 0";
390     pub const parse_trait_solver: &str =
391         "one of the supported solver modes (`classic`, `next`, or `next-coherence`)";
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 = "either `none`, or a comma separated list of location details to track: `file`, `line`, or `column`";
397     pub const parse_switch_with_opt_path: &str =
398         "an optional path to the profiling data output directory";
399     pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
400     pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
401     pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
402     pub const parse_relocation_model: &str =
403         "one of supported relocation models (`rustc --print relocation-models`)";
404     pub const parse_code_model: &str = "one of supported code models (`rustc --print code-models`)";
405     pub const parse_tls_model: &str = "one of supported TLS models (`rustc --print tls-models`)";
406     pub const parse_target_feature: &str = parse_string;
407     pub const parse_terminal_url: &str =
408         "either a boolean (`yes`, `no`, `on`, `off`, etc), or `auto`";
409     pub const parse_wasi_exec_model: &str = "either `command` or `reactor`";
410     pub const parse_split_debuginfo: &str =
411         "one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)";
412     pub const parse_split_dwarf_kind: &str =
413         "one of supported split dwarf modes (`split` or `single`)";
414     pub const parse_gcc_ld: &str = "one of: no value, `lld`";
415     pub const parse_link_self_contained: &str = "one of: `y`, `yes`, `on`, `n`, `no`, `off`, or a list of enabled (`+` prefix) and disabled (`-` prefix) \
416         components: `crto`, `libc`, `unwind`, `linker`, `sanitizers`, `mingw`";
417     pub const parse_stack_protector: &str =
418         "one of (`none` (default), `basic`, `strong`, or `all`)";
419     pub const parse_branch_protection: &str =
420         "a `,` separated combination of `bti`, `b-key`, `pac-ret`, or `leaf`";
421     pub const parse_proc_macro_execution_strategy: &str =
422         "one of supported execution strategies (`same-thread`, or `cross-thread`)";
423     pub const parse_dump_solver_proof_tree: &str = "one of: `always`, `on-request`, `on-error`";
424 }
425 
426 mod parse {
427     pub(crate) use super::*;
428     use std::str::FromStr;
429 
430     /// This is for boolean options that don't take a value and start with
431     /// `no-`. This style of option is deprecated.
parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool432     pub(crate) fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool {
433         match v {
434             None => {
435                 *slot = true;
436                 true
437             }
438             Some(_) => false,
439         }
440     }
441 
442     /// Use this for any boolean option that has a static default.
parse_bool(slot: &mut bool, v: Option<&str>) -> bool443     pub(crate) fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
444         match v {
445             Some("y") | Some("yes") | Some("on") | Some("true") | None => {
446                 *slot = true;
447                 true
448             }
449             Some("n") | Some("no") | Some("off") | Some("false") => {
450                 *slot = false;
451                 true
452             }
453             _ => false,
454         }
455     }
456 
457     /// Use this for any boolean option that lacks a static default. (The
458     /// actions taken when such an option is not specified will depend on
459     /// other factors, such as other options, or target options.)
parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool460     pub(crate) fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
461         match v {
462             Some("y") | Some("yes") | Some("on") | Some("true") | None => {
463                 *slot = Some(true);
464                 true
465             }
466             Some("n") | Some("no") | Some("off") | Some("false") => {
467                 *slot = Some(false);
468                 true
469             }
470             _ => false,
471         }
472     }
473 
474     /// Use this for any string option that has a static default.
parse_string(slot: &mut String, v: Option<&str>) -> bool475     pub(crate) fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
476         match v {
477             Some(s) => {
478                 *slot = s.to_string();
479                 true
480             }
481             None => false,
482         }
483     }
484 
485     /// Use this for any string option that lacks a static default.
parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool486     pub(crate) fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
487         match v {
488             Some(s) => {
489                 *slot = Some(s.to_string());
490                 true
491             }
492             None => false,
493         }
494     }
495 
496     /// Parse an optional language identifier, e.g. `en-US` or `zh-CN`.
parse_opt_langid(slot: &mut Option<LanguageIdentifier>, v: Option<&str>) -> bool497     pub(crate) fn parse_opt_langid(slot: &mut Option<LanguageIdentifier>, v: Option<&str>) -> bool {
498         match v {
499             Some(s) => {
500                 *slot = rustc_errors::LanguageIdentifier::from_str(s).ok();
501                 true
502             }
503             None => false,
504         }
505     }
506 
parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool507     pub(crate) fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
508         match v {
509             Some(s) => {
510                 *slot = Some(PathBuf::from(s));
511                 true
512             }
513             None => false,
514         }
515     }
516 
parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool517     pub(crate) fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
518         match v {
519             Some(s) => {
520                 slot.push(s.to_string());
521                 true
522             }
523             None => false,
524         }
525     }
526 
parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool527     pub(crate) fn parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
528         match v {
529             Some(s) => {
530                 slot.extend(s.split_whitespace().map(|s| s.to_string()));
531                 true
532             }
533             None => false,
534         }
535     }
536 
parse_list_with_polarity( slot: &mut Vec<(String, bool)>, v: Option<&str>, ) -> bool537     pub(crate) fn parse_list_with_polarity(
538         slot: &mut Vec<(String, bool)>,
539         v: Option<&str>,
540     ) -> bool {
541         match v {
542             Some(s) => {
543                 for s in s.split(',') {
544                     let Some(pass_name) = s.strip_prefix(&['+', '-'][..]) else { return false };
545                     slot.push((pass_name.to_string(), &s[..1] == "+"));
546                 }
547                 true
548             }
549             None => false,
550         }
551     }
552 
parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool553     pub(crate) fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool {
554         if let Some(v) = v {
555             ld.line = false;
556             ld.file = false;
557             ld.column = false;
558             if v == "none" {
559                 return true;
560             }
561             for s in v.split(',') {
562                 match s {
563                     "file" => ld.file = true,
564                     "line" => ld.line = true,
565                     "column" => ld.column = true,
566                     _ => return false,
567                 }
568             }
569             true
570         } else {
571             false
572         }
573     }
574 
parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool575     pub(crate) fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
576         match v {
577             Some(s) => {
578                 let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
579                 v.sort_unstable();
580                 *slot = Some(v);
581                 true
582             }
583             None => false,
584         }
585     }
586 
parse_threads(slot: &mut usize, v: Option<&str>) -> bool587     pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
588         match v.and_then(|s| s.parse().ok()) {
589             Some(0) => {
590                 *slot = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
591                 true
592             }
593             Some(i) => {
594                 *slot = i;
595                 true
596             }
597             None => false,
598         }
599     }
600 
601     /// Use this for any numeric option that has a static default.
parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool602     pub(crate) fn parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool {
603         match v.and_then(|s| s.parse().ok()) {
604             Some(i) => {
605                 *slot = i;
606                 true
607             }
608             None => false,
609         }
610     }
611 
612     /// Use this for any numeric option that lacks a static default.
parse_opt_number<T: Copy + FromStr>( slot: &mut Option<T>, v: Option<&str>, ) -> bool613     pub(crate) fn parse_opt_number<T: Copy + FromStr>(
614         slot: &mut Option<T>,
615         v: Option<&str>,
616     ) -> bool {
617         match v {
618             Some(s) => {
619                 *slot = s.parse().ok();
620                 slot.is_some()
621             }
622             None => false,
623         }
624     }
625 
parse_passes(slot: &mut Passes, v: Option<&str>) -> bool626     pub(crate) fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
627         match v {
628             Some("all") => {
629                 *slot = Passes::All;
630                 true
631             }
632             v => {
633                 let mut passes = vec![];
634                 if parse_list(&mut passes, v) {
635                     slot.extend(passes);
636                     true
637                 } else {
638                     false
639                 }
640             }
641         }
642     }
643 
parse_opt_panic_strategy( slot: &mut Option<PanicStrategy>, v: Option<&str>, ) -> bool644     pub(crate) fn parse_opt_panic_strategy(
645         slot: &mut Option<PanicStrategy>,
646         v: Option<&str>,
647     ) -> bool {
648         match v {
649             Some("unwind") => *slot = Some(PanicStrategy::Unwind),
650             Some("abort") => *slot = Some(PanicStrategy::Abort),
651             _ => return false,
652         }
653         true
654     }
655 
parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool656     pub(crate) fn parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool {
657         match v {
658             Some("unwind") => *slot = PanicStrategy::Unwind,
659             Some("abort") => *slot = PanicStrategy::Abort,
660             _ => return false,
661         }
662         true
663     }
664 
parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool665     pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool {
666         match v {
667             Some("panic") => *slot = OomStrategy::Panic,
668             Some("abort") => *slot = OomStrategy::Abort,
669             _ => return false,
670         }
671         true
672     }
673 
parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool674     pub(crate) fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
675         match v {
676             Some(s) => match s.parse::<RelroLevel>() {
677                 Ok(level) => *slot = Some(level),
678                 _ => return false,
679             },
680             _ => return false,
681         }
682         true
683     }
684 
parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool685     pub(crate) fn parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool {
686         if let Some(v) = v {
687             for s in v.split(',') {
688                 *slot |= match s {
689                     "address" => SanitizerSet::ADDRESS,
690                     "cfi" => SanitizerSet::CFI,
691                     "kcfi" => SanitizerSet::KCFI,
692                     "kernel-address" => SanitizerSet::KERNELADDRESS,
693                     "leak" => SanitizerSet::LEAK,
694                     "memory" => SanitizerSet::MEMORY,
695                     "memtag" => SanitizerSet::MEMTAG,
696                     "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
697                     "thread" => SanitizerSet::THREAD,
698                     "hwaddress" => SanitizerSet::HWADDRESS,
699                     "safestack" => SanitizerSet::SAFESTACK,
700                     _ => return false,
701                 }
702             }
703             true
704         } else {
705             false
706         }
707     }
708 
parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool709     pub(crate) fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
710         match v {
711             Some("2") | None => {
712                 *slot = 2;
713                 true
714             }
715             Some("1") => {
716                 *slot = 1;
717                 true
718             }
719             Some("0") => {
720                 *slot = 0;
721                 true
722             }
723             Some(_) => false,
724         }
725     }
726 
parse_strip(slot: &mut Strip, v: Option<&str>) -> bool727     pub(crate) fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
728         match v {
729             Some("none") => *slot = Strip::None,
730             Some("debuginfo") => *slot = Strip::Debuginfo,
731             Some("symbols") => *slot = Strip::Symbols,
732             _ => return false,
733         }
734         true
735     }
736 
parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool737     pub(crate) fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
738         if v.is_some() {
739             let mut bool_arg = None;
740             if parse_opt_bool(&mut bool_arg, v) {
741                 *slot = if bool_arg.unwrap() { CFGuard::Checks } else { CFGuard::Disabled };
742                 return true;
743             }
744         }
745 
746         *slot = match v {
747             None => CFGuard::Checks,
748             Some("checks") => CFGuard::Checks,
749             Some("nochecks") => CFGuard::NoChecks,
750             Some(_) => return false,
751         };
752         true
753     }
754 
parse_cfprotection(slot: &mut CFProtection, v: Option<&str>) -> bool755     pub(crate) fn parse_cfprotection(slot: &mut CFProtection, v: Option<&str>) -> bool {
756         if v.is_some() {
757             let mut bool_arg = None;
758             if parse_opt_bool(&mut bool_arg, v) {
759                 *slot = if bool_arg.unwrap() { CFProtection::Full } else { CFProtection::None };
760                 return true;
761             }
762         }
763 
764         *slot = match v {
765             None | Some("none") => CFProtection::None,
766             Some("branch") => CFProtection::Branch,
767             Some("return") => CFProtection::Return,
768             Some("full") => CFProtection::Full,
769             Some(_) => return false,
770         };
771         true
772     }
773 
parse_debuginfo(slot: &mut DebugInfo, v: Option<&str>) -> bool774     pub(crate) fn parse_debuginfo(slot: &mut DebugInfo, v: Option<&str>) -> bool {
775         match v {
776             Some("0") | Some("none") => *slot = DebugInfo::None,
777             Some("line-directives-only") => *slot = DebugInfo::LineDirectivesOnly,
778             Some("line-tables-only") => *slot = DebugInfo::LineTablesOnly,
779             Some("1") | Some("limited") => *slot = DebugInfo::Limited,
780             Some("2") | Some("full") => *slot = DebugInfo::Full,
781             _ => return false,
782         }
783         true
784     }
785 
parse_linker_flavor(slot: &mut Option<LinkerFlavorCli>, v: Option<&str>) -> bool786     pub(crate) fn parse_linker_flavor(slot: &mut Option<LinkerFlavorCli>, v: Option<&str>) -> bool {
787         match v.and_then(LinkerFlavorCli::from_str) {
788             Some(lf) => *slot = Some(lf),
789             _ => return false,
790         }
791         true
792     }
793 
parse_optimization_fuel( slot: &mut Option<(String, u64)>, v: Option<&str>, ) -> bool794     pub(crate) fn parse_optimization_fuel(
795         slot: &mut Option<(String, u64)>,
796         v: Option<&str>,
797     ) -> bool {
798         match v {
799             None => false,
800             Some(s) => {
801                 let parts = s.split('=').collect::<Vec<_>>();
802                 if parts.len() != 2 {
803                     return false;
804                 }
805                 let crate_name = parts[0].to_string();
806                 let fuel = parts[1].parse::<u64>();
807                 if fuel.is_err() {
808                     return false;
809                 }
810                 *slot = Some((crate_name, fuel.unwrap()));
811                 true
812             }
813         }
814     }
815 
parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool816     pub(crate) fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
817         match v {
818             None => false,
819             Some(s) if s.split('=').count() <= 2 => {
820                 *slot = Some(s.to_string());
821                 true
822             }
823             _ => false,
824         }
825     }
826 
parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>) -> bool827     pub(crate) fn parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>) -> bool {
828         if v.is_some() {
829             let mut bool_arg = None;
830             if parse_opt_bool(&mut bool_arg, v) {
831                 *slot = bool_arg.unwrap().then_some(MirSpanview::Statement);
832                 return true;
833             }
834         }
835 
836         let Some(v) = v else {
837             *slot = Some(MirSpanview::Statement);
838             return true;
839         };
840 
841         *slot = Some(match v.trim_end_matches('s') {
842             "statement" | "stmt" => MirSpanview::Statement,
843             "terminator" | "term" => MirSpanview::Terminator,
844             "block" | "basicblock" => MirSpanview::Block,
845             _ => return false,
846         });
847         true
848     }
849 
parse_time_passes_format(slot: &mut TimePassesFormat, v: Option<&str>) -> bool850     pub(crate) fn parse_time_passes_format(slot: &mut TimePassesFormat, v: Option<&str>) -> bool {
851         match v {
852             None => true,
853             Some("json") => {
854                 *slot = TimePassesFormat::Json;
855                 true
856             }
857             Some("text") => {
858                 *slot = TimePassesFormat::Text;
859                 true
860             }
861             Some(_) => false,
862         }
863     }
864 
parse_dump_mono_stats(slot: &mut DumpMonoStatsFormat, v: Option<&str>) -> bool865     pub(crate) fn parse_dump_mono_stats(slot: &mut DumpMonoStatsFormat, v: Option<&str>) -> bool {
866         match v {
867             None => true,
868             Some("json") => {
869                 *slot = DumpMonoStatsFormat::Json;
870                 true
871             }
872             Some("markdown") => {
873                 *slot = DumpMonoStatsFormat::Markdown;
874                 true
875             }
876             Some(_) => false,
877         }
878     }
879 
parse_instrument_coverage( slot: &mut Option<InstrumentCoverage>, v: Option<&str>, ) -> bool880     pub(crate) fn parse_instrument_coverage(
881         slot: &mut Option<InstrumentCoverage>,
882         v: Option<&str>,
883     ) -> bool {
884         if v.is_some() {
885             let mut bool_arg = None;
886             if parse_opt_bool(&mut bool_arg, v) {
887                 *slot = bool_arg.unwrap().then_some(InstrumentCoverage::All);
888                 return true;
889             }
890         }
891 
892         let Some(v) = v else {
893             *slot = Some(InstrumentCoverage::All);
894             return true;
895         };
896 
897         *slot = Some(match v {
898             "all" => InstrumentCoverage::All,
899             "except-unused-generics" | "except_unused_generics" => {
900                 InstrumentCoverage::ExceptUnusedGenerics
901             }
902             "except-unused-functions" | "except_unused_functions" => {
903                 InstrumentCoverage::ExceptUnusedFunctions
904             }
905             "off" | "no" | "n" | "false" | "0" => InstrumentCoverage::Off,
906             _ => return false,
907         });
908         true
909     }
910 
parse_instrument_xray( slot: &mut Option<InstrumentXRay>, v: Option<&str>, ) -> bool911     pub(crate) fn parse_instrument_xray(
912         slot: &mut Option<InstrumentXRay>,
913         v: Option<&str>,
914     ) -> bool {
915         if v.is_some() {
916             let mut bool_arg = None;
917             if parse_opt_bool(&mut bool_arg, v) {
918                 *slot = if bool_arg.unwrap() { Some(InstrumentXRay::default()) } else { None };
919                 return true;
920             }
921         }
922 
923         let options = slot.get_or_insert_default();
924         let mut seen_always = false;
925         let mut seen_never = false;
926         let mut seen_ignore_loops = false;
927         let mut seen_instruction_threshold = false;
928         let mut seen_skip_entry = false;
929         let mut seen_skip_exit = false;
930         for option in v.into_iter().flat_map(|v| v.split(',')) {
931             match option {
932                 "always" if !seen_always && !seen_never => {
933                     options.always = true;
934                     options.never = false;
935                     seen_always = true;
936                 }
937                 "never" if !seen_never && !seen_always => {
938                     options.never = true;
939                     options.always = false;
940                     seen_never = true;
941                 }
942                 "ignore-loops" if !seen_ignore_loops => {
943                     options.ignore_loops = true;
944                     seen_ignore_loops = true;
945                 }
946                 option
947                     if option.starts_with("instruction-threshold")
948                         && !seen_instruction_threshold =>
949                 {
950                     let Some(("instruction-threshold", n)) = option.split_once('=') else {
951                         return false;
952                     };
953                     match n.parse() {
954                         Ok(n) => options.instruction_threshold = Some(n),
955                         Err(_) => return false,
956                     }
957                     seen_instruction_threshold = true;
958                 }
959                 "skip-entry" if !seen_skip_entry => {
960                     options.skip_entry = true;
961                     seen_skip_entry = true;
962                 }
963                 "skip-exit" if !seen_skip_exit => {
964                     options.skip_exit = true;
965                     seen_skip_exit = true;
966                 }
967                 _ => return false,
968             }
969         }
970         true
971     }
972 
parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool973     pub(crate) fn parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool {
974         match v {
975             Some(s) => {
976                 *slot = s.parse().ok();
977                 slot.is_some()
978             }
979             None => {
980                 *slot = NonZeroUsize::new(1);
981                 true
982             }
983         }
984     }
985 
parse_trait_solver(slot: &mut TraitSolver, v: Option<&str>) -> bool986     pub(crate) fn parse_trait_solver(slot: &mut TraitSolver, v: Option<&str>) -> bool {
987         match v {
988             Some("classic") => *slot = TraitSolver::Classic,
989             Some("next") => *slot = TraitSolver::Next,
990             Some("next-coherence") => *slot = TraitSolver::NextCoherence,
991             // default trait solver is subject to change..
992             Some("default") => *slot = TraitSolver::Classic,
993             _ => return false,
994         }
995         true
996     }
997 
parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool998     pub(crate) fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
999         if v.is_some() {
1000             let mut bool_arg = None;
1001             if parse_opt_bool(&mut bool_arg, v) {
1002                 *slot = if bool_arg.unwrap() { LtoCli::Yes } else { LtoCli::No };
1003                 return true;
1004             }
1005         }
1006 
1007         *slot = match v {
1008             None => LtoCli::NoParam,
1009             Some("thin") => LtoCli::Thin,
1010             Some("fat") => LtoCli::Fat,
1011             Some(_) => return false,
1012         };
1013         true
1014     }
1015 
parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool1016     pub(crate) fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1017         if v.is_some() {
1018             let mut bool_arg = None;
1019             if parse_opt_bool(&mut bool_arg, v) {
1020                 *slot = if bool_arg.unwrap() {
1021                     LinkerPluginLto::LinkerPluginAuto
1022                 } else {
1023                     LinkerPluginLto::Disabled
1024                 };
1025                 return true;
1026             }
1027         }
1028 
1029         *slot = match v {
1030             None => LinkerPluginLto::LinkerPluginAuto,
1031             Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1032         };
1033         true
1034     }
1035 
parse_switch_with_opt_path( slot: &mut SwitchWithOptPath, v: Option<&str>, ) -> bool1036     pub(crate) fn parse_switch_with_opt_path(
1037         slot: &mut SwitchWithOptPath,
1038         v: Option<&str>,
1039     ) -> bool {
1040         *slot = match v {
1041             None => SwitchWithOptPath::Enabled(None),
1042             Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
1043         };
1044         true
1045     }
1046 
parse_merge_functions( slot: &mut Option<MergeFunctions>, v: Option<&str>, ) -> bool1047     pub(crate) fn parse_merge_functions(
1048         slot: &mut Option<MergeFunctions>,
1049         v: Option<&str>,
1050     ) -> bool {
1051         match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1052             Some(mergefunc) => *slot = Some(mergefunc),
1053             _ => return false,
1054         }
1055         true
1056     }
1057 
parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool1058     pub(crate) fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
1059         match v.and_then(|s| RelocModel::from_str(s).ok()) {
1060             Some(relocation_model) => *slot = Some(relocation_model),
1061             None if v == Some("default") => *slot = None,
1062             _ => return false,
1063         }
1064         true
1065     }
1066 
parse_code_model(slot: &mut Option<CodeModel>, v: Option<&str>) -> bool1067     pub(crate) fn parse_code_model(slot: &mut Option<CodeModel>, v: Option<&str>) -> bool {
1068         match v.and_then(|s| CodeModel::from_str(s).ok()) {
1069             Some(code_model) => *slot = Some(code_model),
1070             _ => return false,
1071         }
1072         true
1073     }
1074 
parse_tls_model(slot: &mut Option<TlsModel>, v: Option<&str>) -> bool1075     pub(crate) fn parse_tls_model(slot: &mut Option<TlsModel>, v: Option<&str>) -> bool {
1076         match v.and_then(|s| TlsModel::from_str(s).ok()) {
1077             Some(tls_model) => *slot = Some(tls_model),
1078             _ => return false,
1079         }
1080         true
1081     }
1082 
parse_terminal_url(slot: &mut TerminalUrl, v: Option<&str>) -> bool1083     pub(crate) fn parse_terminal_url(slot: &mut TerminalUrl, v: Option<&str>) -> bool {
1084         *slot = match v {
1085             Some("on" | "" | "yes" | "y") | None => TerminalUrl::Yes,
1086             Some("off" | "no" | "n") => TerminalUrl::No,
1087             Some("auto") => TerminalUrl::Auto,
1088             _ => return false,
1089         };
1090         true
1091     }
1092 
parse_symbol_mangling_version( slot: &mut Option<SymbolManglingVersion>, v: Option<&str>, ) -> bool1093     pub(crate) fn parse_symbol_mangling_version(
1094         slot: &mut Option<SymbolManglingVersion>,
1095         v: Option<&str>,
1096     ) -> bool {
1097         *slot = match v {
1098             Some("legacy") => Some(SymbolManglingVersion::Legacy),
1099             Some("v0") => Some(SymbolManglingVersion::V0),
1100             _ => return false,
1101         };
1102         true
1103     }
1104 
parse_src_file_hash( slot: &mut Option<SourceFileHashAlgorithm>, v: Option<&str>, ) -> bool1105     pub(crate) fn parse_src_file_hash(
1106         slot: &mut Option<SourceFileHashAlgorithm>,
1107         v: Option<&str>,
1108     ) -> bool {
1109         match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
1110             Some(hash_kind) => *slot = Some(hash_kind),
1111             _ => return false,
1112         }
1113         true
1114     }
1115 
parse_target_feature(slot: &mut String, v: Option<&str>) -> bool1116     pub(crate) fn parse_target_feature(slot: &mut String, v: Option<&str>) -> bool {
1117         match v {
1118             Some(s) => {
1119                 if !slot.is_empty() {
1120                     slot.push(',');
1121                 }
1122                 slot.push_str(s);
1123                 true
1124             }
1125             None => false,
1126         }
1127     }
1128 
parse_link_self_contained(slot: &mut LinkSelfContained, v: Option<&str>) -> bool1129     pub(crate) fn parse_link_self_contained(slot: &mut LinkSelfContained, v: Option<&str>) -> bool {
1130         // Whenever `-C link-self-contained` is passed without a value, it's an opt-in
1131         // just like `parse_opt_bool`, the historical value of this flag.
1132         //
1133         // 1. Parse historical single bool values
1134         let s = v.unwrap_or("y");
1135         match s {
1136             "y" | "yes" | "on" => {
1137                 slot.set_all_explicitly(true);
1138                 return true;
1139             }
1140             "n" | "no" | "off" => {
1141                 slot.set_all_explicitly(false);
1142                 return true;
1143             }
1144             _ => {}
1145         }
1146 
1147         // 2. Parse a list of enabled and disabled components.
1148         for comp in s.split(",") {
1149             if slot.handle_cli_component(comp).is_err() {
1150                 return false;
1151             }
1152         }
1153 
1154         true
1155     }
1156 
parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool1157     pub(crate) fn parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool {
1158         match v {
1159             Some("command") => *slot = Some(WasiExecModel::Command),
1160             Some("reactor") => *slot = Some(WasiExecModel::Reactor),
1161             _ => return false,
1162         }
1163         true
1164     }
1165 
parse_split_debuginfo( slot: &mut Option<SplitDebuginfo>, v: Option<&str>, ) -> bool1166     pub(crate) fn parse_split_debuginfo(
1167         slot: &mut Option<SplitDebuginfo>,
1168         v: Option<&str>,
1169     ) -> bool {
1170         match v.and_then(|s| SplitDebuginfo::from_str(s).ok()) {
1171             Some(e) => *slot = Some(e),
1172             _ => return false,
1173         }
1174         true
1175     }
1176 
parse_split_dwarf_kind(slot: &mut SplitDwarfKind, v: Option<&str>) -> bool1177     pub(crate) fn parse_split_dwarf_kind(slot: &mut SplitDwarfKind, v: Option<&str>) -> bool {
1178         match v.and_then(|s| SplitDwarfKind::from_str(s).ok()) {
1179             Some(e) => *slot = e,
1180             _ => return false,
1181         }
1182         true
1183     }
1184 
parse_gcc_ld(slot: &mut Option<LdImpl>, v: Option<&str>) -> bool1185     pub(crate) fn parse_gcc_ld(slot: &mut Option<LdImpl>, v: Option<&str>) -> bool {
1186         match v {
1187             None => *slot = None,
1188             Some("lld") => *slot = Some(LdImpl::Lld),
1189             _ => return false,
1190         }
1191         true
1192     }
1193 
parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool1194     pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1195         match v.and_then(|s| StackProtector::from_str(s).ok()) {
1196             Some(ssp) => *slot = ssp,
1197             _ => return false,
1198         }
1199         true
1200     }
1201 
parse_branch_protection( slot: &mut Option<BranchProtection>, v: Option<&str>, ) -> bool1202     pub(crate) fn parse_branch_protection(
1203         slot: &mut Option<BranchProtection>,
1204         v: Option<&str>,
1205     ) -> bool {
1206         match v {
1207             Some(s) => {
1208                 let slot = slot.get_or_insert_default();
1209                 for opt in s.split(',') {
1210                     match opt {
1211                         "bti" => slot.bti = true,
1212                         "pac-ret" if slot.pac_ret.is_none() => {
1213                             slot.pac_ret = Some(PacRet { leaf: false, key: PAuthKey::A })
1214                         }
1215                         "leaf" => match slot.pac_ret.as_mut() {
1216                             Some(pac) => pac.leaf = true,
1217                             _ => return false,
1218                         },
1219                         "b-key" => match slot.pac_ret.as_mut() {
1220                             Some(pac) => pac.key = PAuthKey::B,
1221                             _ => return false,
1222                         },
1223                         _ => return false,
1224                     };
1225                 }
1226             }
1227             _ => return false,
1228         }
1229         true
1230     }
1231 
parse_proc_macro_execution_strategy( slot: &mut ProcMacroExecutionStrategy, v: Option<&str>, ) -> bool1232     pub(crate) fn parse_proc_macro_execution_strategy(
1233         slot: &mut ProcMacroExecutionStrategy,
1234         v: Option<&str>,
1235     ) -> bool {
1236         *slot = match v {
1237             Some("same-thread") => ProcMacroExecutionStrategy::SameThread,
1238             Some("cross-thread") => ProcMacroExecutionStrategy::CrossThread,
1239             _ => return false,
1240         };
1241         true
1242     }
1243 
parse_dump_solver_proof_tree( slot: &mut DumpSolverProofTree, v: Option<&str>, ) -> bool1244     pub(crate) fn parse_dump_solver_proof_tree(
1245         slot: &mut DumpSolverProofTree,
1246         v: Option<&str>,
1247     ) -> bool {
1248         match v {
1249             None | Some("always") => *slot = DumpSolverProofTree::Always,
1250             Some("never") => *slot = DumpSolverProofTree::Never,
1251             Some("on-error") => *slot = DumpSolverProofTree::OnError,
1252             _ => return false,
1253         };
1254         true
1255     }
1256 }
1257 
1258 options! {
1259     CodegenOptions, CG_OPTIONS, cgopts, "C", "codegen",
1260 
1261     // If you add a new option, please update:
1262     // - compiler/rustc_interface/src/tests.rs
1263     // - src/doc/rustc/src/codegen-options/index.md
1264 
1265     // tidy-alphabetical-start
1266     ar: String = (String::new(), parse_string, [UNTRACKED],
1267         "this option is deprecated and does nothing"),
1268     #[rustc_lint_opt_deny_field_access("use `Session::code_model` instead of this field")]
1269     code_model: Option<CodeModel> = (None, parse_code_model, [TRACKED],
1270         "choose the code model to use (`rustc --print code-models` for details)"),
1271     codegen_units: Option<usize> = (None, parse_opt_number, [UNTRACKED],
1272         "divide crate into N units to optimize in parallel"),
1273     control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [TRACKED],
1274         "use Windows Control Flow Guard (default: no)"),
1275     debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1276         "explicitly enable the `cfg(debug_assertions)` directive"),
1277     debuginfo: DebugInfo = (DebugInfo::None, parse_debuginfo, [TRACKED],
1278         "debug info emission level (0-2, none, line-directives-only, \
1279         line-tables-only, limited, or full; default: 0)"),
1280     default_linker_libraries: bool = (false, parse_bool, [UNTRACKED],
1281         "allow the linker to link its default libraries (default: no)"),
1282     dlltool: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1283         "import library generation tool (ignored except when targeting windows-gnu)"),
1284     embed_bitcode: bool = (true, parse_bool, [TRACKED],
1285         "emit bitcode in rlibs (default: yes)"),
1286     extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1287         "extra data to put in each output filename"),
1288     force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1289         "force use of the frame pointers"),
1290     #[rustc_lint_opt_deny_field_access("use `Session::must_emit_unwind_tables` instead of this field")]
1291     force_unwind_tables: Option<bool> = (None, parse_opt_bool, [TRACKED],
1292         "force use of unwind tables"),
1293     incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1294         "enable incremental compilation"),
1295     inline_threshold: Option<u32> = (None, parse_opt_number, [TRACKED],
1296         "set the threshold for inlining a function"),
1297     #[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
1298     instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
1299         "instrument the generated code to support LLVM source-based code coverage \
1300         reports (note, the compiler build config must include `profiler = true`); \
1301         implies `-C symbol-mangling-version=v0`. Optional values are:
1302         `=all` (implicit value)
1303         `=except-unused-generics`
1304         `=except-unused-functions`
1305         `=off` (default)"),
1306     link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
1307         "a single extra argument to append to the linker invocation (can be used several times)"),
1308     link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
1309         "extra arguments to append to the linker invocation (space separated)"),
1310     #[rustc_lint_opt_deny_field_access("use `Session::link_dead_code` instead of this field")]
1311     link_dead_code: Option<bool> = (None, parse_opt_bool, [TRACKED],
1312         "keep dead code at link time (useful for code coverage) (default: no)"),
1313     link_self_contained: LinkSelfContained = (LinkSelfContained::default(), parse_link_self_contained, [UNTRACKED],
1314         "control whether to link Rust provided C objects/libraries or rely
1315         on a C toolchain or linker installed in the system"),
1316     linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1317         "system linker to link outputs with"),
1318     linker_flavor: Option<LinkerFlavorCli> = (None, parse_linker_flavor, [UNTRACKED],
1319         "linker flavor"),
1320     linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1321         parse_linker_plugin_lto, [TRACKED],
1322         "generate build artifacts that are compatible with linker-based LTO"),
1323     llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1324         "a list of arguments to pass to LLVM (space separated)"),
1325     #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
1326     lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1327         "perform LLVM link-time optimizations"),
1328     metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1329         "metadata to mangle symbol names with"),
1330     no_prepopulate_passes: bool = (false, parse_no_flag, [TRACKED],
1331         "give an empty list of passes to the pass manager"),
1332     no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1333         "disable the use of the redzone"),
1334     no_stack_check: bool = (false, parse_no_flag, [UNTRACKED],
1335         "this option is deprecated and does nothing"),
1336     no_vectorize_loops: bool = (false, parse_no_flag, [TRACKED],
1337         "disable loop vectorization optimization passes"),
1338     no_vectorize_slp: bool = (false, parse_no_flag, [TRACKED],
1339         "disable LLVM's SLP vectorization pass"),
1340     opt_level: String = ("0".to_string(), parse_string, [TRACKED],
1341         "optimization level (0-3, s, or z; default: 0)"),
1342     #[rustc_lint_opt_deny_field_access("use `Session::overflow_checks` instead of this field")]
1343     overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1344         "use overflow checks for integer arithmetic"),
1345     #[rustc_lint_opt_deny_field_access("use `Session::panic_strategy` instead of this field")]
1346     panic: Option<PanicStrategy> = (None, parse_opt_panic_strategy, [TRACKED],
1347         "panic strategy to compile crate with"),
1348     passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1349         "a list of extra LLVM passes to run (space separated)"),
1350     prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1351         "prefer dynamic linking to static linking (default: no)"),
1352     profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1353         parse_switch_with_opt_path, [TRACKED],
1354         "compile the program with profiling instrumentation"),
1355     profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1356         "use the given `.profdata` file for profile-guided optimization"),
1357     #[rustc_lint_opt_deny_field_access("use `Session::relocation_model` instead of this field")]
1358     relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
1359         "control generation of position-independent code (PIC) \
1360         (`rustc --print relocation-models` for details)"),
1361     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1362         "choose which RELRO level to use"),
1363     remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1364         "output remarks for these optimization passes (space separated, or \"all\")"),
1365     rpath: bool = (false, parse_bool, [UNTRACKED],
1366         "set rpath values in libs/exes (default: no)"),
1367     save_temps: bool = (false, parse_bool, [UNTRACKED],
1368         "save all temporary output files during compilation (default: no)"),
1369     soft_float: bool = (false, parse_bool, [TRACKED],
1370         "use soft float ABI (*eabihf targets only) (default: no)"),
1371     #[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
1372     split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
1373         "how to handle split-debuginfo, a platform-specific option"),
1374     strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
1375         "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
1376     symbol_mangling_version: Option<SymbolManglingVersion> = (None,
1377         parse_symbol_mangling_version, [TRACKED],
1378         "which mangling version to use for symbol names ('legacy' (default) or 'v0')"),
1379     target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1380         "select target processor (`rustc --print target-cpus` for details)"),
1381     target_feature: String = (String::new(), parse_target_feature, [TRACKED],
1382         "target specific attributes. (`rustc --print target-features` for details). \
1383         This feature is unsafe."),
1384     // tidy-alphabetical-end
1385 
1386     // If you add a new option, please update:
1387     // - compiler/rustc_interface/src/tests.rs
1388     // - src/doc/rustc/src/codegen-options/index.md
1389 }
1390 
1391 options! {
1392     UnstableOptions, Z_OPTIONS, dbopts, "Z", "unstable",
1393 
1394     // If you add a new option, please update:
1395     // - compiler/rustc_interface/src/tests.rs
1396     // - src/doc/unstable-book/src/compiler-flags
1397 
1398     // tidy-alphabetical-start
1399     allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1400         "only allow the listed language features to be enabled in code (comma separated)"),
1401     always_encode_mir: bool = (false, parse_bool, [TRACKED],
1402         "encode MIR of all functions into the crate metadata (default: no)"),
1403     asm_comments: bool = (false, parse_bool, [TRACKED],
1404         "generate comments into the assembly (may change behavior) (default: no)"),
1405     assert_incr_state: Option<String> = (None, parse_opt_string, [UNTRACKED],
1406         "assert that the incremental cache is in given state: \
1407          either `loaded` or `not-loaded`."),
1408     assume_incomplete_release: bool = (false, parse_bool, [TRACKED],
1409         "make cfg(version) treat the current version as incomplete (default: no)"),
1410     #[rustc_lint_opt_deny_field_access("use `Session::binary_dep_depinfo` instead of this field")]
1411     binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
1412         "include artifacts (sysroot, crate dependencies) used during compilation in dep-info \
1413         (default: no)"),
1414     box_noalias: bool = (true, parse_bool, [TRACKED],
1415         "emit noalias metadata for box (default: yes)"),
1416     branch_protection: Option<BranchProtection> = (None, parse_branch_protection, [TRACKED],
1417         "set options for branch target identification and pointer authentication on AArch64"),
1418     cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED],
1419         "instrument control-flow architecture protection"),
1420     codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1421         "the backend to use"),
1422     combine_cgu: bool = (false, parse_bool, [TRACKED],
1423         "combine CGUs into a single one"),
1424     crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1425         "inject the given attribute in the crate"),
1426     debug_info_for_profiling: bool = (false, parse_bool, [TRACKED],
1427         "emit discriminators and other data necessary for AutoFDO"),
1428     debug_macros: bool = (false, parse_bool, [TRACKED],
1429         "emit line numbers debug info inside macros (default: no)"),
1430     deduplicate_diagnostics: bool = (true, parse_bool, [UNTRACKED],
1431         "deduplicate identical diagnostics (default: yes)"),
1432     dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1433         "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1434         themselves (default: no)"),
1435     dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1436         "print tasks that execute and the color their dep node gets (requires debug build) \
1437         (default: no)"),
1438     diagnostic_width: Option<usize> = (None, parse_opt_number, [UNTRACKED],
1439         "set the current output width for diagnostic truncation"),
1440     dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1441         "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) \
1442         (default: no)"),
1443     drop_tracking: bool = (false, parse_bool, [TRACKED],
1444         "enables drop tracking in generators (default: no)"),
1445     drop_tracking_mir: bool = (false, parse_bool, [TRACKED],
1446         "enables drop tracking on MIR in generators (default: no)"),
1447     dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1448         "load proc macros for both target and host, but only link to the target (default: no)"),
1449     dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1450         "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) \
1451         (default: no)"),
1452     dump_drop_tracking_cfg: Option<String> = (None, parse_opt_string, [UNTRACKED],
1453         "dump drop-tracking control-flow graph as a `.dot` file (default: no)"),
1454     dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1455         "dump MIR state to file.
1456         `val` is used to select which passes and functions to dump. For example:
1457         `all` matches all passes and functions,
1458         `foo` matches all passes for functions whose name contains 'foo',
1459         `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1460         `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1461     dump_mir_dataflow: bool = (false, parse_bool, [UNTRACKED],
1462         "in addition to `.mir` files, create graphviz `.dot` files with dataflow results \
1463         (default: no)"),
1464     dump_mir_dir: String = ("mir_dump".to_string(), parse_string, [UNTRACKED],
1465         "the directory the MIR is dumped into (default: `mir_dump`)"),
1466     dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1467         "exclude the pass number when dumping MIR (used in tests) (default: no)"),
1468     dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1469         "in addition to `.mir` files, create graphviz `.dot` files (and with \
1470         `-Z instrument-coverage`, also create a `.dot` file for the MIR-derived \
1471         coverage graph) (default: no)"),
1472     dump_mir_spanview: Option<MirSpanview> = (None, parse_mir_spanview, [UNTRACKED],
1473         "in addition to `.mir` files, create `.html` files to view spans for \
1474         all `statement`s (including terminators), only `terminator` spans, or \
1475         computed `block` spans (one span encompassing a block's terminator and \
1476         all statements). If `-Z instrument-coverage` is also enabled, create \
1477         an additional `.html` file showing the computed coverage spans."),
1478     dump_mono_stats: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1479         parse_switch_with_opt_path, [UNTRACKED],
1480         "output statistics about monomorphization collection"),
1481     dump_mono_stats_format: DumpMonoStatsFormat = (DumpMonoStatsFormat::Markdown, parse_dump_mono_stats, [UNTRACKED],
1482         "the format to use for -Z dump-mono-stats (`markdown` (default) or `json`)"),
1483     dump_solver_proof_tree: DumpSolverProofTree = (DumpSolverProofTree::Never, parse_dump_solver_proof_tree, [UNTRACKED],
1484         "dump a proof tree for every goal evaluated by the new trait solver. If the flag is specified without any options after it
1485         then it defaults to `always`. If the flag is not specified at all it defaults to `on-request`."),
1486     dump_solver_proof_tree_use_cache: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1487         "determines whether dumped proof trees use the global cache"),
1488     dwarf_version: Option<u32> = (None, parse_opt_number, [TRACKED],
1489         "version of DWARF debug information to emit (default: 2 or 4, depending on platform)"),
1490     dylib_lto: bool = (false, parse_bool, [UNTRACKED],
1491         "enables LTO for dylib crate type"),
1492     emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1493         "emit a section containing stack size metadata (default: no)"),
1494     emit_thin_lto: bool = (true, parse_bool, [TRACKED],
1495         "emit the bc module with thin LTO info (default: yes)"),
1496     export_executable_symbols: bool = (false, parse_bool, [TRACKED],
1497         "export symbols from executables, as if they were dynamic libraries"),
1498     extra_const_ub_checks: bool = (false, parse_bool, [TRACKED],
1499         "turns on more checks to detect const UB, which can be slow (default: no)"),
1500     #[rustc_lint_opt_deny_field_access("use `Session::fewer_names` instead of this field")]
1501     fewer_names: Option<bool> = (None, parse_opt_bool, [TRACKED],
1502         "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \
1503         (default: no)"),
1504     flatten_format_args: bool = (true, parse_bool, [TRACKED],
1505         "flatten nested format_args!() and literals into a simplified format_args!() call \
1506         (default: yes)"),
1507     force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1508         "force all crates to be `rustc_private` unstable (default: no)"),
1509     fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1510         "set the optimization fuel quota for a crate"),
1511     function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
1512         "whether each function should go in its own section"),
1513     future_incompat_test: bool = (false, parse_bool, [UNTRACKED],
1514         "forces all lints to be future incompatible, used for internal testing (default: no)"),
1515     gcc_ld: Option<LdImpl> = (None, parse_gcc_ld, [TRACKED], "implementation of ld used by cc"),
1516     graphviz_dark_mode: bool = (false, parse_bool, [UNTRACKED],
1517         "use dark-themed colors in graphviz output (default: no)"),
1518     graphviz_font: String = ("Courier, monospace".to_string(), parse_string, [UNTRACKED],
1519         "use the given `fontname` in graphviz output; can be overridden by setting \
1520         environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`)"),
1521     hir_stats: bool = (false, parse_bool, [UNTRACKED],
1522         "print some statistics about AST and HIR (default: no)"),
1523     human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1524         "generate human-readable, predictable names for codegen units (default: no)"),
1525     identify_regions: bool = (false, parse_bool, [UNTRACKED],
1526         "display unnamed regions as `'<id>`, using a non-ident unique id (default: no)"),
1527     incremental_ignore_spans: bool = (false, parse_bool, [TRACKED],
1528         "ignore spans during ICH computation -- used for testing (default: no)"),
1529     incremental_info: bool = (false, parse_bool, [UNTRACKED],
1530         "print high-level information about incremental reuse (or the lack thereof) \
1531         (default: no)"),
1532     #[rustc_lint_opt_deny_field_access("use `Session::incremental_relative_spans` instead of this field")]
1533     incremental_relative_spans: bool = (false, parse_bool, [TRACKED],
1534         "hash spans relative to their parent item for incr. comp. (default: no)"),
1535     incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1536         "verify incr. comp. hashes of green query instances (default: no)"),
1537     inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1538         "control whether `#[inline]` functions are in all CGUs"),
1539     inline_llvm: bool = (true, parse_bool, [TRACKED],
1540         "enable LLVM inlining (default: yes)"),
1541     inline_mir: Option<bool> = (None, parse_opt_bool, [TRACKED],
1542         "enable MIR inlining (default: no)"),
1543     inline_mir_hint_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1544         "inlining threshold for functions with inline hint (default: 100)"),
1545     inline_mir_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1546         "a default MIR inlining threshold (default: 50)"),
1547     input_stats: bool = (false, parse_bool, [UNTRACKED],
1548         "gather statistics about the input (default: no)"),
1549     #[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
1550     instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
1551         "instrument the generated code to support LLVM source-based code coverage \
1552         reports (note, the compiler build config must include `profiler = true`); \
1553         implies `-C symbol-mangling-version=v0`. Optional values are:
1554         `=all` (implicit value)
1555         `=except-unused-generics`
1556         `=except-unused-functions`
1557         `=off` (default)"),
1558     instrument_mcount: bool = (false, parse_bool, [TRACKED],
1559         "insert function instrument code for mcount-based tracing (default: no)"),
1560     instrument_xray: Option<InstrumentXRay> = (None, parse_instrument_xray, [TRACKED],
1561         "insert function instrument code for XRay-based tracing (default: no)
1562          Optional extra settings:
1563          `=always`
1564          `=never`
1565          `=ignore-loops`
1566          `=instruction-threshold=N`
1567          `=skip-entry`
1568          `=skip-exit`
1569          Multiple options can be combined with commas."),
1570     keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1571         "keep hygiene data after analysis (default: no)"),
1572     layout_seed: Option<u64> = (None, parse_opt_number, [TRACKED],
1573         "seed layout randomization"),
1574     link_directives: bool = (true, parse_bool, [TRACKED],
1575         "honor #[link] directives in the compiled crate (default: yes)"),
1576     link_native_libraries: bool = (true, parse_bool, [UNTRACKED],
1577         "link native libraries in the linker invocation (default: yes)"),
1578     link_only: bool = (false, parse_bool, [TRACKED],
1579         "link the `.rlink` file generated by `-Z no-link` (default: no)"),
1580     llvm_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1581         "a list LLVM plugins to enable (space separated)"),
1582     llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
1583         "generate JSON tracing data file from LLVM data (default: no)"),
1584     location_detail: LocationDetail = (LocationDetail::all(), parse_location_detail, [TRACKED],
1585         "what location details should be tracked when using caller_location, either \
1586         `none`, or a comma separated list of location details, for which \
1587         valid options are `file`, `line`, and `column` (default: `file,line,column`)"),
1588     lower_impl_trait_in_trait_to_assoc_ty: bool = (false, parse_bool, [TRACKED],
1589         "modify the lowering strategy for `impl Trait` in traits so that they are lowered to \
1590         generic associated types"),
1591     ls: bool = (false, parse_bool, [UNTRACKED],
1592         "list the symbols defined by a library crate (default: no)"),
1593     macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1594         "show macro backtraces (default: no)"),
1595     maximal_hir_to_mir_coverage: bool = (false, parse_bool, [TRACKED],
1596         "save as much information as possible about the correspondence between MIR and HIR \
1597         as source scopes (default: no)"),
1598     merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1599         "control the operation of the MergeFunctions LLVM pass, taking \
1600         the same values as the target option of the same name"),
1601     meta_stats: bool = (false, parse_bool, [UNTRACKED],
1602         "gather metadata statistics (default: no)"),
1603     mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1604         "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
1605         (default: no)"),
1606     mir_enable_passes: Vec<(String, bool)> = (Vec::new(), parse_list_with_polarity, [TRACKED],
1607         "use like `-Zmir-enable-passes=+DestinationPropagation,-InstSimplify`. Forces the specified passes to be \
1608         enabled, overriding all other checks. Passes that are not specified are enabled or \
1609         disabled by other flags as usual."),
1610     mir_include_spans: bool = (false, parse_bool, [UNTRACKED],
1611         "use line numbers relative to the function in mir pretty printing"),
1612     mir_keep_place_mention: bool = (false, parse_bool, [TRACKED],
1613         "keep place mention MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
1614         (default: no)"),
1615     #[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
1616     mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
1617         "MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),
1618     move_size_limit: Option<usize> = (None, parse_opt_number, [TRACKED],
1619         "the size at which the `large_assignments` lint starts to be emitted"),
1620     mutable_noalias: bool = (true, parse_bool, [TRACKED],
1621         "emit noalias metadata for mutable references (default: yes)"),
1622     nll_facts: bool = (false, parse_bool, [UNTRACKED],
1623         "dump facts from NLL analysis into side files (default: no)"),
1624     nll_facts_dir: String = ("nll-facts".to_string(), parse_string, [UNTRACKED],
1625         "the directory the NLL facts are dumped into (default: `nll-facts`)"),
1626     no_analysis: bool = (false, parse_no_flag, [UNTRACKED],
1627         "parse and expand the source, but run no analysis"),
1628     no_codegen: bool = (false, parse_no_flag, [TRACKED_NO_CRATE_HASH],
1629         "run all passes except codegen; no output"),
1630     no_generate_arange_section: bool = (false, parse_no_flag, [TRACKED],
1631         "omit DWARF address ranges that give faster lookups"),
1632     no_jump_tables: bool = (false, parse_no_flag, [TRACKED],
1633         "disable the jump tables and lookup tables that can be generated from a switch case lowering"),
1634     no_leak_check: bool = (false, parse_no_flag, [UNTRACKED],
1635         "disable the 'leak check' for subtyping; unsound, but useful for tests"),
1636     no_link: bool = (false, parse_no_flag, [TRACKED],
1637         "compile without linking"),
1638     no_parallel_llvm: bool = (false, parse_no_flag, [UNTRACKED],
1639         "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"),
1640     no_profiler_runtime: bool = (false, parse_no_flag, [TRACKED],
1641         "prevent automatic injection of the profiler_builtins crate"),
1642     no_unique_section_names: bool = (false, parse_bool, [TRACKED],
1643         "do not use unique names for text and data sections when -Z function-sections is used"),
1644     normalize_docs: bool = (false, parse_bool, [TRACKED],
1645         "normalize associated items in rustdoc when generating documentation"),
1646     oom: OomStrategy = (OomStrategy::Abort, parse_oom_strategy, [TRACKED],
1647         "panic strategy for out-of-memory handling"),
1648     osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1649         "pass `-install_name @rpath/...` to the macOS linker (default: no)"),
1650     packed_bundled_libs: bool = (false, parse_bool, [TRACKED],
1651         "change rlib format to store native libraries as archives"),
1652     panic_abort_tests: bool = (false, parse_bool, [TRACKED],
1653         "support compiling tests with panic=abort (default: no)"),
1654     panic_in_drop: PanicStrategy = (PanicStrategy::Unwind, parse_panic_strategy, [TRACKED],
1655         "panic strategy for panics in drops"),
1656     parse_only: bool = (false, parse_bool, [UNTRACKED],
1657         "parse only; do not compile, assemble, or link (default: no)"),
1658     perf_stats: bool = (false, parse_bool, [UNTRACKED],
1659         "print some performance-related statistics (default: no)"),
1660     plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1661         "whether to use the PLT when calling into shared libraries;
1662         only has effect for PIC code on systems with ELF binaries
1663         (default: PLT is disabled if full relro is enabled on x86_64)"),
1664     polonius: bool = (false, parse_bool, [TRACKED],
1665         "enable polonius-based borrow-checker (default: no)"),
1666     polymorphize: bool = (false, parse_bool, [TRACKED],
1667           "perform polymorphization analysis"),
1668     pre_link_arg: (/* redirected to pre_link_args */) = ((), parse_string_push, [UNTRACKED],
1669         "a single extra argument to prepend the linker invocation (can be used several times)"),
1670     pre_link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
1671         "extra arguments to prepend to the linker invocation (space separated)"),
1672     precise_enum_drop_elaboration: bool = (true, parse_bool, [TRACKED],
1673         "use a more precise version of drop elaboration for matches on enums (default: yes). \
1674         This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
1675         See #77382 and #74551."),
1676     print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1677         "make rustc print the total optimization fuel used by a crate"),
1678     print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1679         "print the LLVM optimization passes being run (default: no)"),
1680     print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1681         "print the result of the monomorphization collection pass"),
1682     print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1683         "print layout information for each type encountered (default: no)"),
1684     print_vtable_sizes: bool = (false, parse_bool, [UNTRACKED],
1685         "print size comparison between old and new vtable layouts (default: no)"),
1686     proc_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1687          "show backtraces for panics during proc-macro execution (default: no)"),
1688     proc_macro_execution_strategy: ProcMacroExecutionStrategy = (ProcMacroExecutionStrategy::SameThread,
1689         parse_proc_macro_execution_strategy, [UNTRACKED],
1690         "how to run proc-macro code (default: same-thread)"),
1691     profile: bool = (false, parse_bool, [TRACKED],
1692         "insert profiling code (default: no)"),
1693     profile_closures: bool = (false, parse_no_flag, [UNTRACKED],
1694         "profile size of closures"),
1695     profile_emit: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1696         "file path to emit profiling data at runtime when using 'profile' \
1697         (default based on relative source path)"),
1698     profile_sample_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1699         "use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO)"),
1700     profiler_runtime: String = (String::from("profiler_builtins"), parse_string, [TRACKED],
1701         "name of the profiler runtime crate to automatically inject (default: `profiler_builtins`)"),
1702     query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1703         "enable queries of the dependency graph for regression testing (default: no)"),
1704     randomize_layout: bool = (false, parse_bool, [TRACKED],
1705         "randomize the layout of types (default: no)"),
1706     relax_elf_relocations: Option<bool> = (None, parse_opt_bool, [TRACKED],
1707         "whether ELF relocations can be relaxed"),
1708     remap_cwd_prefix: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1709         "remap paths under the current working directory to this path prefix"),
1710     remark_dir: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1711         "directory into which to write optimization remarks (if not specified, they will be \
1712 written to standard error output)"),
1713     report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1714         "immediately print bugs registered with `delay_span_bug` (default: no)"),
1715     sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1716         "use a sanitizer"),
1717     sanitizer_cfi_canonical_jump_tables: Option<bool> = (Some(true), parse_opt_bool, [TRACKED],
1718         "enable canonical jump tables (default: yes)"),
1719     sanitizer_cfi_generalize_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1720         "enable generalizing pointer types (default: no)"),
1721     sanitizer_cfi_normalize_integers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1722         "enable normalizing integer types (default: no)"),
1723     sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED],
1724         "enable origins tracking in MemorySanitizer"),
1725     sanitizer_recover: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1726         "enable recovery for selected sanitizers"),
1727     saturating_float_casts: Option<bool> = (None, parse_opt_bool, [TRACKED],
1728         "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1729         the max/min integer respectively, and NaN is mapped to 0 (default: yes)"),
1730     self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1731         parse_switch_with_opt_path, [UNTRACKED],
1732         "run the self profiler and output the raw event data"),
1733     self_profile_counter: String = ("wall-time".to_string(), parse_string, [UNTRACKED],
1734         "counter used by the self profiler (default: `wall-time`), one of:
1735         `wall-time` (monotonic clock, i.e. `std::time::Instant`)
1736         `instructions:u` (retired instructions, userspace-only)
1737         `instructions-minus-irqs:u` (subtracting hardware interrupt counts for extra accuracy)"
1738     ),
1739     /// keep this in sync with the event filter names in librustc_data_structures/profiling.rs
1740     self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1741         "specify the events recorded by the self profiler;
1742         for example: `-Z self-profile-events=default,query-keys`
1743         all options: none, all, default, generic-activity, query-provider, query-cache-hit
1744                      query-blocked, incr-cache-load, incr-result-hashing, query-keys, function-args, args, llvm, artifact-sizes"),
1745     share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1746         "make the current crate share its generic instantiations"),
1747     show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1748         "show spans for compiler debugging (expr|pat|ty)"),
1749     simulate_remapped_rust_src_base: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1750         "simulate the effect of remap-debuginfo = true at bootstrapping by remapping path \
1751         to rust's source base directory. only meant for testing purposes"),
1752     span_debug: bool = (false, parse_bool, [UNTRACKED],
1753         "forward proc_macro::Span's `Debug` impl to `Span`"),
1754     /// o/w tests have closure@path
1755     span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1756         "exclude spans when debug-printing compiler state (default: no)"),
1757     split_dwarf_inlining: bool = (false, parse_bool, [TRACKED],
1758         "provide minimal debug info in the object/executable to facilitate online \
1759          symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF"),
1760     split_dwarf_kind: SplitDwarfKind = (SplitDwarfKind::Split, parse_split_dwarf_kind, [TRACKED],
1761         "split dwarf variant (only if -Csplit-debuginfo is enabled and on relevant platform)
1762         (default: `split`)
1763 
1764         `split`: sections which do not require relocation are written into a DWARF object (`.dwo`)
1765                  file which is ignored by the linker
1766         `single`: sections which do not require relocation are written into object file but ignored
1767                   by the linker"),
1768     split_lto_unit: Option<bool> = (None, parse_opt_bool, [TRACKED],
1769         "enable LTO unit splitting (default: no)"),
1770     src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
1771         "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
1772     #[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
1773     stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
1774         "control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
1775     staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
1776         "allow staticlibs to have rust dylib dependencies"),
1777     staticlib_prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1778         "prefer dynamic linking to static linking for staticlibs (default: no)"),
1779     strict_init_checks: bool = (false, parse_bool, [TRACKED],
1780         "control if mem::uninitialized and mem::zeroed panic on more UB"),
1781     strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
1782         "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
1783     symbol_mangling_version: Option<SymbolManglingVersion> = (None,
1784         parse_symbol_mangling_version, [TRACKED],
1785         "which mangling version to use for symbol names ('legacy' (default) or 'v0')"),
1786     #[rustc_lint_opt_deny_field_access("use `Session::teach` instead of this field")]
1787     teach: bool = (false, parse_bool, [TRACKED],
1788         "show extended diagnostic help (default: no)"),
1789     temps_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1790         "the directory the intermediate files are written to"),
1791     terminal_urls: TerminalUrl = (TerminalUrl::No, parse_terminal_url, [UNTRACKED],
1792         "use the OSC 8 hyperlink terminal specification to print hyperlinks in the compiler output"),
1793     #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
1794     thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1795         "enable ThinLTO when possible"),
1796     thir_unsafeck: bool = (false, parse_bool, [TRACKED],
1797         "use the THIR unsafety checker (default: no)"),
1798     /// We default to 1 here since we want to behave like
1799     /// a sequential compiler for now. This'll likely be adjusted
1800     /// in the future. Note that -Zthreads=0 is the way to get
1801     /// the num_cpus behavior.
1802     #[rustc_lint_opt_deny_field_access("use `Session::threads` instead of this field")]
1803     threads: usize = (1, parse_threads, [UNTRACKED],
1804         "use a thread pool with N threads"),
1805     time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1806         "measure time of each LLVM pass (default: no)"),
1807     time_passes: bool = (false, parse_bool, [UNTRACKED],
1808         "measure time of each rustc pass (default: no)"),
1809     time_passes_format: TimePassesFormat = (TimePassesFormat::Text, parse_time_passes_format, [UNTRACKED],
1810         "the format to use for -Z time-passes (`text` (default) or `json`)"),
1811     tiny_const_eval_limit: bool = (false, parse_bool, [TRACKED],
1812         "sets a tiny, non-configurable limit for const eval; useful for compiler tests"),
1813     #[rustc_lint_opt_deny_field_access("use `Session::tls_model` instead of this field")]
1814     tls_model: Option<TlsModel> = (None, parse_tls_model, [TRACKED],
1815         "choose the TLS model to use (`rustc --print tls-models` for details)"),
1816     trace_macros: bool = (false, parse_bool, [UNTRACKED],
1817         "for every macro invocation, print its name and arguments (default: no)"),
1818     track_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1819         "tracks where in rustc a diagnostic was emitted"),
1820     trait_solver: TraitSolver = (TraitSolver::Classic, parse_trait_solver, [TRACKED],
1821         "specify the trait solver mode used by rustc (default: classic)"),
1822     // Diagnostics are considered side-effects of a query (see `QuerySideEffects`) and are saved
1823     // alongside query results and changes to translation options can affect diagnostics - so
1824     // translation options should be tracked.
1825     translate_additional_ftl: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1826         "additional fluent translation to preferentially use (for testing translation)"),
1827     translate_directionality_markers: bool = (false, parse_bool, [TRACKED],
1828         "emit directionality isolation markers in translated diagnostics"),
1829     translate_lang: Option<LanguageIdentifier> = (None, parse_opt_langid, [TRACKED],
1830         "language identifier for diagnostic output"),
1831     translate_remapped_path_to_local_path: bool = (true, parse_bool, [TRACKED],
1832         "translate remapped paths into local paths when possible (default: yes)"),
1833     trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED],
1834         "generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"),
1835     treat_err_as_bug: Option<NonZeroUsize> = (None, parse_treat_err_as_bug, [TRACKED],
1836         "treat error number `val` that occurs as bug"),
1837     trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED],
1838         "in diagnostics, use heuristics to shorten paths referring to items"),
1839     tune_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1840         "select processor to schedule for (`rustc --print target-cpus` for details)"),
1841     ui_testing: bool = (false, parse_bool, [UNTRACKED],
1842         "emit compiler diagnostics in a form suitable for UI testing (default: no)"),
1843     uninit_const_chunk_threshold: usize = (16, parse_number, [TRACKED],
1844         "allow generating const initializers with mixed init/uninit chunks, \
1845         and set the maximum number of chunks for which this is allowed (default: 16)"),
1846     unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1847         "take the brakes off const evaluation. NOTE: this is unsound (default: no)"),
1848     unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1849         "present the input source, unstable (and less-pretty) variants;
1850         `normal`, `identified`,
1851         `expanded`, `expanded,identified`,
1852         `expanded,hygiene` (with internal representations),
1853         `ast-tree` (raw AST before expansion),
1854         `ast-tree,expanded` (raw AST after expansion),
1855         `hir` (the HIR), `hir,identified`,
1856         `hir,typed` (HIR with types for each node),
1857         `hir-tree` (dump the raw HIR),
1858         `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1859     unsound_mir_opts: bool = (false, parse_bool, [TRACKED],
1860         "enable unsound and buggy MIR optimizations (default: no)"),
1861     /// This name is kind of confusing: Most unstable options enable something themselves, while
1862     /// this just allows "normal" options to be feature-gated.
1863     #[rustc_lint_opt_deny_field_access("use `Session::unstable_options` instead of this field")]
1864     unstable_options: bool = (false, parse_bool, [UNTRACKED],
1865         "adds unstable command line options to rustc interface (default: no)"),
1866     use_ctors_section: Option<bool> = (None, parse_opt_bool, [TRACKED],
1867         "use legacy .ctors section for initializers rather than .init_array"),
1868     validate_mir: bool = (false, parse_bool, [UNTRACKED],
1869         "validate MIR after each transformation"),
1870     #[rustc_lint_opt_deny_field_access("use `Session::verbose` instead of this field")]
1871     verbose: bool = (false, parse_bool, [UNTRACKED],
1872         "in general, enable more debug printouts (default: no)"),
1873     #[rustc_lint_opt_deny_field_access("use `Session::verify_llvm_ir` instead of this field")]
1874     verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1875         "verify LLVM IR (default: no)"),
1876     virtual_function_elimination: bool = (false, parse_bool, [TRACKED],
1877         "enables dead virtual function elimination optimization. \
1878         Requires `-Clto[=[fat,yes]]`"),
1879     wasi_exec_model: Option<WasiExecModel> = (None, parse_wasi_exec_model, [TRACKED],
1880         "whether to build a wasi command or reactor"),
1881     // tidy-alphabetical-end
1882 
1883     // If you add a new option, please update:
1884     // - compiler/rustc_interface/src/tests.rs
1885 }
1886 
1887 #[derive(Clone, Hash, PartialEq, Eq, Debug)]
1888 pub enum WasiExecModel {
1889     Command,
1890     Reactor,
1891 }
1892 
1893 #[derive(Clone, Copy, Hash)]
1894 pub enum LdImpl {
1895     Lld,
1896 }
1897