rustc_session/
options.rs

1use std::collections::BTreeMap;
2use std::num::{IntErrorKind, NonZero};
3use std::path::PathBuf;
4use std::str;
5
6use rustc_abi::Align;
7use rustc_data_structures::fx::FxIndexMap;
8use rustc_data_structures::profiling::TimePassesFormat;
9use rustc_data_structures::stable_hasher::StableHasher;
10use rustc_errors::{ColorConfig, LanguageIdentifier, TerminalUrl};
11use rustc_feature::UnstableFeatures;
12use rustc_hashes::Hash64;
13use rustc_macros::{BlobDecodable, Encodable};
14use rustc_span::edition::Edition;
15use rustc_span::{RealFileName, RemapPathScopeComponents, SourceFileHashAlgorithm};
16use rustc_target::spec::{
17    CodeModel, FramePointer, LinkerFlavorCli, MergeFunctions, OnBrokenPipe, PanicStrategy,
18    RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, SymbolVisibility,
19    TargetTuple, TlsModel,
20};
21
22use crate::config::*;
23use crate::search_paths::SearchPath;
24use crate::utils::NativeLib;
25use crate::{EarlyDiagCtxt, Session, lint};
26
27macro_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
38macro_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
49macro_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/// Extended target modifier info.
64/// For example, when external target modifier is '-Zregparm=2':
65/// Target modifier enum value + user value ('2') from external crate
66/// is converted into description: prefix ('Z'), name ('regparm'), tech value ('Some(2)').
67pub struct ExtendedTargetModifierInfo {
68    /// Flag prefix (usually, 'C' for codegen flags or 'Z' for unstable flags)
69    pub prefix: String,
70    /// Flag name
71    pub name: String,
72    /// Flag parsed technical value
73    pub tech_value: String,
74}
75
76/// A recorded -Zopt_name=opt_value (or -Copt_name=opt_value)
77/// which alter the ABI or effectiveness of exploit mitigations.
78#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, BlobDecodable)]
79pub struct TargetModifier {
80    /// Option enum value
81    pub opt: OptionsTargetModifiers,
82    /// User-provided option value (before parsing)
83    pub value_name: String,
84}
85
86mod target_modifier_consistency_check {
87    use super::*;
88    pub(super) fn sanitizer(l: &TargetModifier, r: Option<&TargetModifier>) -> bool {
89        let mut lparsed: SanitizerSet = Default::default();
90        let lval = if l.value_name.is_empty() { None } else { Some(l.value_name.as_str()) };
91        parse::parse_sanitizers(&mut lparsed, lval);
92
93        let mut rparsed: SanitizerSet = Default::default();
94        let rval = r.filter(|v| !v.value_name.is_empty()).map(|v| v.value_name.as_str());
95        parse::parse_sanitizers(&mut rparsed, rval);
96
97        // Some sanitizers need to be target modifiers, and some do not.
98        // For now, we should mark all sanitizers as target modifiers except for these:
99        // AddressSanitizer, LeakSanitizer
100        let tmod_sanitizers = SanitizerSet::MEMORY
101            | SanitizerSet::THREAD
102            | SanitizerSet::HWADDRESS
103            | SanitizerSet::CFI
104            | SanitizerSet::MEMTAG
105            | SanitizerSet::SHADOWCALLSTACK
106            | SanitizerSet::KCFI
107            | SanitizerSet::KERNELADDRESS
108            | SanitizerSet::SAFESTACK
109            | SanitizerSet::DATAFLOW;
110
111        lparsed & tmod_sanitizers == rparsed & tmod_sanitizers
112    }
113    pub(super) fn sanitizer_cfi_normalize_integers(
114        sess: &Session,
115        l: &TargetModifier,
116        r: Option<&TargetModifier>,
117    ) -> bool {
118        // For kCFI, the helper flag -Zsanitizer-cfi-normalize-integers should also be a target modifier
119        if sess.sanitizers().contains(SanitizerSet::KCFI) {
120            if let Some(r) = r {
121                return l.extend().tech_value == r.extend().tech_value;
122            } else {
123                return false;
124            }
125        }
126        true
127    }
128}
129
130impl TargetModifier {
131    pub fn extend(&self) -> ExtendedTargetModifierInfo {
132        self.opt.reparse(&self.value_name)
133    }
134    // Custom consistency check for target modifiers (or default `l.tech_value == r.tech_value`)
135    // When other is None, consistency with default value is checked
136    pub fn consistent(&self, sess: &Session, other: Option<&TargetModifier>) -> bool {
137        assert!(other.is_none() || self.opt == other.unwrap().opt);
138        match self.opt {
139            OptionsTargetModifiers::UnstableOptions(unstable) => match unstable {
140                UnstableOptionsTargetModifiers::sanitizer => {
141                    return target_modifier_consistency_check::sanitizer(self, other);
142                }
143                UnstableOptionsTargetModifiers::sanitizer_cfi_normalize_integers => {
144                    return target_modifier_consistency_check::sanitizer_cfi_normalize_integers(
145                        sess, self, other,
146                    );
147                }
148                _ => {}
149            },
150            _ => {}
151        };
152        match other {
153            Some(other) => self.extend().tech_value == other.extend().tech_value,
154            None => false,
155        }
156    }
157}
158
159fn tmod_push_impl(
160    opt: OptionsTargetModifiers,
161    tmod_vals: &BTreeMap<OptionsTargetModifiers, String>,
162    tmods: &mut Vec<TargetModifier>,
163) {
164    if let Some(v) = tmod_vals.get(&opt) {
165        tmods.push(TargetModifier { opt, value_name: v.clone() })
166    }
167}
168
169macro_rules! tmod_push {
170    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr) => {
171        if *$opt_expr != $init {
172            tmod_push_impl(
173                OptionsTargetModifiers::$struct_name($tmod_enum_name::$opt_name),
174                $tmod_vals,
175                $mods,
176            );
177        }
178    };
179}
180
181macro_rules! gather_tmods {
182    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
183        [SUBSTRUCT], [TARGET_MODIFIER]) => {
184        compile_error!("SUBSTRUCT can't be target modifier");
185    };
186    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
187        [UNTRACKED], [TARGET_MODIFIER]) => {
188        tmod_push!($struct_name, $tmod_enum_name, $opt_name, $opt_expr, $init, $mods, $tmod_vals)
189    };
190    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
191        [TRACKED], [TARGET_MODIFIER]) => {
192        tmod_push!($struct_name, $tmod_enum_name, $opt_name, $opt_expr, $init, $mods, $tmod_vals)
193    };
194    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
195        [TRACKED_NO_CRATE_HASH], [TARGET_MODIFIER]) => {
196        tmod_push!($struct_name, $tmod_enum_name, $opt_name, $opt_expr, $init, $mods, $tmod_vals)
197    };
198    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
199        [SUBSTRUCT], []) => {
200        $opt_expr.gather_target_modifiers($mods, $tmod_vals);
201    };
202    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
203        [UNTRACKED], []) => {{}};
204    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
205        [TRACKED], []) => {{}};
206    ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $init:expr, $mods:expr, $tmod_vals:expr,
207        [TRACKED_NO_CRATE_HASH], []) => {{}};
208}
209
210macro_rules! gather_tmods_top_level {
211    ($_opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [SUBSTRUCT $substruct_enum:ident]) => {
212        $opt_expr.gather_target_modifiers($mods, $tmod_vals);
213    };
214    ($opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [$non_substruct:ident TARGET_MODIFIER]) => {
215        compile_error!("Top level option can't be target modifier");
216    };
217    ($opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [$non_substruct:ident]) => {};
218}
219
220/// Macro for generating OptionsTargetsModifiers top-level enum with impl.
221/// Will generate something like:
222/// ```rust,ignore (illustrative)
223/// pub enum OptionsTargetModifiers {
224///     CodegenOptions(CodegenOptionsTargetModifiers),
225///     UnstableOptions(UnstableOptionsTargetModifiers),
226/// }
227/// impl OptionsTargetModifiers {
228///     pub fn reparse(&self, user_value: &str) -> ExtendedTargetModifierInfo {
229///         match self {
230///             Self::CodegenOptions(v) => v.reparse(user_value),
231///             Self::UnstableOptions(v) => v.reparse(user_value),
232///         }
233///     }
234///     pub fn is_target_modifier(flag_name: &str) -> bool {
235///         CodegenOptionsTargetModifiers::is_target_modifier(flag_name) ||
236///         UnstableOptionsTargetModifiers::is_target_modifier(flag_name)
237///     }
238/// }
239/// ```
240macro_rules! top_level_tmod_enum {
241    ($( {$($optinfo:tt)*} ),* $(,)*) => {
242        top_level_tmod_enum! { @parse {}, (user_value){}; $($($optinfo)*|)* }
243    };
244    // Termination
245    (
246        @parse
247        {$($variant:tt($substruct_enum:tt))*},
248        ($user_value:ident){$($pout:tt)*};
249    ) => {
250        #[allow(non_camel_case_types)]
251        #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone, Encodable, BlobDecodable)]
252        pub enum OptionsTargetModifiers {
253            $($variant($substruct_enum)),*
254        }
255        impl OptionsTargetModifiers {
256            #[allow(unused_variables)]
257            pub fn reparse(&self, $user_value: &str) -> ExtendedTargetModifierInfo {
258                #[allow(unreachable_patterns)]
259                match self {
260                    $($pout)*
261                    _ => panic!("unknown target modifier option: {:?}", *self)
262                }
263            }
264            pub fn is_target_modifier(flag_name: &str) -> bool {
265                $($substruct_enum::is_target_modifier(flag_name))||*
266            }
267        }
268    };
269    // Adding SUBSTRUCT option group into $eout
270    (
271        @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*};
272            [SUBSTRUCT $substruct_enum:ident $variant:ident] |
273        $($tail:tt)*
274    ) => {
275        top_level_tmod_enum! {
276            @parse
277            {
278                $($eout)*
279                $variant($substruct_enum)
280            },
281            ($puser_value){
282                $($pout)*
283                Self::$variant(v) => v.reparse($puser_value),
284            };
285            $($tail)*
286        }
287    };
288    // Skipping non-target-modifier and non-substruct
289    (
290        @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*};
291            [$non_substruct:ident] |
292        $($tail:tt)*
293    ) => {
294        top_level_tmod_enum! {
295            @parse
296            {
297                $($eout)*
298            },
299            ($puser_value){
300                $($pout)*
301            };
302            $($tail)*
303        }
304    };
305}
306
307macro_rules! top_level_options {
308    ( $( #[$top_level_attr:meta] )* pub struct Options { $(
309        $( #[$attr:meta] )*
310        $opt:ident : $t:ty [$dep_tracking_marker:ident $( $tmod:ident $variant:ident )?],
311    )* } ) => (
312        top_level_tmod_enum!( {$([$dep_tracking_marker $($tmod $variant),*])|*} );
313
314        #[derive(Clone)]
315        $( #[$top_level_attr] )*
316        pub struct Options {
317            $(
318                $( #[$attr] )*
319                pub $opt: $t
320            ),*,
321            pub target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
322        }
323
324        impl Options {
325            pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> Hash64 {
326                let mut sub_hashes = BTreeMap::new();
327                $({
328                    hash_opt!($opt,
329                                &self.$opt,
330                                &mut sub_hashes,
331                                for_crate_hash,
332                                [$dep_tracking_marker]);
333                })*
334                let mut hasher = StableHasher::new();
335                dep_tracking::stable_hash(sub_hashes,
336                                          &mut hasher,
337                                          self.error_format,
338                                          for_crate_hash);
339                $({
340                    hash_substruct!($opt,
341                        &self.$opt,
342                        self.error_format,
343                        for_crate_hash,
344                        &mut hasher,
345                        [$dep_tracking_marker]);
346                })*
347                hasher.finish()
348            }
349
350            pub fn gather_target_modifiers(&self) -> Vec<TargetModifier> {
351                let mut mods = Vec::<TargetModifier>::new();
352                $({
353                    gather_tmods_top_level!($opt,
354                        &self.$opt, &mut mods, &self.target_modifiers,
355                        [$dep_tracking_marker $($tmod),*]);
356                })*
357                mods.sort_by(|a, b| a.opt.cmp(&b.opt));
358                mods
359            }
360        }
361    );
362}
363
364top_level_options!(
365    /// The top-level command-line options struct.
366    ///
367    /// For each option, one has to specify how it behaves with regard to the
368    /// dependency tracking system of incremental compilation. This is done via the
369    /// square-bracketed directive after the field type. The options are:
370    ///
371    /// - `[TRACKED]`
372    /// A change in the given field will cause the compiler to completely clear the
373    /// incremental compilation cache before proceeding.
374    ///
375    /// - `[TRACKED_NO_CRATE_HASH]`
376    /// Same as `[TRACKED]`, but will not affect the crate hash. This is useful for options that
377    /// only affect the incremental cache.
378    ///
379    /// - `[UNTRACKED]`
380    /// Incremental compilation is not influenced by this option.
381    ///
382    /// - `[SUBSTRUCT]`
383    /// Second-level sub-structs containing more options.
384    ///
385    /// If you add a new option to this struct or one of the sub-structs like
386    /// `CodegenOptions`, think about how it influences incremental compilation. If in
387    /// doubt, specify `[TRACKED]`, which is always "correct" but might lead to
388    /// unnecessary re-compilation.
389    #[rustc_lint_opt_ty]
390    pub struct Options {
391        /// The crate config requested for the session, which may be combined
392        /// with additional crate configurations during the compile process.
393        #[rustc_lint_opt_deny_field_access("use `TyCtxt::crate_types` instead of this field")]
394        crate_types: Vec<CrateType> [TRACKED],
395        optimize: OptLevel [TRACKED],
396        /// Include the `debug_assertions` flag in dependency tracking, since it
397        /// can influence whether overflow checks are done or not.
398        debug_assertions: bool [TRACKED],
399        debuginfo: DebugInfo [TRACKED],
400        lint_opts: Vec<(String, lint::Level)> [TRACKED_NO_CRATE_HASH],
401        lint_cap: Option<lint::Level> [TRACKED_NO_CRATE_HASH],
402        describe_lints: bool [UNTRACKED],
403        output_types: OutputTypes [TRACKED],
404        search_paths: Vec<SearchPath> [UNTRACKED],
405        libs: Vec<NativeLib> [TRACKED],
406        sysroot: Sysroot [UNTRACKED],
407
408        target_triple: TargetTuple [TRACKED],
409
410        /// Effective logical environment used by `env!`/`option_env!` macros
411        logical_env: FxIndexMap<String, String> [TRACKED],
412
413        test: bool [TRACKED],
414        error_format: ErrorOutputType [UNTRACKED],
415        diagnostic_width: Option<usize> [UNTRACKED],
416
417        /// If `Some`, enable incremental compilation, using the given
418        /// directory to store intermediate results.
419        incremental: Option<PathBuf> [UNTRACKED],
420        assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],
421        /// Set by the `Config::hash_untracked_state` callback for custom
422        /// drivers to invalidate the incremental cache
423        #[rustc_lint_opt_deny_field_access("should only be used via `Config::hash_untracked_state`")]
424        untracked_state_hash: Hash64 [TRACKED_NO_CRATE_HASH],
425
426        unstable_opts: UnstableOptions [SUBSTRUCT UnstableOptionsTargetModifiers UnstableOptions],
427        prints: Vec<PrintRequest> [UNTRACKED],
428        cg: CodegenOptions [SUBSTRUCT CodegenOptionsTargetModifiers CodegenOptions],
429        externs: Externs [UNTRACKED],
430        crate_name: Option<String> [TRACKED],
431        /// Indicates how the compiler should treat unstable features.
432        unstable_features: UnstableFeatures [TRACKED],
433
434        /// Indicates whether this run of the compiler is actually rustdoc. This
435        /// is currently just a hack and will be removed eventually, so please
436        /// try to not rely on this too much.
437        actually_rustdoc: bool [TRACKED],
438        /// Whether name resolver should resolve documentation links.
439        resolve_doc_links: ResolveDocLinks [TRACKED],
440
441        /// Control path trimming.
442        trimmed_def_paths: bool [TRACKED],
443
444        /// Specifications of codegen units / ThinLTO which are forced as a
445        /// result of parsing command line options. These are not necessarily
446        /// what rustc was invoked with, but massaged a bit to agree with
447        /// commands like `--emit llvm-ir` which they're often incompatible with
448        /// if we otherwise use the defaults of rustc.
449        #[rustc_lint_opt_deny_field_access("use `Session::codegen_units` instead of this field")]
450        cli_forced_codegen_units: Option<usize> [UNTRACKED],
451        #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
452        cli_forced_local_thinlto_off: bool [UNTRACKED],
453
454        /// Remap source path prefixes in all output (messages, object files, debug, etc.).
455        remap_path_prefix: Vec<(PathBuf, PathBuf)> [TRACKED_NO_CRATE_HASH],
456
457        /// Base directory containing the `library/` directory for the Rust standard library.
458        /// Right now it's always `$sysroot/lib/rustlib/src/rust`
459        /// (i.e. the `rustup` `rust-src` component).
460        ///
461        /// This directory is what the virtual `/rustc/$hash` is translated back to,
462        /// if Rust was built with path remapping to `/rustc/$hash` enabled
463        /// (the `rust.remap-debuginfo` option in `bootstrap.toml`).
464        real_rust_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
465
466        /// Base directory containing the `compiler/` directory for the rustc sources.
467        /// Right now it's always `$sysroot/lib/rustlib/rustc-src/rust`
468        /// (i.e. the `rustup` `rustc-dev` component).
469        ///
470        /// This directory is what the virtual `/rustc-dev/$hash` is translated back to,
471        /// if Rust was built with path remapping to `/rustc/$hash` enabled
472        /// (the `rust.remap-debuginfo` option in `bootstrap.toml`).
473        real_rustc_dev_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
474
475        edition: Edition [TRACKED],
476
477        /// `true` if we're emitting JSON blobs about each artifact produced
478        /// by the compiler.
479        json_artifact_notifications: bool [TRACKED],
480
481        /// `true` if we're emitting JSON timings with the start and end of
482        /// high-level compilation sections
483        json_timings: bool [UNTRACKED],
484
485        /// `true` if we're emitting a JSON blob containing the unused externs
486        json_unused_externs: JsonUnusedExterns [UNTRACKED],
487
488        /// `true` if we're emitting a JSON job containing a future-incompat report for lints
489        json_future_incompat: bool [TRACKED],
490
491        pretty: Option<PpMode> [UNTRACKED],
492
493        /// The (potentially remapped) working directory
494        #[rustc_lint_opt_deny_field_access("use `SourceMap::working_dir` instead of this field")]
495        working_dir: RealFileName [TRACKED],
496
497        color: ColorConfig [UNTRACKED],
498
499        verbose: bool [TRACKED_NO_CRATE_HASH],
500    }
501);
502
503macro_rules! tmod_enum_opt {
504    ($struct_name:ident, $tmod_enum_name:ident, $opt:ident, $v:ident) => {
505        Some(OptionsTargetModifiers::$struct_name($tmod_enum_name::$opt))
506    };
507    ($struct_name:ident, $tmod_enum_name:ident, $opt:ident, ) => {
508        None
509    };
510}
511
512macro_rules! tmod_enum {
513    ($tmod_enum_name:ident, $prefix:expr, $( {$($optinfo:tt)*} ),* $(,)*) => {
514        tmod_enum! { $tmod_enum_name, $prefix, @parse {}, (user_value){}; $($($optinfo)*|)* }
515    };
516    // Termination
517    (
518        $tmod_enum_name:ident, $prefix:expr,
519        @parse
520        {$($eout:tt)*},
521        ($user_value:ident){$($pout:tt)*};
522    ) => {
523        #[allow(non_camel_case_types)]
524        #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone, Encodable, BlobDecodable)]
525        pub enum $tmod_enum_name {
526            $($eout),*
527        }
528        impl $tmod_enum_name {
529            #[allow(unused_variables)]
530            pub fn reparse(&self, $user_value: &str) -> ExtendedTargetModifierInfo {
531                #[allow(unreachable_patterns)]
532                match self {
533                    $($pout)*
534                    _ => panic!("unknown target modifier option: {:?}", *self)
535                }
536            }
537            pub fn is_target_modifier(flag_name: &str) -> bool {
538                match flag_name.replace('-', "_").as_str() {
539                    $(stringify!($eout) => true,)*
540                    _ => false,
541                }
542            }
543        }
544    };
545    // Adding target-modifier option into $eout
546    (
547        $tmod_enum_name:ident, $prefix:expr,
548        @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*};
549            $opt:ident, $parse:ident, $t:ty, [TARGET_MODIFIER] |
550        $($tail:tt)*
551    ) => {
552        tmod_enum! {
553            $tmod_enum_name, $prefix,
554            @parse
555            {
556                $($eout)*
557                $opt
558            },
559            ($puser_value){
560                $($pout)*
561                Self::$opt => {
562                    let mut parsed : $t = Default::default();
563                    let val = if $puser_value.is_empty() { None } else { Some($puser_value) };
564                    parse::$parse(&mut parsed, val);
565                    ExtendedTargetModifierInfo {
566                        prefix: $prefix.to_string(),
567                        name: stringify!($opt).to_string().replace('_', "-"),
568                        tech_value: format!("{:?}", parsed),
569                    }
570                },
571            };
572            $($tail)*
573        }
574    };
575    // Skipping non-target-modifier
576    (
577        $tmod_enum_name:ident, $prefix:expr,
578        @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*};
579            $opt:ident, $parse:ident, $t:ty, [] |
580        $($tail:tt)*
581    ) => {
582        tmod_enum! {
583            $tmod_enum_name, $prefix,
584            @parse
585            {
586                $($eout)*
587            },
588            ($puser_value){
589                $($pout)*
590            };
591            $($tail)*
592        }
593    };
594}
595
596/// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
597/// macro is to define an interface that can be programmatically used by the option parser
598/// to initialize the struct without hardcoding field names all over the place.
599///
600/// The goal is to invoke this macro once with the correct fields, and then this macro generates all
601/// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
602/// generated code to parse an option into its respective field in the struct. There are a few
603/// hand-written parsers for parsing specific types of values in this module.
604macro_rules! options {
605    ($struct_name:ident, $tmod_enum_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr,
606     $($( #[$attr:meta] )* $opt:ident : $t:ty = (
607        $init:expr,
608        $parse:ident,
609        [$dep_tracking_marker:ident $( $tmod:ident )?],
610        $desc:expr
611        $(, deprecated_do_nothing: $dnn:literal )?)
612     ),* ,) =>
613(
614    #[derive(Clone)]
615    #[rustc_lint_opt_ty]
616    pub struct $struct_name { $( $( #[$attr] )* pub $opt: $t),* }
617
618    tmod_enum!( $tmod_enum_name, $prefix, {$($opt, $parse, $t, [$($tmod),*])|*} );
619
620    impl Default for $struct_name {
621        fn default() -> $struct_name {
622            $struct_name { $($opt: $init),* }
623        }
624    }
625
626    impl $struct_name {
627        pub fn build(
628            early_dcx: &EarlyDiagCtxt,
629            matches: &getopts::Matches,
630            target_modifiers: &mut BTreeMap<OptionsTargetModifiers, String>,
631        ) -> $struct_name {
632            build_options(early_dcx, matches, target_modifiers, $stat, $prefix, $outputname)
633        }
634
635        fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> Hash64 {
636            let mut sub_hashes = BTreeMap::new();
637            $({
638                hash_opt!($opt,
639                            &self.$opt,
640                            &mut sub_hashes,
641                            for_crate_hash,
642                            [$dep_tracking_marker]);
643            })*
644            let mut hasher = StableHasher::new();
645            dep_tracking::stable_hash(sub_hashes,
646                                        &mut hasher,
647                                        error_format,
648                                        for_crate_hash
649                                        );
650            hasher.finish()
651        }
652
653        pub fn gather_target_modifiers(
654            &self,
655            _mods: &mut Vec<TargetModifier>,
656            _tmod_vals: &BTreeMap<OptionsTargetModifiers, String>,
657        ) {
658            $({
659                gather_tmods!($struct_name, $tmod_enum_name, $opt, &self.$opt, $init, _mods, _tmod_vals,
660                    [$dep_tracking_marker], [$($tmod),*]);
661            })*
662        }
663    }
664
665    pub const $stat: OptionDescrs<$struct_name> =
666        &[ $( OptionDesc{ name: stringify!($opt), setter: $optmod::$opt,
667            type_desc: desc::$parse, desc: $desc, is_deprecated_and_do_nothing: false $( || $dnn )?,
668            tmod: tmod_enum_opt!($struct_name, $tmod_enum_name, $opt, $($tmod),*) } ),* ];
669
670    mod $optmod {
671    $(
672        pub(super) fn $opt(cg: &mut super::$struct_name, v: Option<&str>) -> bool {
673            super::parse::$parse(&mut redirect_field!(cg.$opt), v)
674        }
675    )*
676    }
677
678) }
679
680impl CodegenOptions {
681    // JUSTIFICATION: defn of the suggested wrapper fn
682    #[allow(rustc::bad_opt_access)]
683    pub fn instrument_coverage(&self) -> InstrumentCoverage {
684        self.instrument_coverage
685    }
686}
687
688// Sometimes different options need to build a common structure.
689// That structure can be kept in one of the options' fields, the others become dummy.
690macro_rules! redirect_field {
691    ($cg:ident.link_arg) => {
692        $cg.link_args
693    };
694    ($cg:ident.pre_link_arg) => {
695        $cg.pre_link_args
696    };
697    ($cg:ident.$field:ident) => {
698        $cg.$field
699    };
700}
701
702type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
703type OptionDescrs<O> = &'static [OptionDesc<O>];
704
705pub struct OptionDesc<O> {
706    name: &'static str,
707    setter: OptionSetter<O>,
708    // description for return value/type from mod desc
709    type_desc: &'static str,
710    // description for option from options table
711    desc: &'static str,
712    is_deprecated_and_do_nothing: bool,
713    tmod: Option<OptionsTargetModifiers>,
714}
715
716impl<O> OptionDesc<O> {
717    pub fn name(&self) -> &'static str {
718        self.name
719    }
720
721    pub fn desc(&self) -> &'static str {
722        self.desc
723    }
724}
725
726#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
727fn build_options<O: Default>(
728    early_dcx: &EarlyDiagCtxt,
729    matches: &getopts::Matches,
730    target_modifiers: &mut BTreeMap<OptionsTargetModifiers, String>,
731    descrs: OptionDescrs<O>,
732    prefix: &str,
733    outputname: &str,
734) -> O {
735    let mut op = O::default();
736    for option in matches.opt_strs(prefix) {
737        let (key, value) = match option.split_once('=') {
738            None => (option, None),
739            Some((k, v)) => (k.to_string(), Some(v)),
740        };
741
742        let option_to_lookup = key.replace('-', "_");
743        match descrs.iter().find(|opt_desc| opt_desc.name == option_to_lookup) {
744            Some(OptionDesc {
745                name: _,
746                setter,
747                type_desc,
748                desc,
749                is_deprecated_and_do_nothing,
750                tmod,
751            }) => {
752                if *is_deprecated_and_do_nothing {
753                    // deprecation works for prefixed options only
754                    assert!(!prefix.is_empty());
755                    early_dcx.early_warn(format!("`-{prefix} {key}`: {desc}"));
756                }
757                if !setter(&mut op, value) {
758                    match value {
759                        None => early_dcx.early_fatal(
760                            format!(
761                                "{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)"
762                            ),
763                        ),
764                        Some(value) => early_dcx.early_fatal(
765                            format!(
766                                "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
767                            ),
768                        ),
769                    }
770                }
771                if let Some(tmod) = *tmod {
772                    let v = value.map_or(String::new(), ToOwned::to_owned);
773                    target_modifiers.insert(tmod, v);
774                }
775            }
776            None => early_dcx.early_fatal(format!("unknown {outputname} option: `{key}`")),
777        }
778    }
779    op
780}
781
782#[allow(non_upper_case_globals)]
783mod desc {
784    pub(crate) const parse_no_value: &str = "no value";
785    pub(crate) const parse_bool: &str =
786        "one of: `y`, `yes`, `on`, `true`, `n`, `no`, `off` or `false`";
787    pub(crate) const parse_opt_bool: &str = parse_bool;
788    pub(crate) const parse_string: &str = "a string";
789    pub(crate) const parse_opt_string: &str = parse_string;
790    pub(crate) const parse_string_push: &str = parse_string;
791    pub(crate) const parse_opt_langid: &str = "a language identifier";
792    pub(crate) const parse_opt_pathbuf: &str = "a path";
793    pub(crate) const parse_list: &str = "a space-separated list of strings";
794    pub(crate) const parse_list_with_polarity: &str =
795        "a comma-separated list of strings, with elements beginning with + or -";
796    pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintTAFn`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `PrintPasses`, `NoPostopt`, `LooseTypes`, `Inline`, `NoTT`";
797    pub(crate) const parse_offload: &str =
798        "a comma separated list of settings: `Host=<Absolute-Path>`, `Device`, `Test`";
799    pub(crate) const parse_comma_list: &str = "a comma-separated list of strings";
800    pub(crate) const parse_opt_comma_list: &str = parse_comma_list;
801    pub(crate) const parse_number: &str = "a number";
802    pub(crate) const parse_opt_number: &str = parse_number;
803    pub(crate) const parse_frame_pointer: &str = "one of `true`/`yes`/`on`, `false`/`no`/`off`, or (with -Zunstable-options) `non-leaf` or `always`";
804    pub(crate) const parse_threads: &str = parse_number;
805    pub(crate) const parse_time_passes_format: &str = "`text` (default) or `json`";
806    pub(crate) const parse_passes: &str = "a space-separated list of passes, or `all`";
807    pub(crate) const parse_panic_strategy: &str = "either `unwind`, `abort`, or `immediate-abort`";
808    pub(crate) const parse_on_broken_pipe: &str = "either `kill`, `error`, or `inherit`";
809    pub(crate) const parse_patchable_function_entry: &str = "either two comma separated integers (total_nops,prefix_nops), with prefix_nops <= total_nops, or one integer (total_nops)";
810    pub(crate) const parse_opt_panic_strategy: &str = parse_panic_strategy;
811    pub(crate) const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
812    pub(crate) const parse_sanitizers: &str = "comma separated list of sanitizers: `address`, `cfi`, `dataflow`, `hwaddress`, `kcfi`, `kernel-address`, `leak`, `memory`, `memtag`, `safestack`, `shadow-call-stack`, `thread`, or 'realtime'";
813    pub(crate) const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
814    pub(crate) const parse_cfguard: &str =
815        "either a boolean (`yes`, `no`, `on`, `off`, etc), `checks`, or `nochecks`";
816    pub(crate) const parse_cfprotection: &str = "`none`|`no`|`n` (default), `branch`, `return`, or `full`|`yes`|`y` (equivalent to `branch` and `return`)";
817    pub(crate) const parse_debuginfo: &str = "either an integer (0, 1, 2), `none`, `line-directives-only`, `line-tables-only`, `limited`, or `full`";
818    pub(crate) const parse_debuginfo_compression: &str = "one of `none`, `zlib`, or `zstd`";
819    pub(crate) const parse_mir_strip_debuginfo: &str =
820        "one of `none`, `locals-in-tiny-functions`, or `all-locals`";
821    pub(crate) const parse_collapse_macro_debuginfo: &str = "one of `no`, `external`, or `yes`";
822    pub(crate) const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
823    pub(crate) const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
824    pub(crate) const parse_dump_mono_stats: &str = "`markdown` (default) or `json`";
825    pub(crate) const parse_instrument_coverage: &str = parse_bool;
826    pub(crate) const parse_coverage_options: &str = "`block` | `branch` | `condition`";
827    pub(crate) 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`";
828    pub(crate) const parse_unpretty: &str = "`string` or `string=string`";
829    pub(crate) const parse_treat_err_as_bug: &str = "either no value or a non-negative number";
830    pub(crate) const parse_next_solver_config: &str =
831        "either `globally` (when used without an argument), `coherence` (default) or `no`";
832    pub(crate) const parse_lto: &str =
833        "either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
834    pub(crate) const parse_linker_plugin_lto: &str =
835        "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
836    pub(crate) const parse_location_detail: &str = "either `none`, or a comma separated list of location details to track: `file`, `line`, or `column`";
837    pub(crate) const parse_fmt_debug: &str = "either `full`, `shallow`, or `none`";
838    pub(crate) const parse_switch_with_opt_path: &str =
839        "an optional path to the profiling data output directory";
840    pub(crate) const parse_merge_functions: &str =
841        "one of: `disabled`, `trampolines`, or `aliases`";
842    pub(crate) const parse_symbol_mangling_version: &str =
843        "one of: `legacy`, `v0` (RFC 2603), or `hashed`";
844    pub(crate) const parse_opt_symbol_visibility: &str =
845        "one of: `hidden`, `protected`, or `interposable`";
846    pub(crate) const parse_cargo_src_file_hash: &str =
847        "one of `blake3`, `md5`, `sha1`, or `sha256`";
848    pub(crate) const parse_src_file_hash: &str = "one of `md5`, `sha1`, or `sha256`";
849    pub(crate) const parse_relocation_model: &str =
850        "one of supported relocation models (`rustc --print relocation-models`)";
851    pub(crate) const parse_code_model: &str =
852        "one of supported code models (`rustc --print code-models`)";
853    pub(crate) const parse_tls_model: &str =
854        "one of supported TLS models (`rustc --print tls-models`)";
855    pub(crate) const parse_target_feature: &str = parse_string;
856    pub(crate) const parse_terminal_url: &str =
857        "either a boolean (`yes`, `no`, `on`, `off`, etc), or `auto`";
858    pub(crate) const parse_wasi_exec_model: &str = "either `command` or `reactor`";
859    pub(crate) const parse_split_debuginfo: &str =
860        "one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)";
861    pub(crate) const parse_split_dwarf_kind: &str =
862        "one of supported split dwarf modes (`split` or `single`)";
863    pub(crate) const parse_link_self_contained: &str = "one of: `y`, `yes`, `on`, `n`, `no`, `off`, or a list of enabled (`+` prefix) and disabled (`-` prefix) \
864        components: `crto`, `libc`, `unwind`, `linker`, `sanitizers`, `mingw`";
865    pub(crate) const parse_linker_features: &str =
866        "a list of enabled (`+` prefix) and disabled (`-` prefix) features: `lld`";
867    pub(crate) const parse_polonius: &str = "either no value or `legacy` (the default), or `next`";
868    pub(crate) const parse_annotate_moves: &str =
869        "either a boolean (`yes`, `no`, `on`, `off`, etc.), or a size limit in bytes";
870    pub(crate) const parse_stack_protector: &str =
871        "one of (`none` (default), `basic`, `strong`, or `all`)";
872    pub(crate) const parse_branch_protection: &str = "a `,` separated combination of `bti`, `gcs`, `pac-ret`, (optionally with `pc`, `b-key`, `leaf` if `pac-ret` is set)";
873    pub(crate) const parse_proc_macro_execution_strategy: &str =
874        "one of supported execution strategies (`same-thread`, or `cross-thread`)";
875    pub(crate) const parse_remap_path_scope: &str = "comma separated list of scopes: `macro`, `diagnostics`, `debuginfo`, `coverage`, `object`, `all`";
876    pub(crate) const parse_inlining_threshold: &str =
877        "either a boolean (`yes`, `no`, `on`, `off`, etc), or a non-negative number";
878    pub(crate) const parse_llvm_module_flag: &str = "<key>:<type>:<value>:<behavior>. Type must currently be `u32`. Behavior should be one of (`error`, `warning`, `require`, `override`, `append`, `appendunique`, `max`, `min`)";
879    pub(crate) const parse_function_return: &str = "`keep` or `thunk-extern`";
880    pub(crate) const parse_wasm_c_abi: &str = "`spec`";
881    pub(crate) const parse_mir_include_spans: &str =
882        "either a boolean (`yes`, `no`, `on`, `off`, etc), or `nll` (default: `nll`)";
883    pub(crate) const parse_align: &str = "a number that is a power of 2 between 1 and 2^29";
884}
885
886pub mod parse {
887    use std::str::FromStr;
888
889    pub(crate) use super::*;
890    pub(crate) const MAX_THREADS_CAP: usize = 256;
891
892    /// This is for boolean options that don't take a value, and are true simply
893    /// by existing on the command-line.
894    ///
895    /// This style of option is deprecated, and is mainly used by old options
896    /// beginning with `no-`.
897    pub(crate) fn parse_no_value(slot: &mut bool, v: Option<&str>) -> bool {
898        match v {
899            None => {
900                *slot = true;
901                true
902            }
903            // Trying to specify a value is always forbidden.
904            Some(_) => false,
905        }
906    }
907
908    /// Use this for any boolean option that has a static default.
909    pub(crate) fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
910        match v {
911            Some("y") | Some("yes") | Some("on") | Some("true") | None => {
912                *slot = true;
913                true
914            }
915            Some("n") | Some("no") | Some("off") | Some("false") => {
916                *slot = false;
917                true
918            }
919            _ => false,
920        }
921    }
922
923    /// Use this for any boolean option that lacks a static default. (The
924    /// actions taken when such an option is not specified will depend on
925    /// other factors, such as other options, or target options.)
926    pub(crate) fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
927        match v {
928            Some("y") | Some("yes") | Some("on") | Some("true") | None => {
929                *slot = Some(true);
930                true
931            }
932            Some("n") | Some("no") | Some("off") | Some("false") => {
933                *slot = Some(false);
934                true
935            }
936            _ => false,
937        }
938    }
939
940    /// Parses whether polonius is enabled, and if so, which version.
941    pub(crate) fn parse_polonius(slot: &mut Polonius, v: Option<&str>) -> bool {
942        match v {
943            Some("legacy") | None => {
944                *slot = Polonius::Legacy;
945                true
946            }
947            Some("next") => {
948                *slot = Polonius::Next;
949                true
950            }
951            _ => false,
952        }
953    }
954
955    pub(crate) fn parse_annotate_moves(slot: &mut AnnotateMoves, v: Option<&str>) -> bool {
956        let mut bslot = false;
957        let mut nslot = 0u64;
958
959        *slot = match v {
960            // No value provided: -Z annotate-moves (enable with default limit)
961            None => AnnotateMoves::Enabled(None),
962            // Explicit boolean value provided: -Z annotate-moves=yes/no
963            s @ Some(_) if parse_bool(&mut bslot, s) => {
964                if bslot {
965                    AnnotateMoves::Enabled(None)
966                } else {
967                    AnnotateMoves::Disabled
968                }
969            }
970            // With numeric limit provided: -Z annotate-moves=1234
971            s @ Some(_) if parse_number(&mut nslot, s) => AnnotateMoves::Enabled(Some(nslot)),
972            _ => return false,
973        };
974
975        true
976    }
977
978    /// Use this for any string option that has a static default.
979    pub(crate) fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
980        match v {
981            Some(s) => {
982                *slot = s.to_string();
983                true
984            }
985            None => false,
986        }
987    }
988
989    /// Use this for any string option that lacks a static default.
990    pub(crate) fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
991        match v {
992            Some(s) => {
993                *slot = Some(s.to_string());
994                true
995            }
996            None => false,
997        }
998    }
999
1000    /// Parse an optional language identifier, e.g. `en-US` or `zh-CN`.
1001    pub(crate) fn parse_opt_langid(slot: &mut Option<LanguageIdentifier>, v: Option<&str>) -> bool {
1002        match v {
1003            Some(s) => {
1004                *slot = rustc_errors::LanguageIdentifier::from_str(s).ok();
1005                true
1006            }
1007            None => false,
1008        }
1009    }
1010
1011    pub(crate) fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
1012        match v {
1013            Some(s) => {
1014                *slot = Some(PathBuf::from(s));
1015                true
1016            }
1017            None => false,
1018        }
1019    }
1020
1021    pub(crate) fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
1022        match v {
1023            Some(s) => {
1024                slot.push(s.to_string());
1025                true
1026            }
1027            None => false,
1028        }
1029    }
1030
1031    pub(crate) fn parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
1032        match v {
1033            Some(s) => {
1034                slot.extend(s.split_whitespace().map(|s| s.to_string()));
1035                true
1036            }
1037            None => false,
1038        }
1039    }
1040
1041    pub(crate) fn parse_list_with_polarity(
1042        slot: &mut Vec<(String, bool)>,
1043        v: Option<&str>,
1044    ) -> bool {
1045        match v {
1046            Some(s) => {
1047                for s in s.split(',') {
1048                    let Some(pass_name) = s.strip_prefix(&['+', '-'][..]) else { return false };
1049                    slot.push((pass_name.to_string(), &s[..1] == "+"));
1050                }
1051                true
1052            }
1053            None => false,
1054        }
1055    }
1056
1057    pub(crate) fn parse_fmt_debug(opt: &mut FmtDebug, v: Option<&str>) -> bool {
1058        *opt = match v {
1059            Some("full") => FmtDebug::Full,
1060            Some("shallow") => FmtDebug::Shallow,
1061            Some("none") => FmtDebug::None,
1062            _ => return false,
1063        };
1064        true
1065    }
1066
1067    pub(crate) fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool {
1068        if let Some(v) = v {
1069            ld.line = false;
1070            ld.file = false;
1071            ld.column = false;
1072            if v == "none" {
1073                return true;
1074            }
1075            for s in v.split(',') {
1076                match s {
1077                    "file" => ld.file = true,
1078                    "line" => ld.line = true,
1079                    "column" => ld.column = true,
1080                    _ => return false,
1081                }
1082            }
1083            true
1084        } else {
1085            false
1086        }
1087    }
1088
1089    pub(crate) fn parse_comma_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
1090        match v {
1091            Some(s) => {
1092                let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
1093                v.sort_unstable();
1094                *slot = v;
1095                true
1096            }
1097            None => false,
1098        }
1099    }
1100
1101    pub(crate) fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
1102        match v {
1103            Some(s) => {
1104                let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
1105                v.sort_unstable();
1106                *slot = Some(v);
1107                true
1108            }
1109            None => false,
1110        }
1111    }
1112
1113    pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
1114        let ret = match v.and_then(|s| s.parse().ok()) {
1115            Some(0) => {
1116                *slot = std::thread::available_parallelism().map_or(1, NonZero::<usize>::get);
1117                true
1118            }
1119            Some(i) => {
1120                *slot = i;
1121                true
1122            }
1123            None => false,
1124        };
1125        // We want to cap the number of threads here to avoid large numbers like 999999 and compiler panics.
1126        // This solution was suggested here https://github.com/rust-lang/rust/issues/117638#issuecomment-1800925067
1127        *slot = slot.clone().min(MAX_THREADS_CAP);
1128        ret
1129    }
1130
1131    /// Use this for any numeric option that has a static default.
1132    pub(crate) fn parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool {
1133        match v.and_then(|s| s.parse().ok()) {
1134            Some(i) => {
1135                *slot = i;
1136                true
1137            }
1138            None => false,
1139        }
1140    }
1141
1142    /// Use this for any numeric option that lacks a static default.
1143    pub(crate) fn parse_opt_number<T: Copy + FromStr>(
1144        slot: &mut Option<T>,
1145        v: Option<&str>,
1146    ) -> bool {
1147        match v {
1148            Some(s) => {
1149                *slot = s.parse().ok();
1150                slot.is_some()
1151            }
1152            None => false,
1153        }
1154    }
1155
1156    pub(crate) fn parse_frame_pointer(slot: &mut FramePointer, v: Option<&str>) -> bool {
1157        let mut yes = false;
1158        match v {
1159            _ if parse_bool(&mut yes, v) && yes => slot.ratchet(FramePointer::Always),
1160            _ if parse_bool(&mut yes, v) => slot.ratchet(FramePointer::MayOmit),
1161            Some("always") => slot.ratchet(FramePointer::Always),
1162            Some("non-leaf") => slot.ratchet(FramePointer::NonLeaf),
1163            _ => return false,
1164        };
1165        true
1166    }
1167
1168    pub(crate) fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
1169        match v {
1170            Some("all") => {
1171                *slot = Passes::All;
1172                true
1173            }
1174            v => {
1175                let mut passes = vec![];
1176                if parse_list(&mut passes, v) {
1177                    slot.extend(passes);
1178                    true
1179                } else {
1180                    false
1181                }
1182            }
1183        }
1184    }
1185
1186    pub(crate) fn parse_opt_panic_strategy(
1187        slot: &mut Option<PanicStrategy>,
1188        v: Option<&str>,
1189    ) -> bool {
1190        match v {
1191            Some("unwind") => *slot = Some(PanicStrategy::Unwind),
1192            Some("abort") => *slot = Some(PanicStrategy::Abort),
1193            Some("immediate-abort") => *slot = Some(PanicStrategy::ImmediateAbort),
1194            _ => return false,
1195        }
1196        true
1197    }
1198
1199    pub(crate) fn parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool {
1200        match v {
1201            Some("unwind") => *slot = PanicStrategy::Unwind,
1202            Some("abort") => *slot = PanicStrategy::Abort,
1203            Some("immediate-abort") => *slot = PanicStrategy::ImmediateAbort,
1204            _ => return false,
1205        }
1206        true
1207    }
1208
1209    pub(crate) fn parse_on_broken_pipe(slot: &mut OnBrokenPipe, v: Option<&str>) -> bool {
1210        match v {
1211            // OnBrokenPipe::Default can't be explicitly specified
1212            Some("kill") => *slot = OnBrokenPipe::Kill,
1213            Some("error") => *slot = OnBrokenPipe::Error,
1214            Some("inherit") => *slot = OnBrokenPipe::Inherit,
1215            _ => return false,
1216        }
1217        true
1218    }
1219
1220    pub(crate) fn parse_patchable_function_entry(
1221        slot: &mut PatchableFunctionEntry,
1222        v: Option<&str>,
1223    ) -> bool {
1224        let mut total_nops = 0;
1225        let mut prefix_nops = 0;
1226
1227        if !parse_number(&mut total_nops, v) {
1228            let parts = v.and_then(|v| v.split_once(',')).unzip();
1229            if !parse_number(&mut total_nops, parts.0) {
1230                return false;
1231            }
1232            if !parse_number(&mut prefix_nops, parts.1) {
1233                return false;
1234            }
1235        }
1236
1237        if let Some(pfe) =
1238            PatchableFunctionEntry::from_total_and_prefix_nops(total_nops, prefix_nops)
1239        {
1240            *slot = pfe;
1241            return true;
1242        }
1243        false
1244    }
1245
1246    pub(crate) fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
1247        match v {
1248            Some(s) => match s.parse::<RelroLevel>() {
1249                Ok(level) => *slot = Some(level),
1250                _ => return false,
1251            },
1252            _ => return false,
1253        }
1254        true
1255    }
1256
1257    pub(crate) fn parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool {
1258        if let Some(v) = v {
1259            for s in v.split(',') {
1260                *slot |= match s {
1261                    "address" => SanitizerSet::ADDRESS,
1262                    "cfi" => SanitizerSet::CFI,
1263                    "dataflow" => SanitizerSet::DATAFLOW,
1264                    "kcfi" => SanitizerSet::KCFI,
1265                    "kernel-address" => SanitizerSet::KERNELADDRESS,
1266                    "leak" => SanitizerSet::LEAK,
1267                    "memory" => SanitizerSet::MEMORY,
1268                    "memtag" => SanitizerSet::MEMTAG,
1269                    "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
1270                    "thread" => SanitizerSet::THREAD,
1271                    "hwaddress" => SanitizerSet::HWADDRESS,
1272                    "safestack" => SanitizerSet::SAFESTACK,
1273                    "realtime" => SanitizerSet::REALTIME,
1274                    _ => return false,
1275                }
1276            }
1277            true
1278        } else {
1279            false
1280        }
1281    }
1282
1283    pub(crate) fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
1284        match v {
1285            Some("2") | None => {
1286                *slot = 2;
1287                true
1288            }
1289            Some("1") => {
1290                *slot = 1;
1291                true
1292            }
1293            Some("0") => {
1294                *slot = 0;
1295                true
1296            }
1297            Some(_) => false,
1298        }
1299    }
1300
1301    pub(crate) fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
1302        match v {
1303            Some("none") => *slot = Strip::None,
1304            Some("debuginfo") => *slot = Strip::Debuginfo,
1305            Some("symbols") => *slot = Strip::Symbols,
1306            _ => return false,
1307        }
1308        true
1309    }
1310
1311    pub(crate) fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
1312        if v.is_some() {
1313            let mut bool_arg = None;
1314            if parse_opt_bool(&mut bool_arg, v) {
1315                *slot = if bool_arg.unwrap() { CFGuard::Checks } else { CFGuard::Disabled };
1316                return true;
1317            }
1318        }
1319
1320        *slot = match v {
1321            None => CFGuard::Checks,
1322            Some("checks") => CFGuard::Checks,
1323            Some("nochecks") => CFGuard::NoChecks,
1324            Some(_) => return false,
1325        };
1326        true
1327    }
1328
1329    pub(crate) fn parse_cfprotection(slot: &mut CFProtection, v: Option<&str>) -> bool {
1330        if v.is_some() {
1331            let mut bool_arg = None;
1332            if parse_opt_bool(&mut bool_arg, v) {
1333                *slot = if bool_arg.unwrap() { CFProtection::Full } else { CFProtection::None };
1334                return true;
1335            }
1336        }
1337
1338        *slot = match v {
1339            None | Some("none") => CFProtection::None,
1340            Some("branch") => CFProtection::Branch,
1341            Some("return") => CFProtection::Return,
1342            Some("full") => CFProtection::Full,
1343            Some(_) => return false,
1344        };
1345        true
1346    }
1347
1348    pub(crate) fn parse_debuginfo(slot: &mut DebugInfo, v: Option<&str>) -> bool {
1349        match v {
1350            Some("0") | Some("none") => *slot = DebugInfo::None,
1351            Some("line-directives-only") => *slot = DebugInfo::LineDirectivesOnly,
1352            Some("line-tables-only") => *slot = DebugInfo::LineTablesOnly,
1353            Some("1") | Some("limited") => *slot = DebugInfo::Limited,
1354            Some("2") | Some("full") => *slot = DebugInfo::Full,
1355            _ => return false,
1356        }
1357        true
1358    }
1359
1360    pub(crate) fn parse_debuginfo_compression(
1361        slot: &mut DebugInfoCompression,
1362        v: Option<&str>,
1363    ) -> bool {
1364        match v {
1365            Some("none") => *slot = DebugInfoCompression::None,
1366            Some("zlib") => *slot = DebugInfoCompression::Zlib,
1367            Some("zstd") => *slot = DebugInfoCompression::Zstd,
1368            _ => return false,
1369        };
1370        true
1371    }
1372
1373    pub(crate) fn parse_mir_strip_debuginfo(slot: &mut MirStripDebugInfo, v: Option<&str>) -> bool {
1374        match v {
1375            Some("none") => *slot = MirStripDebugInfo::None,
1376            Some("locals-in-tiny-functions") => *slot = MirStripDebugInfo::LocalsInTinyFunctions,
1377            Some("all-locals") => *slot = MirStripDebugInfo::AllLocals,
1378            _ => return false,
1379        };
1380        true
1381    }
1382
1383    pub(crate) fn parse_linker_flavor(slot: &mut Option<LinkerFlavorCli>, v: Option<&str>) -> bool {
1384        match v.and_then(|v| LinkerFlavorCli::from_str(v).ok()) {
1385            Some(lf) => *slot = Some(lf),
1386            _ => return false,
1387        }
1388        true
1389    }
1390
1391    pub(crate) fn parse_opt_symbol_visibility(
1392        slot: &mut Option<SymbolVisibility>,
1393        v: Option<&str>,
1394    ) -> bool {
1395        if let Some(v) = v {
1396            if let Ok(vis) = SymbolVisibility::from_str(v) {
1397                *slot = Some(vis);
1398            } else {
1399                return false;
1400            }
1401        }
1402        true
1403    }
1404
1405    pub(crate) fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1406        match v {
1407            None => false,
1408            Some(s) if s.split('=').count() <= 2 => {
1409                *slot = Some(s.to_string());
1410                true
1411            }
1412            _ => false,
1413        }
1414    }
1415
1416    pub(crate) fn parse_time_passes_format(slot: &mut TimePassesFormat, v: Option<&str>) -> bool {
1417        match v {
1418            None => true,
1419            Some("json") => {
1420                *slot = TimePassesFormat::Json;
1421                true
1422            }
1423            Some("text") => {
1424                *slot = TimePassesFormat::Text;
1425                true
1426            }
1427            Some(_) => false,
1428        }
1429    }
1430
1431    pub(crate) fn parse_dump_mono_stats(slot: &mut DumpMonoStatsFormat, v: Option<&str>) -> bool {
1432        match v {
1433            None => true,
1434            Some("json") => {
1435                *slot = DumpMonoStatsFormat::Json;
1436                true
1437            }
1438            Some("markdown") => {
1439                *slot = DumpMonoStatsFormat::Markdown;
1440                true
1441            }
1442            Some(_) => false,
1443        }
1444    }
1445
1446    pub(crate) fn parse_offload(slot: &mut Vec<Offload>, v: Option<&str>) -> bool {
1447        let Some(v) = v else {
1448            *slot = vec![];
1449            return true;
1450        };
1451        let mut v: Vec<&str> = v.split(",").collect();
1452        v.sort_unstable();
1453        for &val in v.iter() {
1454            // Split each entry on '=' if it has an argument
1455            let (key, arg) = match val.split_once('=') {
1456                Some((k, a)) => (k, Some(a)),
1457                None => (val, None),
1458            };
1459
1460            let variant = match key {
1461                "Host" => {
1462                    if let Some(p) = arg {
1463                        Offload::Host(p.to_string())
1464                    } else {
1465                        return false;
1466                    }
1467                }
1468                "Device" => {
1469                    if let Some(_) = arg {
1470                        // Device does not accept a value
1471                        return false;
1472                    }
1473                    Offload::Device
1474                }
1475                "Test" => {
1476                    if let Some(_) = arg {
1477                        // Test does not accept a value
1478                        return false;
1479                    }
1480                    Offload::Test
1481                }
1482                _ => {
1483                    // FIXME(ZuseZ4): print an error saying which value is not recognized
1484                    return false;
1485                }
1486            };
1487            slot.push(variant);
1488        }
1489
1490        true
1491    }
1492
1493    pub(crate) fn parse_autodiff(slot: &mut Vec<AutoDiff>, v: Option<&str>) -> bool {
1494        let Some(v) = v else {
1495            *slot = vec![];
1496            return true;
1497        };
1498        let mut v: Vec<&str> = v.split(",").collect();
1499        v.sort_unstable();
1500        for &val in v.iter() {
1501            // Split each entry on '=' if it has an argument
1502            let (key, arg) = match val.split_once('=') {
1503                Some((k, a)) => (k, Some(a)),
1504                None => (val, None),
1505            };
1506
1507            let variant = match key {
1508                "Enable" => AutoDiff::Enable,
1509                "PrintTA" => AutoDiff::PrintTA,
1510                "PrintTAFn" => {
1511                    if let Some(fun) = arg {
1512                        AutoDiff::PrintTAFn(fun.to_string())
1513                    } else {
1514                        return false;
1515                    }
1516                }
1517                "PrintAA" => AutoDiff::PrintAA,
1518                "PrintPerf" => AutoDiff::PrintPerf,
1519                "PrintSteps" => AutoDiff::PrintSteps,
1520                "PrintModBefore" => AutoDiff::PrintModBefore,
1521                "PrintModAfter" => AutoDiff::PrintModAfter,
1522                "PrintModFinal" => AutoDiff::PrintModFinal,
1523                "NoPostopt" => AutoDiff::NoPostopt,
1524                "PrintPasses" => AutoDiff::PrintPasses,
1525                "LooseTypes" => AutoDiff::LooseTypes,
1526                "Inline" => AutoDiff::Inline,
1527                "NoTT" => AutoDiff::NoTT,
1528                _ => {
1529                    // FIXME(ZuseZ4): print an error saying which value is not recognized
1530                    return false;
1531                }
1532            };
1533            slot.push(variant);
1534        }
1535
1536        true
1537    }
1538
1539    pub(crate) fn parse_instrument_coverage(
1540        slot: &mut InstrumentCoverage,
1541        v: Option<&str>,
1542    ) -> bool {
1543        if v.is_some() {
1544            let mut bool_arg = false;
1545            if parse_bool(&mut bool_arg, v) {
1546                *slot = if bool_arg { InstrumentCoverage::Yes } else { InstrumentCoverage::No };
1547                return true;
1548            }
1549        }
1550
1551        let Some(v) = v else {
1552            *slot = InstrumentCoverage::Yes;
1553            return true;
1554        };
1555
1556        // Parse values that have historically been accepted by stable compilers,
1557        // even though they're currently just aliases for boolean values.
1558        *slot = match v {
1559            "all" => InstrumentCoverage::Yes,
1560            "0" => InstrumentCoverage::No,
1561            _ => return false,
1562        };
1563        true
1564    }
1565
1566    pub(crate) fn parse_coverage_options(slot: &mut CoverageOptions, v: Option<&str>) -> bool {
1567        let Some(v) = v else { return true };
1568
1569        for option in v.split(',') {
1570            match option {
1571                "block" => slot.level = CoverageLevel::Block,
1572                "branch" => slot.level = CoverageLevel::Branch,
1573                "condition" => slot.level = CoverageLevel::Condition,
1574                "discard-all-spans-in-codegen" => slot.discard_all_spans_in_codegen = true,
1575                _ => return false,
1576            }
1577        }
1578        true
1579    }
1580
1581    pub(crate) fn parse_instrument_xray(
1582        slot: &mut Option<InstrumentXRay>,
1583        v: Option<&str>,
1584    ) -> bool {
1585        if v.is_some() {
1586            let mut bool_arg = None;
1587            if parse_opt_bool(&mut bool_arg, v) {
1588                *slot = if bool_arg.unwrap() { Some(InstrumentXRay::default()) } else { None };
1589                return true;
1590            }
1591        }
1592
1593        let options = slot.get_or_insert_default();
1594        let mut seen_always = false;
1595        let mut seen_never = false;
1596        let mut seen_ignore_loops = false;
1597        let mut seen_instruction_threshold = false;
1598        let mut seen_skip_entry = false;
1599        let mut seen_skip_exit = false;
1600        for option in v.into_iter().flat_map(|v| v.split(',')) {
1601            match option {
1602                "always" if !seen_always && !seen_never => {
1603                    options.always = true;
1604                    options.never = false;
1605                    seen_always = true;
1606                }
1607                "never" if !seen_never && !seen_always => {
1608                    options.never = true;
1609                    options.always = false;
1610                    seen_never = true;
1611                }
1612                "ignore-loops" if !seen_ignore_loops => {
1613                    options.ignore_loops = true;
1614                    seen_ignore_loops = true;
1615                }
1616                option
1617                    if option.starts_with("instruction-threshold")
1618                        && !seen_instruction_threshold =>
1619                {
1620                    let Some(("instruction-threshold", n)) = option.split_once('=') else {
1621                        return false;
1622                    };
1623                    match n.parse() {
1624                        Ok(n) => options.instruction_threshold = Some(n),
1625                        Err(_) => return false,
1626                    }
1627                    seen_instruction_threshold = true;
1628                }
1629                "skip-entry" if !seen_skip_entry => {
1630                    options.skip_entry = true;
1631                    seen_skip_entry = true;
1632                }
1633                "skip-exit" if !seen_skip_exit => {
1634                    options.skip_exit = true;
1635                    seen_skip_exit = true;
1636                }
1637                _ => return false,
1638            }
1639        }
1640        true
1641    }
1642
1643    pub(crate) fn parse_treat_err_as_bug(
1644        slot: &mut Option<NonZero<usize>>,
1645        v: Option<&str>,
1646    ) -> bool {
1647        match v {
1648            Some(s) => match s.parse() {
1649                Ok(val) => {
1650                    *slot = Some(val);
1651                    true
1652                }
1653                Err(e) => {
1654                    *slot = None;
1655                    e.kind() == &IntErrorKind::Zero
1656                }
1657            },
1658            None => {
1659                *slot = NonZero::new(1);
1660                true
1661            }
1662        }
1663    }
1664
1665    pub(crate) fn parse_next_solver_config(slot: &mut NextSolverConfig, v: Option<&str>) -> bool {
1666        if let Some(config) = v {
1667            *slot = match config {
1668                "no" => NextSolverConfig { coherence: false, globally: false },
1669                "coherence" => NextSolverConfig { coherence: true, globally: false },
1670                "globally" => NextSolverConfig { coherence: true, globally: true },
1671                _ => return false,
1672            };
1673        } else {
1674            *slot = NextSolverConfig { coherence: true, globally: true };
1675        }
1676
1677        true
1678    }
1679
1680    pub(crate) fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1681        if v.is_some() {
1682            let mut bool_arg = None;
1683            if parse_opt_bool(&mut bool_arg, v) {
1684                *slot = if bool_arg.unwrap() { LtoCli::Yes } else { LtoCli::No };
1685                return true;
1686            }
1687        }
1688
1689        *slot = match v {
1690            None => LtoCli::NoParam,
1691            Some("thin") => LtoCli::Thin,
1692            Some("fat") => LtoCli::Fat,
1693            Some(_) => return false,
1694        };
1695        true
1696    }
1697
1698    pub(crate) fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1699        if v.is_some() {
1700            let mut bool_arg = None;
1701            if parse_opt_bool(&mut bool_arg, v) {
1702                *slot = if bool_arg.unwrap() {
1703                    LinkerPluginLto::LinkerPluginAuto
1704                } else {
1705                    LinkerPluginLto::Disabled
1706                };
1707                return true;
1708            }
1709        }
1710
1711        *slot = match v {
1712            None => LinkerPluginLto::LinkerPluginAuto,
1713            Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1714        };
1715        true
1716    }
1717
1718    pub(crate) fn parse_switch_with_opt_path(
1719        slot: &mut SwitchWithOptPath,
1720        v: Option<&str>,
1721    ) -> bool {
1722        *slot = match v {
1723            None => SwitchWithOptPath::Enabled(None),
1724            Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
1725        };
1726        true
1727    }
1728
1729    pub(crate) fn parse_merge_functions(
1730        slot: &mut Option<MergeFunctions>,
1731        v: Option<&str>,
1732    ) -> bool {
1733        match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1734            Some(mergefunc) => *slot = Some(mergefunc),
1735            _ => return false,
1736        }
1737        true
1738    }
1739
1740    pub(crate) fn parse_remap_path_scope(
1741        slot: &mut RemapPathScopeComponents,
1742        v: Option<&str>,
1743    ) -> bool {
1744        if let Some(v) = v {
1745            *slot = RemapPathScopeComponents::empty();
1746            for s in v.split(',') {
1747                *slot |= match s {
1748                    "macro" => RemapPathScopeComponents::MACRO,
1749                    "diagnostics" => RemapPathScopeComponents::DIAGNOSTICS,
1750                    "debuginfo" => RemapPathScopeComponents::DEBUGINFO,
1751                    "coverage" => RemapPathScopeComponents::COVERAGE,
1752                    "object" => RemapPathScopeComponents::OBJECT,
1753                    "all" => RemapPathScopeComponents::all(),
1754                    _ => return false,
1755                }
1756            }
1757            true
1758        } else {
1759            false
1760        }
1761    }
1762
1763    pub(crate) fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
1764        match v.and_then(|s| RelocModel::from_str(s).ok()) {
1765            Some(relocation_model) => *slot = Some(relocation_model),
1766            None if v == Some("default") => *slot = None,
1767            _ => return false,
1768        }
1769        true
1770    }
1771
1772    pub(crate) fn parse_code_model(slot: &mut Option<CodeModel>, v: Option<&str>) -> bool {
1773        match v.and_then(|s| CodeModel::from_str(s).ok()) {
1774            Some(code_model) => *slot = Some(code_model),
1775            _ => return false,
1776        }
1777        true
1778    }
1779
1780    pub(crate) fn parse_tls_model(slot: &mut Option<TlsModel>, v: Option<&str>) -> bool {
1781        match v.and_then(|s| TlsModel::from_str(s).ok()) {
1782            Some(tls_model) => *slot = Some(tls_model),
1783            _ => return false,
1784        }
1785        true
1786    }
1787
1788    pub(crate) fn parse_terminal_url(slot: &mut TerminalUrl, v: Option<&str>) -> bool {
1789        *slot = match v {
1790            Some("on" | "" | "yes" | "y") | None => TerminalUrl::Yes,
1791            Some("off" | "no" | "n") => TerminalUrl::No,
1792            Some("auto") => TerminalUrl::Auto,
1793            _ => return false,
1794        };
1795        true
1796    }
1797
1798    pub(crate) fn parse_symbol_mangling_version(
1799        slot: &mut Option<SymbolManglingVersion>,
1800        v: Option<&str>,
1801    ) -> bool {
1802        *slot = match v {
1803            Some("legacy") => Some(SymbolManglingVersion::Legacy),
1804            Some("v0") => Some(SymbolManglingVersion::V0),
1805            Some("hashed") => Some(SymbolManglingVersion::Hashed),
1806            _ => return false,
1807        };
1808        true
1809    }
1810
1811    pub(crate) fn parse_src_file_hash(
1812        slot: &mut Option<SourceFileHashAlgorithm>,
1813        v: Option<&str>,
1814    ) -> bool {
1815        match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
1816            Some(hash_kind) => *slot = Some(hash_kind),
1817            _ => return false,
1818        }
1819        true
1820    }
1821
1822    pub(crate) fn parse_cargo_src_file_hash(
1823        slot: &mut Option<SourceFileHashAlgorithm>,
1824        v: Option<&str>,
1825    ) -> bool {
1826        match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
1827            Some(hash_kind) => {
1828                *slot = Some(hash_kind);
1829            }
1830            _ => return false,
1831        }
1832        true
1833    }
1834
1835    pub(crate) fn parse_target_feature(slot: &mut String, v: Option<&str>) -> bool {
1836        match v {
1837            Some(s) => {
1838                if !slot.is_empty() {
1839                    slot.push(',');
1840                }
1841                slot.push_str(s);
1842                true
1843            }
1844            None => false,
1845        }
1846    }
1847
1848    pub(crate) fn parse_link_self_contained(slot: &mut LinkSelfContained, v: Option<&str>) -> bool {
1849        // Whenever `-C link-self-contained` is passed without a value, it's an opt-in
1850        // just like `parse_opt_bool`, the historical value of this flag.
1851        //
1852        // 1. Parse historical single bool values
1853        let s = v.unwrap_or("y");
1854        match s {
1855            "y" | "yes" | "on" => {
1856                slot.set_all_explicitly(true);
1857                return true;
1858            }
1859            "n" | "no" | "off" => {
1860                slot.set_all_explicitly(false);
1861                return true;
1862            }
1863            _ => {}
1864        }
1865
1866        // 2. Parse a list of enabled and disabled components.
1867        for comp in s.split(',') {
1868            if slot.handle_cli_component(comp).is_none() {
1869                return false;
1870            }
1871        }
1872
1873        true
1874    }
1875
1876    /// Parse a comma-separated list of enabled and disabled linker features.
1877    pub(crate) fn parse_linker_features(slot: &mut LinkerFeaturesCli, v: Option<&str>) -> bool {
1878        match v {
1879            Some(s) => {
1880                for feature in s.split(',') {
1881                    if slot.handle_cli_feature(feature).is_none() {
1882                        return false;
1883                    }
1884                }
1885
1886                true
1887            }
1888            None => false,
1889        }
1890    }
1891
1892    pub(crate) fn parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool {
1893        match v {
1894            Some("command") => *slot = Some(WasiExecModel::Command),
1895            Some("reactor") => *slot = Some(WasiExecModel::Reactor),
1896            _ => return false,
1897        }
1898        true
1899    }
1900
1901    pub(crate) fn parse_split_debuginfo(
1902        slot: &mut Option<SplitDebuginfo>,
1903        v: Option<&str>,
1904    ) -> bool {
1905        match v.and_then(|s| SplitDebuginfo::from_str(s).ok()) {
1906            Some(e) => *slot = Some(e),
1907            _ => return false,
1908        }
1909        true
1910    }
1911
1912    pub(crate) fn parse_split_dwarf_kind(slot: &mut SplitDwarfKind, v: Option<&str>) -> bool {
1913        match v.and_then(|s| SplitDwarfKind::from_str(s).ok()) {
1914            Some(e) => *slot = e,
1915            _ => return false,
1916        }
1917        true
1918    }
1919
1920    pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1921        match v.and_then(|s| StackProtector::from_str(s).ok()) {
1922            Some(ssp) => *slot = ssp,
1923            _ => return false,
1924        }
1925        true
1926    }
1927
1928    pub(crate) fn parse_branch_protection(
1929        slot: &mut Option<BranchProtection>,
1930        v: Option<&str>,
1931    ) -> bool {
1932        match v {
1933            Some(s) => {
1934                let slot = slot.get_or_insert_default();
1935                for opt in s.split(',') {
1936                    match opt {
1937                        "bti" => slot.bti = true,
1938                        "pac-ret" if slot.pac_ret.is_none() => {
1939                            slot.pac_ret = Some(PacRet { leaf: false, pc: false, key: PAuthKey::A })
1940                        }
1941                        "leaf" => match slot.pac_ret.as_mut() {
1942                            Some(pac) => pac.leaf = true,
1943                            _ => return false,
1944                        },
1945                        "b-key" => match slot.pac_ret.as_mut() {
1946                            Some(pac) => pac.key = PAuthKey::B,
1947                            _ => return false,
1948                        },
1949                        "pc" => match slot.pac_ret.as_mut() {
1950                            Some(pac) => pac.pc = true,
1951                            _ => return false,
1952                        },
1953                        "gcs" => slot.gcs = true,
1954                        _ => return false,
1955                    };
1956                }
1957            }
1958            _ => return false,
1959        }
1960        true
1961    }
1962
1963    pub(crate) fn parse_collapse_macro_debuginfo(
1964        slot: &mut CollapseMacroDebuginfo,
1965        v: Option<&str>,
1966    ) -> bool {
1967        if v.is_some() {
1968            let mut bool_arg = None;
1969            if parse_opt_bool(&mut bool_arg, v) {
1970                *slot = if bool_arg.unwrap() {
1971                    CollapseMacroDebuginfo::Yes
1972                } else {
1973                    CollapseMacroDebuginfo::No
1974                };
1975                return true;
1976            }
1977        }
1978
1979        *slot = match v {
1980            Some("external") => CollapseMacroDebuginfo::External,
1981            _ => return false,
1982        };
1983        true
1984    }
1985
1986    pub(crate) fn parse_proc_macro_execution_strategy(
1987        slot: &mut ProcMacroExecutionStrategy,
1988        v: Option<&str>,
1989    ) -> bool {
1990        *slot = match v {
1991            Some("same-thread") => ProcMacroExecutionStrategy::SameThread,
1992            Some("cross-thread") => ProcMacroExecutionStrategy::CrossThread,
1993            _ => return false,
1994        };
1995        true
1996    }
1997
1998    pub(crate) fn parse_inlining_threshold(slot: &mut InliningThreshold, v: Option<&str>) -> bool {
1999        match v {
2000            Some("always" | "yes") => {
2001                *slot = InliningThreshold::Always;
2002            }
2003            Some("never") => {
2004                *slot = InliningThreshold::Never;
2005            }
2006            Some(v) => {
2007                if let Ok(threshold) = v.parse() {
2008                    *slot = InliningThreshold::Sometimes(threshold);
2009                } else {
2010                    return false;
2011                }
2012            }
2013            None => return false,
2014        }
2015        true
2016    }
2017
2018    pub(crate) fn parse_llvm_module_flag(
2019        slot: &mut Vec<(String, u32, String)>,
2020        v: Option<&str>,
2021    ) -> bool {
2022        let elements = v.unwrap_or_default().split(':').collect::<Vec<_>>();
2023        let [key, md_type, value, behavior] = elements.as_slice() else {
2024            return false;
2025        };
2026        if *md_type != "u32" {
2027            // Currently we only support u32 metadata flags, but require the
2028            // type for forward-compatibility.
2029            return false;
2030        }
2031        let Ok(value) = value.parse::<u32>() else {
2032            return false;
2033        };
2034        let behavior = behavior.to_lowercase();
2035        let all_behaviors =
2036            ["error", "warning", "require", "override", "append", "appendunique", "max", "min"];
2037        if !all_behaviors.contains(&behavior.as_str()) {
2038            return false;
2039        }
2040
2041        slot.push((key.to_string(), value, behavior));
2042        true
2043    }
2044
2045    pub(crate) fn parse_function_return(slot: &mut FunctionReturn, v: Option<&str>) -> bool {
2046        match v {
2047            Some("keep") => *slot = FunctionReturn::Keep,
2048            Some("thunk-extern") => *slot = FunctionReturn::ThunkExtern,
2049            _ => return false,
2050        }
2051        true
2052    }
2053
2054    pub(crate) fn parse_wasm_c_abi(_slot: &mut (), v: Option<&str>) -> bool {
2055        v == Some("spec")
2056    }
2057
2058    pub(crate) fn parse_mir_include_spans(slot: &mut MirIncludeSpans, v: Option<&str>) -> bool {
2059        *slot = match v {
2060            Some("on" | "yes" | "y" | "true") | None => MirIncludeSpans::On,
2061            Some("off" | "no" | "n" | "false") => MirIncludeSpans::Off,
2062            Some("nll") => MirIncludeSpans::Nll,
2063            _ => return false,
2064        };
2065
2066        true
2067    }
2068
2069    pub(crate) fn parse_align(slot: &mut Option<Align>, v: Option<&str>) -> bool {
2070        let mut bytes = 0u64;
2071        if !parse_number(&mut bytes, v) {
2072            return false;
2073        }
2074
2075        let Ok(align) = Align::from_bytes(bytes) else {
2076            return false;
2077        };
2078
2079        *slot = Some(align);
2080
2081        true
2082    }
2083}
2084
2085options! {
2086    CodegenOptions, CodegenOptionsTargetModifiers, CG_OPTIONS, cgopts, "C", "codegen",
2087
2088    // If you add a new option, please update:
2089    // - compiler/rustc_interface/src/tests.rs
2090    // - src/doc/rustc/src/codegen-options/index.md
2091
2092    // tidy-alphabetical-start
2093    #[rustc_lint_opt_deny_field_access("documented to do nothing")]
2094    ar: String = (String::new(), parse_string, [UNTRACKED],
2095        "this option is deprecated and does nothing",
2096        deprecated_do_nothing: true),
2097    #[rustc_lint_opt_deny_field_access("use `Session::code_model` instead of this field")]
2098    code_model: Option<CodeModel> = (None, parse_code_model, [TRACKED],
2099        "choose the code model to use (`rustc --print code-models` for details)"),
2100    codegen_units: Option<usize> = (None, parse_opt_number, [UNTRACKED],
2101        "divide crate into N units to optimize in parallel"),
2102    collapse_macro_debuginfo: CollapseMacroDebuginfo = (CollapseMacroDebuginfo::Unspecified,
2103        parse_collapse_macro_debuginfo, [TRACKED],
2104        "set option to collapse debuginfo for macros"),
2105    control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [TRACKED],
2106        "use Windows Control Flow Guard (default: no)"),
2107    debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
2108        "explicitly enable the `cfg(debug_assertions)` directive"),
2109    debuginfo: DebugInfo = (DebugInfo::None, parse_debuginfo, [TRACKED],
2110        "debug info emission level (0-2, none, line-directives-only, \
2111        line-tables-only, limited, or full; default: 0)"),
2112    default_linker_libraries: bool = (false, parse_bool, [UNTRACKED],
2113        "allow the linker to link its default libraries (default: no)"),
2114    dlltool: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
2115        "import library generation tool (ignored except when targeting windows-gnu)"),
2116    #[rustc_lint_opt_deny_field_access("use `Session::dwarf_version` instead of this field")]
2117    dwarf_version: Option<u32> = (None, parse_opt_number, [TRACKED],
2118        "version of DWARF debug information to emit (default: 2 or 4, depending on platform)"),
2119    embed_bitcode: bool = (true, parse_bool, [TRACKED],
2120        "emit bitcode in rlibs (default: yes)"),
2121    extra_filename: String = (String::new(), parse_string, [UNTRACKED],
2122        "extra data to put in each output filename"),
2123    force_frame_pointers: FramePointer = (FramePointer::MayOmit, parse_frame_pointer, [TRACKED],
2124        "force use of the frame pointers"),
2125    #[rustc_lint_opt_deny_field_access("use `Session::must_emit_unwind_tables` instead of this field")]
2126    force_unwind_tables: Option<bool> = (None, parse_opt_bool, [TRACKED],
2127        "force use of unwind tables"),
2128    incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
2129        "enable incremental compilation"),
2130    #[rustc_lint_opt_deny_field_access("documented to do nothing")]
2131    inline_threshold: Option<u32> = (None, parse_opt_number, [UNTRACKED],
2132        "this option is deprecated and does nothing \
2133        (consider using `-Cllvm-args=--inline-threshold=...`)",
2134        deprecated_do_nothing: true),
2135    #[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
2136    instrument_coverage: InstrumentCoverage = (InstrumentCoverage::No, parse_instrument_coverage, [TRACKED],
2137        "instrument the generated code to support LLVM source-based code coverage reports \
2138        (note, the compiler build config must include `profiler = true`); \
2139        implies `-C symbol-mangling-version=v0`"),
2140    jump_tables: bool = (true, parse_bool, [TRACKED],
2141        "allow jump table and lookup table generation from switch case lowering (default: yes)"),
2142    link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
2143        "a single extra argument to append to the linker invocation (can be used several times)"),
2144    link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
2145        "extra arguments to append to the linker invocation (space separated)"),
2146    #[rustc_lint_opt_deny_field_access("use `Session::link_dead_code` instead of this field")]
2147    link_dead_code: Option<bool> = (None, parse_opt_bool, [TRACKED],
2148        "try to generate and link dead code (default: no)"),
2149    link_self_contained: LinkSelfContained = (LinkSelfContained::default(), parse_link_self_contained, [UNTRACKED],
2150        "control whether to link Rust provided C objects/libraries or rely \
2151        on a C toolchain or linker installed in the system"),
2152    linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
2153        "system linker to link outputs with"),
2154    linker_features: LinkerFeaturesCli = (LinkerFeaturesCli::default(), parse_linker_features, [UNTRACKED],
2155        "a comma-separated list of linker features to enable (+) or disable (-): `lld`"),
2156    linker_flavor: Option<LinkerFlavorCli> = (None, parse_linker_flavor, [UNTRACKED],
2157        "linker flavor"),
2158    linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
2159        parse_linker_plugin_lto, [TRACKED],
2160        "generate build artifacts that are compatible with linker-based LTO"),
2161    llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
2162        "a list of arguments to pass to LLVM (space separated)"),
2163    #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
2164    lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
2165        "perform LLVM link-time optimizations"),
2166    metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
2167        "metadata to mangle symbol names with"),
2168    no_prepopulate_passes: bool = (false, parse_no_value, [TRACKED],
2169        "give an empty list of passes to the pass manager"),
2170    no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
2171        "disable the use of the redzone"),
2172    #[rustc_lint_opt_deny_field_access("documented to do nothing")]
2173    no_stack_check: bool = (false, parse_no_value, [UNTRACKED],
2174        "this option is deprecated and does nothing",
2175        deprecated_do_nothing: true),
2176    no_vectorize_loops: bool = (false, parse_no_value, [TRACKED],
2177        "disable loop vectorization optimization passes"),
2178    no_vectorize_slp: bool = (false, parse_no_value, [TRACKED],
2179        "disable LLVM's SLP vectorization pass"),
2180    opt_level: String = ("0".to_string(), parse_string, [TRACKED],
2181        "optimization level (0-3, s, or z; default: 0)"),
2182    #[rustc_lint_opt_deny_field_access("use `Session::overflow_checks` instead of this field")]
2183    overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
2184        "use overflow checks for integer arithmetic"),
2185    #[rustc_lint_opt_deny_field_access("use `Session::panic_strategy` instead of this field")]
2186    panic: Option<PanicStrategy> = (None, parse_opt_panic_strategy, [TRACKED],
2187        "panic strategy to compile crate with"),
2188    passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
2189        "a list of extra LLVM passes to run (space separated)"),
2190    prefer_dynamic: bool = (false, parse_bool, [TRACKED],
2191        "prefer dynamic linking to static linking (default: no)"),
2192    profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
2193        parse_switch_with_opt_path, [TRACKED],
2194        "compile the program with profiling instrumentation"),
2195    profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2196        "use the given `.profdata` file for profile-guided optimization"),
2197    #[rustc_lint_opt_deny_field_access("use `Session::relocation_model` instead of this field")]
2198    relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
2199        "control generation of position-independent code (PIC) \
2200        (`rustc --print relocation-models` for details)"),
2201    relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
2202        "choose which RELRO level to use"),
2203    remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
2204        "output remarks for these optimization passes (space separated, or \"all\")"),
2205    rpath: bool = (false, parse_bool, [UNTRACKED],
2206        "set rpath values in libs/exes (default: no)"),
2207    save_temps: bool = (false, parse_bool, [UNTRACKED],
2208        "save all temporary output files during compilation (default: no)"),
2209    soft_float: bool = (false, parse_bool, [TRACKED],
2210        "deprecated option: use soft float ABI (*eabihf targets only) (default: no)"),
2211    #[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
2212    split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
2213        "how to handle split-debuginfo, a platform-specific option"),
2214    strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
2215        "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
2216    symbol_mangling_version: Option<SymbolManglingVersion> = (None,
2217        parse_symbol_mangling_version, [TRACKED],
2218        "which mangling version to use for symbol names ('legacy' (default), 'v0', or 'hashed')"),
2219    target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
2220        "select target processor (`rustc --print target-cpus` for details)"),
2221    target_feature: String = (String::new(), parse_target_feature, [TRACKED],
2222        "target specific attributes. (`rustc --print target-features` for details). \
2223        This feature is unsafe."),
2224    unsafe_allow_abi_mismatch: Vec<String> = (Vec::new(), parse_comma_list, [UNTRACKED],
2225        "Allow incompatible target modifiers in dependency crates (comma separated list)"),
2226    // tidy-alphabetical-end
2227
2228    // If you add a new option, please update:
2229    // - compiler/rustc_interface/src/tests.rs
2230    // - src/doc/rustc/src/codegen-options/index.md
2231}
2232
2233options! {
2234    UnstableOptions, UnstableOptionsTargetModifiers, Z_OPTIONS, dbopts, "Z", "unstable",
2235
2236    // If you add a new option, please update:
2237    // - compiler/rustc_interface/src/tests.rs
2238    // - src/doc/unstable-book/src/compiler-flags
2239
2240    // tidy-alphabetical-start
2241    allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
2242        "only allow the listed language features to be enabled in code (comma separated)"),
2243    always_encode_mir: bool = (false, parse_bool, [TRACKED],
2244        "encode MIR of all functions into the crate metadata (default: no)"),
2245    annotate_moves: AnnotateMoves = (AnnotateMoves::Disabled, parse_annotate_moves, [TRACKED],
2246        "emit debug info for compiler-generated move and copy operations \
2247        to make them visible in profilers. Can be a boolean or a size limit in bytes (default: disabled)"),
2248    assert_incr_state: Option<String> = (None, parse_opt_string, [UNTRACKED],
2249        "assert that the incremental cache is in given state: \
2250         either `loaded` or `not-loaded`."),
2251    assume_incomplete_release: bool = (false, parse_bool, [TRACKED],
2252        "make cfg(version) treat the current version as incomplete (default: no)"),
2253    autodiff: Vec<crate::config::AutoDiff> = (Vec::new(), parse_autodiff, [TRACKED],
2254        "a list of autodiff flags to enable
2255        Mandatory setting:
2256        `=Enable`
2257        Optional extra settings:
2258        `=PrintTA`
2259        `=PrintAA`
2260        `=PrintPerf`
2261        `=PrintSteps`
2262        `=PrintModBefore`
2263        `=PrintModAfter`
2264        `=PrintModFinal`
2265        `=PrintPasses`,
2266        `=NoPostopt`
2267        `=LooseTypes`
2268        `=Inline`
2269        Multiple options can be combined with commas."),
2270    #[rustc_lint_opt_deny_field_access("use `Session::binary_dep_depinfo` instead of this field")]
2271    binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
2272        "include artifacts (sysroot, crate dependencies) used during compilation in dep-info \
2273        (default: no)"),
2274    box_noalias: bool = (true, parse_bool, [TRACKED],
2275        "emit noalias metadata for box (default: yes)"),
2276    branch_protection: Option<BranchProtection> = (None, parse_branch_protection, [TRACKED],
2277        "set options for branch target identification and pointer authentication on AArch64"),
2278    build_sdylib_interface: bool = (false, parse_bool, [UNTRACKED],
2279        "whether the stable interface is being built"),
2280    cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED],
2281        "instrument control-flow architecture protection"),
2282    check_cfg_all_expected: bool = (false, parse_bool, [UNTRACKED],
2283        "show all expected values in check-cfg diagnostics (default: no)"),
2284    checksum_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_cargo_src_file_hash, [TRACKED],
2285        "hash algorithm of source files used to check freshness in cargo (`blake3` or `sha256`)"),
2286    codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
2287        "the backend to use"),
2288    codegen_source_order: bool = (false, parse_bool, [UNTRACKED],
2289        "emit mono items in the order of spans in source files (default: no)"),
2290    contract_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
2291        "emit runtime checks for contract pre- and post-conditions (default: no)"),
2292    coverage_options: CoverageOptions = (CoverageOptions::default(), parse_coverage_options, [TRACKED],
2293        "control details of coverage instrumentation"),
2294    crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
2295        "inject the given attribute in the crate"),
2296    cross_crate_inline_threshold: InliningThreshold = (InliningThreshold::Sometimes(100), parse_inlining_threshold, [TRACKED],
2297        "threshold to allow cross crate inlining of functions"),
2298    debug_info_for_profiling: bool = (false, parse_bool, [TRACKED],
2299        "emit discriminators and other data necessary for AutoFDO"),
2300    debug_info_type_line_numbers: bool = (false, parse_bool, [TRACKED],
2301        "emit type and line information for additional data types (default: no)"),
2302    debuginfo_compression: DebugInfoCompression = (DebugInfoCompression::None, parse_debuginfo_compression, [TRACKED],
2303        "compress debug info sections (none, zlib, zstd, default: none)"),
2304    deduplicate_diagnostics: bool = (true, parse_bool, [UNTRACKED],
2305        "deduplicate identical diagnostics (default: yes)"),
2306    default_visibility: Option<SymbolVisibility> = (None, parse_opt_symbol_visibility, [TRACKED],
2307        "overrides the `default_visibility` setting of the target"),
2308    dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
2309        "in dep-info output, omit targets for tracking dependencies of the dep-info files \
2310        themselves (default: no)"),
2311    direct_access_external_data: Option<bool> = (None, parse_opt_bool, [TRACKED],
2312        "Direct or use GOT indirect to reference external data symbols"),
2313    dual_proc_macros: bool = (false, parse_bool, [TRACKED],
2314        "load proc macros for both target and host, but only link to the target (default: no)"),
2315    dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
2316        "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) \
2317        (default: no)"),
2318    dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
2319        "dump MIR state to file.
2320        `val` is used to select which passes and functions to dump. For example:
2321        `all` matches all passes and functions,
2322        `foo` matches all passes for functions whose name contains 'foo',
2323        `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
2324        `foo | bar` all passes for function names containing 'foo' or 'bar'."),
2325    dump_mir_dataflow: bool = (false, parse_bool, [UNTRACKED],
2326        "in addition to `.mir` files, create graphviz `.dot` files with dataflow results \
2327        (default: no)"),
2328    dump_mir_dir: String = ("mir_dump".to_string(), parse_string, [UNTRACKED],
2329        "the directory the MIR is dumped into (default: `mir_dump`)"),
2330    dump_mir_exclude_alloc_bytes: bool = (false, parse_bool, [UNTRACKED],
2331        "exclude the raw bytes of allocations when dumping MIR (used in tests) (default: no)"),
2332    dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
2333        "exclude the pass number when dumping MIR (used in tests) (default: no)"),
2334    dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
2335        "in addition to `.mir` files, create graphviz `.dot` files (default: no)"),
2336    dump_mono_stats: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
2337        parse_switch_with_opt_path, [UNTRACKED],
2338        "output statistics about monomorphization collection"),
2339    dump_mono_stats_format: DumpMonoStatsFormat = (DumpMonoStatsFormat::Markdown, parse_dump_mono_stats, [UNTRACKED],
2340        "the format to use for -Z dump-mono-stats (`markdown` (default) or `json`)"),
2341    #[rustc_lint_opt_deny_field_access("use `Session::dwarf_version` instead of this field")]
2342    dwarf_version: Option<u32> = (None, parse_opt_number, [TRACKED],
2343        "version of DWARF debug information to emit (default: 2 or 4, depending on platform)"),
2344    dylib_lto: bool = (false, parse_bool, [UNTRACKED],
2345        "enables LTO for dylib crate type"),
2346    eagerly_emit_delayed_bugs: bool = (false, parse_bool, [UNTRACKED],
2347        "emit delayed bugs eagerly as errors instead of stashing them and emitting \
2348        them only if an error has not been emitted"),
2349    ehcont_guard: bool = (false, parse_bool, [TRACKED],
2350        "generate Windows EHCont Guard tables"),
2351    embed_metadata: bool = (true, parse_bool, [TRACKED],
2352        "embed metadata in rlibs and dylibs (default: yes)"),
2353    embed_source: bool = (false, parse_bool, [TRACKED],
2354        "embed source text in DWARF debug sections (default: no)"),
2355    emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
2356        "emit a section containing stack size metadata (default: no)"),
2357    emit_thin_lto: bool = (true, parse_bool, [TRACKED],
2358        "emit the bc module with thin LTO info (default: yes)"),
2359    emscripten_wasm_eh: bool = (true, parse_bool, [TRACKED],
2360        "Use WebAssembly error handling for wasm32-unknown-emscripten"),
2361    enforce_type_length_limit: bool = (false, parse_bool, [TRACKED],
2362        "enforce the type length limit when monomorphizing instances in codegen"),
2363    experimental_default_bounds: bool = (false, parse_bool, [TRACKED],
2364        "enable default bounds for experimental group of auto traits"),
2365    export_executable_symbols: bool = (false, parse_bool, [TRACKED],
2366        "export symbols from executables, as if they were dynamic libraries"),
2367    external_clangrt: bool = (false, parse_bool, [UNTRACKED],
2368        "rely on user specified linker commands to find clangrt"),
2369    extra_const_ub_checks: bool = (false, parse_bool, [TRACKED],
2370        "turns on more checks to detect const UB, which can be slow (default: no)"),
2371    #[rustc_lint_opt_deny_field_access("use `Session::fewer_names` instead of this field")]
2372    fewer_names: Option<bool> = (None, parse_opt_bool, [TRACKED],
2373        "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \
2374        (default: no)"),
2375    fixed_x18: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
2376        "make the x18 register reserved on AArch64 (default: no)"),
2377    flatten_format_args: bool = (true, parse_bool, [TRACKED],
2378        "flatten nested format_args!() and literals into a simplified format_args!() call \
2379        (default: yes)"),
2380    fmt_debug: FmtDebug = (FmtDebug::Full, parse_fmt_debug, [TRACKED],
2381        "how detailed `#[derive(Debug)]` should be. `full` prints types recursively, \
2382        `shallow` prints only type names, `none` prints nothing and disables `{:?}`. (default: `full`)"),
2383    force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
2384        "force all crates to be `rustc_private` unstable (default: no)"),
2385    function_return: FunctionReturn = (FunctionReturn::default(), parse_function_return, [TRACKED],
2386        "replace returns with jumps to `__x86_return_thunk` (default: `keep`)"),
2387    function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
2388        "whether each function should go in its own section"),
2389    future_incompat_test: bool = (false, parse_bool, [UNTRACKED],
2390        "forces all lints to be future incompatible, used for internal testing (default: no)"),
2391    graphviz_dark_mode: bool = (false, parse_bool, [UNTRACKED],
2392        "use dark-themed colors in graphviz output (default: no)"),
2393    graphviz_font: String = ("Courier, monospace".to_string(), parse_string, [UNTRACKED],
2394        "use the given `fontname` in graphviz output; can be overridden by setting \
2395        environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`)"),
2396    has_thread_local: Option<bool> = (None, parse_opt_bool, [TRACKED],
2397        "explicitly enable the `cfg(target_thread_local)` directive"),
2398    higher_ranked_assumptions: bool = (false, parse_bool, [TRACKED],
2399        "allow deducing higher-ranked outlives assumptions from coroutines when proving auto traits"),
2400    hint_mostly_unused: bool = (false, parse_bool, [TRACKED],
2401        "hint that most of this crate will go unused, to minimize work for uncalled functions"),
2402    human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
2403        "generate human-readable, predictable names for codegen units (default: no)"),
2404    identify_regions: bool = (false, parse_bool, [UNTRACKED],
2405        "display unnamed regions as `'<id>`, using a non-ident unique id (default: no)"),
2406    ignore_directory_in_diagnostics_source_blocks: Vec<String> = (Vec::new(), parse_string_push, [UNTRACKED],
2407        "do not display the source code block in diagnostics for files in the directory"),
2408    incremental_ignore_spans: bool = (false, parse_bool, [TRACKED],
2409        "ignore spans during ICH computation -- used for testing (default: no)"),
2410    incremental_info: bool = (false, parse_bool, [UNTRACKED],
2411        "print high-level information about incremental reuse (or the lack thereof) \
2412        (default: no)"),
2413    incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
2414        "verify extended properties for incr. comp. (default: no):
2415        - hashes of green query instances
2416        - hash collisions of query keys
2417        - hash collisions when creating dep-nodes"),
2418    indirect_branch_cs_prefix: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
2419        "add `cs` prefix to `call` and `jmp` to indirect thunks (default: no)"),
2420    inline_llvm: bool = (true, parse_bool, [TRACKED],
2421        "enable LLVM inlining (default: yes)"),
2422    inline_mir: Option<bool> = (None, parse_opt_bool, [TRACKED],
2423        "enable MIR inlining (default: no)"),
2424    inline_mir_forwarder_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
2425        "inlining threshold when the caller is a simple forwarding function (default: 30)"),
2426    inline_mir_hint_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
2427        "inlining threshold for functions with inline hint (default: 100)"),
2428    inline_mir_preserve_debug: Option<bool> = (None, parse_opt_bool, [TRACKED],
2429        "when MIR inlining, whether to preserve debug info for callee variables \
2430        (default: preserve for debuginfo != None, otherwise remove)"),
2431    inline_mir_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
2432        "a default MIR inlining threshold (default: 50)"),
2433    input_stats: bool = (false, parse_bool, [UNTRACKED],
2434        "print some statistics about AST and HIR (default: no)"),
2435    instrument_mcount: bool = (false, parse_bool, [TRACKED],
2436        "insert function instrument code for mcount-based tracing (default: no)"),
2437    instrument_xray: Option<InstrumentXRay> = (None, parse_instrument_xray, [TRACKED],
2438        "insert function instrument code for XRay-based tracing (default: no)
2439         Optional extra settings:
2440         `=always`
2441         `=never`
2442         `=ignore-loops`
2443         `=instruction-threshold=N`
2444         `=skip-entry`
2445         `=skip-exit`
2446         Multiple options can be combined with commas."),
2447    layout_seed: Option<u64> = (None, parse_opt_number, [TRACKED],
2448        "seed layout randomization"),
2449    link_directives: bool = (true, parse_bool, [TRACKED],
2450        "honor #[link] directives in the compiled crate (default: yes)"),
2451    link_native_libraries: bool = (true, parse_bool, [UNTRACKED],
2452        "link native libraries in the linker invocation (default: yes)"),
2453    link_only: bool = (false, parse_bool, [TRACKED],
2454        "link the `.rlink` file generated by `-Z no-link` (default: no)"),
2455    lint_llvm_ir: bool = (false, parse_bool, [TRACKED],
2456        "lint LLVM IR (default: no)"),
2457    lint_mir: bool = (false, parse_bool, [UNTRACKED],
2458        "lint MIR before and after each transformation"),
2459    llvm_module_flag: Vec<(String, u32, String)> = (Vec::new(), parse_llvm_module_flag, [TRACKED],
2460        "a list of module flags to pass to LLVM (space separated)"),
2461    llvm_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
2462        "a list LLVM plugins to enable (space separated)"),
2463    llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
2464        "generate JSON tracing data file from LLVM data (default: no)"),
2465    location_detail: LocationDetail = (LocationDetail::all(), parse_location_detail, [TRACKED],
2466        "what location details should be tracked when using caller_location, either \
2467        `none`, or a comma separated list of location details, for which \
2468        valid options are `file`, `line`, and `column` (default: `file,line,column`)"),
2469    ls: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
2470        "decode and print various parts of the crate metadata for a library crate \
2471        (space separated)"),
2472    macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
2473        "show macro backtraces (default: no)"),
2474    macro_stats: bool = (false, parse_bool, [UNTRACKED],
2475        "print some statistics about macro expansions (default: no)"),
2476    maximal_hir_to_mir_coverage: bool = (false, parse_bool, [TRACKED],
2477        "save as much information as possible about the correspondence between MIR and HIR \
2478        as source scopes (default: no)"),
2479    merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
2480        "control the operation of the MergeFunctions LLVM pass, taking \
2481        the same values as the target option of the same name"),
2482    meta_stats: bool = (false, parse_bool, [UNTRACKED],
2483        "gather metadata statistics (default: no)"),
2484    metrics_dir: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
2485        "the directory metrics emitted by rustc are dumped into (implicitly enables default set of metrics)"),
2486    min_function_alignment: Option<Align> = (None, parse_align, [TRACKED],
2487        "align all functions to at least this many bytes. Must be a power of 2"),
2488    mir_emit_retag: bool = (false, parse_bool, [TRACKED],
2489        "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
2490        (default: no)"),
2491    mir_enable_passes: Vec<(String, bool)> = (Vec::new(), parse_list_with_polarity, [TRACKED],
2492        "use like `-Zmir-enable-passes=+DestinationPropagation,-InstSimplify`. Forces the \
2493        specified passes to be enabled, overriding all other checks. In particular, this will \
2494        enable unsound (known-buggy and hence usually disabled) passes without further warning! \
2495        Passes that are not specified are enabled or disabled by other flags as usual."),
2496    mir_include_spans: MirIncludeSpans = (MirIncludeSpans::default(), parse_mir_include_spans, [UNTRACKED],
2497        "include extra comments in mir pretty printing, like line numbers and statement indices, \
2498         details about types, etc. (boolean for all passes, 'nll' to enable in NLL MIR only, default: 'nll')"),
2499    #[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
2500    mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
2501        "MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),
2502    mir_preserve_ub: bool = (false, parse_bool, [TRACKED],
2503        "keep place mention statements and reads in trivial SwitchInt terminators, which are interpreted \
2504        e.g., by miri; implies -Zmir-opt-level=0 (default: no)"),
2505    mir_strip_debuginfo: MirStripDebugInfo = (MirStripDebugInfo::None, parse_mir_strip_debuginfo, [TRACKED],
2506        "Whether to remove some of the MIR debug info from methods.  Default: None"),
2507    move_size_limit: Option<usize> = (None, parse_opt_number, [TRACKED],
2508        "the size at which the `large_assignments` lint starts to be emitted"),
2509    mutable_noalias: bool = (true, parse_bool, [TRACKED],
2510        "emit noalias metadata for mutable references (default: yes)"),
2511    namespaced_crates: bool = (false, parse_bool, [TRACKED],
2512        "allow crates to be namespaced by other crates (default: no)"),
2513    next_solver: NextSolverConfig = (NextSolverConfig::default(), parse_next_solver_config, [TRACKED],
2514        "enable and configure the next generation trait solver used by rustc"),
2515    nll_facts: bool = (false, parse_bool, [UNTRACKED],
2516        "dump facts from NLL analysis into side files (default: no)"),
2517    nll_facts_dir: String = ("nll-facts".to_string(), parse_string, [UNTRACKED],
2518        "the directory the NLL facts are dumped into (default: `nll-facts`)"),
2519    no_analysis: bool = (false, parse_no_value, [UNTRACKED],
2520        "parse and expand the source, but run no analysis"),
2521    no_codegen: bool = (false, parse_no_value, [TRACKED_NO_CRATE_HASH],
2522        "run all passes except codegen; no output"),
2523    no_generate_arange_section: bool = (false, parse_no_value, [TRACKED],
2524        "omit DWARF address ranges that give faster lookups"),
2525    no_implied_bounds_compat: bool = (false, parse_bool, [TRACKED],
2526        "disable the compatibility version of the `implied_bounds_ty` query"),
2527    no_leak_check: bool = (false, parse_no_value, [UNTRACKED],
2528        "disable the 'leak check' for subtyping; unsound, but useful for tests"),
2529    no_link: bool = (false, parse_no_value, [TRACKED],
2530        "compile without linking"),
2531    no_parallel_backend: bool = (false, parse_no_value, [UNTRACKED],
2532        "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"),
2533    no_profiler_runtime: bool = (false, parse_no_value, [TRACKED],
2534        "prevent automatic injection of the profiler_builtins crate"),
2535    no_steal_thir: bool = (false, parse_bool, [UNTRACKED],
2536        "don't steal the THIR when we're done with it; useful for rustc drivers (default: no)"),
2537    no_trait_vptr: bool = (false, parse_no_value, [TRACKED],
2538        "disable generation of trait vptr in vtable for upcasting"),
2539    no_unique_section_names: bool = (false, parse_bool, [TRACKED],
2540        "do not use unique names for text and data sections when -Z function-sections is used"),
2541    normalize_docs: bool = (false, parse_bool, [TRACKED],
2542        "normalize associated items in rustdoc when generating documentation"),
2543    offload: Vec<crate::config::Offload> = (Vec::new(), parse_offload, [TRACKED],
2544        "a list of offload flags to enable
2545        Mandatory setting:
2546        `=Enable`
2547        Currently the only option available"),
2548    on_broken_pipe: OnBrokenPipe = (OnBrokenPipe::Default, parse_on_broken_pipe, [TRACKED],
2549        "behavior of std::io::ErrorKind::BrokenPipe (SIGPIPE)"),
2550    osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
2551        "pass `-install_name @rpath/...` to the macOS linker (default: no)"),
2552    packed_bundled_libs: bool = (false, parse_bool, [TRACKED],
2553        "change rlib format to store native libraries as archives"),
2554    panic_abort_tests: bool = (false, parse_bool, [TRACKED],
2555        "support compiling tests with panic=abort (default: no)"),
2556    panic_in_drop: PanicStrategy = (PanicStrategy::Unwind, parse_panic_strategy, [TRACKED],
2557        "panic strategy for panics in drops"),
2558    parse_crate_root_only: bool = (false, parse_bool, [UNTRACKED],
2559        "parse the crate root file only; do not parse other files, compile, assemble, or link \
2560        (default: no)"),
2561    patchable_function_entry: PatchableFunctionEntry = (PatchableFunctionEntry::default(), parse_patchable_function_entry, [TRACKED],
2562        "nop padding at function entry"),
2563    plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
2564        "whether to use the PLT when calling into shared libraries;
2565        only has effect for PIC code on systems with ELF binaries
2566        (default: PLT is disabled if full relro is enabled on x86_64)"),
2567    polonius: Polonius = (Polonius::default(), parse_polonius, [TRACKED],
2568        "enable polonius-based borrow-checker (default: no)"),
2569    pre_link_arg: (/* redirected to pre_link_args */) = ((), parse_string_push, [UNTRACKED],
2570        "a single extra argument to prepend the linker invocation (can be used several times)"),
2571    pre_link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
2572        "extra arguments to prepend to the linker invocation (space separated)"),
2573    precise_enum_drop_elaboration: bool = (true, parse_bool, [TRACKED],
2574        "use a more precise version of drop elaboration for matches on enums (default: yes). \
2575        This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
2576        See #77382 and #74551."),
2577    #[rustc_lint_opt_deny_field_access("use `Session::print_codegen_stats` instead of this field")]
2578    print_codegen_stats: bool = (false, parse_bool, [UNTRACKED],
2579        "print codegen statistics (default: no)"),
2580    print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
2581        "print the LLVM optimization passes being run (default: no)"),
2582    print_mono_items: bool = (false, parse_bool, [UNTRACKED],
2583        "print the result of the monomorphization collection pass (default: no)"),
2584    print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
2585        "print layout information for each type encountered (default: no)"),
2586    proc_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
2587         "show backtraces for panics during proc-macro execution (default: no)"),
2588    proc_macro_execution_strategy: ProcMacroExecutionStrategy = (ProcMacroExecutionStrategy::SameThread,
2589        parse_proc_macro_execution_strategy, [UNTRACKED],
2590        "how to run proc-macro code (default: same-thread)"),
2591    profile_closures: bool = (false, parse_no_value, [UNTRACKED],
2592        "profile size of closures"),
2593    profile_sample_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2594        "use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO)"),
2595    profiler_runtime: String = (String::from("profiler_builtins"), parse_string, [TRACKED],
2596        "name of the profiler runtime crate to automatically inject (default: `profiler_builtins`)"),
2597    query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
2598        "enable queries of the dependency graph for regression testing (default: no)"),
2599    randomize_layout: bool = (false, parse_bool, [TRACKED],
2600        "randomize the layout of types (default: no)"),
2601    reg_struct_return: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
2602        "On x86-32 targets, it overrides the default ABI to return small structs in registers.
2603        It is UNSOUND to link together crates that use different values for this flag!"),
2604    regparm: Option<u32> = (None, parse_opt_number, [TRACKED TARGET_MODIFIER],
2605        "On x86-32 targets, setting this to N causes the compiler to pass N arguments \
2606        in registers EAX, EDX, and ECX instead of on the stack for\
2607        \"C\", \"cdecl\", and \"stdcall\" fn.\
2608        It is UNSOUND to link together crates that use different values for this flag!"),
2609    relax_elf_relocations: Option<bool> = (None, parse_opt_bool, [TRACKED],
2610        "whether ELF relocations can be relaxed"),
2611    remap_cwd_prefix: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2612        "remap paths under the current working directory to this path prefix"),
2613    remap_path_scope: RemapPathScopeComponents = (RemapPathScopeComponents::all(), parse_remap_path_scope, [TRACKED],
2614        "remap path scope (default: all)"),
2615    remark_dir: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
2616        "directory into which to write optimization remarks (if not specified, they will be \
2617written to standard error output)"),
2618    retpoline: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
2619        "enables retpoline-indirect-branches and retpoline-indirect-calls target features (default: no)"),
2620    retpoline_external_thunk: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
2621        "enables retpoline-external-thunk, retpoline-indirect-branches and retpoline-indirect-calls \
2622        target features (default: no)"),
2623    #[rustc_lint_opt_deny_field_access("use `Session::sanitizers()` instead of this field")]
2624    sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED TARGET_MODIFIER],
2625        "use a sanitizer"),
2626    sanitizer_cfi_canonical_jump_tables: Option<bool> = (Some(true), parse_opt_bool, [TRACKED],
2627        "enable canonical jump tables (default: yes)"),
2628    sanitizer_cfi_generalize_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
2629        "enable generalizing pointer types (default: no)"),
2630    sanitizer_cfi_normalize_integers: Option<bool> = (None, parse_opt_bool, [TRACKED TARGET_MODIFIER],
2631        "enable normalizing integer types (default: no)"),
2632    sanitizer_dataflow_abilist: Vec<String> = (Vec::new(), parse_comma_list, [TRACKED],
2633        "additional ABI list files that control how shadow parameters are passed (comma separated)"),
2634    sanitizer_kcfi_arity: Option<bool> = (None, parse_opt_bool, [TRACKED],
2635        "enable KCFI arity indicator (default: no)"),
2636    sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED],
2637        "enable origins tracking in MemorySanitizer"),
2638    sanitizer_recover: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
2639        "enable recovery for selected sanitizers"),
2640    saturating_float_casts: Option<bool> = (None, parse_opt_bool, [TRACKED],
2641        "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
2642        the max/min integer respectively, and NaN is mapped to 0 (default: yes)"),
2643    self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
2644        parse_switch_with_opt_path, [UNTRACKED],
2645        "run the self profiler and output the raw event data"),
2646    self_profile_counter: String = ("wall-time".to_string(), parse_string, [UNTRACKED],
2647        "counter used by the self profiler (default: `wall-time`), one of:
2648        `wall-time` (monotonic clock, i.e. `std::time::Instant`)
2649        `instructions:u` (retired instructions, userspace-only)
2650        `instructions-minus-irqs:u` (subtracting hardware interrupt counts for extra accuracy)"
2651    ),
2652    /// keep this in sync with the event filter names in librustc_data_structures/profiling.rs
2653    self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
2654        "specify the events recorded by the self profiler;
2655        for example: `-Z self-profile-events=default,query-keys`
2656        all options: none, all, default, generic-activity, query-provider, query-cache-hit
2657                     query-blocked, incr-cache-load, incr-result-hashing, query-keys, function-args, args, llvm, artifact-sizes"),
2658    share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
2659        "make the current crate share its generic instantiations"),
2660    shell_argfiles: bool = (false, parse_bool, [UNTRACKED],
2661        "allow argument files to be specified with POSIX \"shell-style\" argument quoting"),
2662    simulate_remapped_rust_src_base: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2663        "simulate the effect of remap-debuginfo = true at bootstrapping by remapping path \
2664        to rust's source base directory. only meant for testing purposes"),
2665    small_data_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
2666        "Set the threshold for objects to be stored in a \"small data\" section"),
2667    span_debug: bool = (false, parse_bool, [UNTRACKED],
2668        "forward proc_macro::Span's `Debug` impl to `Span`"),
2669    /// o/w tests have closure@path
2670    span_free_formats: bool = (false, parse_bool, [UNTRACKED],
2671        "exclude spans when debug-printing compiler state (default: no)"),
2672    split_dwarf_inlining: bool = (false, parse_bool, [TRACKED],
2673        "provide minimal debug info in the object/executable to facilitate online \
2674         symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF"),
2675    split_dwarf_kind: SplitDwarfKind = (SplitDwarfKind::Split, parse_split_dwarf_kind, [TRACKED],
2676        "split dwarf variant (only if -Csplit-debuginfo is enabled and on relevant platform)
2677        (default: `split`)
2678
2679        `split`: sections which do not require relocation are written into a DWARF object (`.dwo`)
2680                 file which is ignored by the linker
2681        `single`: sections which do not require relocation are written into object file but ignored
2682                  by the linker"),
2683    split_dwarf_out_dir : Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2684        "location for writing split DWARF objects (`.dwo`) if enabled"),
2685    split_lto_unit: Option<bool> = (None, parse_opt_bool, [TRACKED],
2686        "enable LTO unit splitting (default: no)"),
2687    src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
2688        "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
2689    #[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2690    stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
2691        "control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
2692    staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
2693        "allow staticlibs to have rust dylib dependencies"),
2694    staticlib_prefer_dynamic: bool = (false, parse_bool, [TRACKED],
2695        "prefer dynamic linking to static linking for staticlibs (default: no)"),
2696    strict_init_checks: bool = (false, parse_bool, [TRACKED],
2697        "control if mem::uninitialized and mem::zeroed panic on more UB"),
2698    #[rustc_lint_opt_deny_field_access("use `Session::teach` instead of this field")]
2699    teach: bool = (false, parse_bool, [TRACKED],
2700        "show extended diagnostic help (default: no)"),
2701    temps_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
2702        "the directory the intermediate files are written to"),
2703    terminal_urls: TerminalUrl = (TerminalUrl::No, parse_terminal_url, [UNTRACKED],
2704        "use the OSC 8 hyperlink terminal specification to print hyperlinks in the compiler output"),
2705    #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
2706    thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
2707        "enable ThinLTO when possible"),
2708    /// We default to 1 here since we want to behave like
2709    /// a sequential compiler for now. This'll likely be adjusted
2710    /// in the future. Note that -Zthreads=0 is the way to get
2711    /// the num_cpus behavior.
2712    #[rustc_lint_opt_deny_field_access("use `Session::threads` instead of this field")]
2713    threads: usize = (1, parse_threads, [UNTRACKED],
2714        "use a thread pool with N threads"),
2715    time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
2716        "measure time of each LLVM pass (default: no)"),
2717    time_passes: bool = (false, parse_bool, [UNTRACKED],
2718        "measure time of each rustc pass (default: no)"),
2719    time_passes_format: TimePassesFormat = (TimePassesFormat::Text, parse_time_passes_format, [UNTRACKED],
2720        "the format to use for -Z time-passes (`text` (default) or `json`)"),
2721    tiny_const_eval_limit: bool = (false, parse_bool, [TRACKED],
2722        "sets a tiny, non-configurable limit for const eval; useful for compiler tests"),
2723    #[rustc_lint_opt_deny_field_access("use `Session::tls_model` instead of this field")]
2724    tls_model: Option<TlsModel> = (None, parse_tls_model, [TRACKED],
2725        "choose the TLS model to use (`rustc --print tls-models` for details)"),
2726    trace_macros: bool = (false, parse_bool, [UNTRACKED],
2727        "for every macro invocation, print its name and arguments (default: no)"),
2728    track_diagnostics: bool = (false, parse_bool, [UNTRACKED],
2729        "tracks where in rustc a diagnostic was emitted"),
2730    // Diagnostics are considered side-effects of a query (see `QuerySideEffect`) and are saved
2731    // alongside query results and changes to translation options can affect diagnostics - so
2732    // translation options should be tracked.
2733    translate_additional_ftl: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
2734        "additional fluent translation to preferentially use (for testing translation)"),
2735    translate_directionality_markers: bool = (false, parse_bool, [TRACKED],
2736        "emit directionality isolation markers in translated diagnostics"),
2737    translate_lang: Option<LanguageIdentifier> = (None, parse_opt_langid, [TRACKED],
2738        "language identifier for diagnostic output"),
2739    translate_remapped_path_to_local_path: bool = (true, parse_bool, [TRACKED],
2740        "translate remapped paths into local paths when possible (default: yes)"),
2741    trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED],
2742        "generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"),
2743    treat_err_as_bug: Option<NonZero<usize>> = (None, parse_treat_err_as_bug, [TRACKED],
2744        "treat the `val`th error that occurs as bug (default if not specified: 0 - don't treat errors as bugs. \
2745        default if specified without a value: 1 - treat the first error as bug)"),
2746    trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED],
2747        "in diagnostics, use heuristics to shorten paths referring to items"),
2748    tune_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
2749        "select processor to schedule for (`rustc --print target-cpus` for details)"),
2750    #[rustc_lint_opt_deny_field_access("use `TyCtxt::use_typing_mode_borrowck` instead of this field")]
2751    typing_mode_borrowck: bool = (false, parse_bool, [TRACKED],
2752        "enable `TypingMode::Borrowck`, changing the way opaque types are handled during MIR borrowck"),
2753    #[rustc_lint_opt_deny_field_access("use `Session::ub_checks` instead of this field")]
2754    ub_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
2755        "emit runtime checks for Undefined Behavior (default: -Cdebug-assertions)"),
2756    ui_testing: bool = (false, parse_bool, [UNTRACKED],
2757        "emit compiler diagnostics in a form suitable for UI testing (default: no)"),
2758    uninit_const_chunk_threshold: usize = (16, parse_number, [TRACKED],
2759        "allow generating const initializers with mixed init/uninit chunks, \
2760        and set the maximum number of chunks for which this is allowed (default: 16)"),
2761    unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
2762        "take the brakes off const evaluation. NOTE: this is unsound (default: no)"),
2763    unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
2764        "present the input source, unstable (and less-pretty) variants;
2765        `normal`, `identified`,
2766        `expanded`, `expanded,identified`,
2767        `expanded,hygiene` (with internal representations),
2768        `ast-tree` (raw AST before expansion),
2769        `ast-tree,expanded` (raw AST after expansion),
2770        `hir` (the HIR), `hir,identified`,
2771        `hir,typed` (HIR with types for each node),
2772        `hir-tree` (dump the raw HIR),
2773        `thir-tree`, `thir-flat`,
2774        `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
2775    unsound_mir_opts: bool = (false, parse_bool, [TRACKED],
2776        "enable unsound and buggy MIR optimizations (default: no)"),
2777    /// This name is kind of confusing: Most unstable options enable something themselves, while
2778    /// this just allows "normal" options to be feature-gated.
2779    ///
2780    /// The main check for `-Zunstable-options` takes place separately from the
2781    /// usual parsing of `-Z` options (see [`crate::config::nightly_options`]),
2782    /// so this boolean value is mostly used for enabling unstable _values_ of
2783    /// stable options. That separate check doesn't handle boolean values, so
2784    /// to avoid an inconsistent state we also forbid them here.
2785    #[rustc_lint_opt_deny_field_access("use `Session::unstable_options` instead of this field")]
2786    unstable_options: bool = (false, parse_no_value, [UNTRACKED],
2787        "adds unstable command line options to rustc interface (default: no)"),
2788    use_ctors_section: Option<bool> = (None, parse_opt_bool, [TRACKED],
2789        "use legacy .ctors section for initializers rather than .init_array"),
2790    use_sync_unwind: Option<bool> = (None, parse_opt_bool, [TRACKED],
2791        "Generate sync unwind tables instead of async unwind tables (default: no)"),
2792    validate_mir: bool = (false, parse_bool, [UNTRACKED],
2793        "validate MIR after each transformation"),
2794    verbose_asm: bool = (false, parse_bool, [TRACKED],
2795        "add descriptive comments from LLVM to the assembly (may change behavior) (default: no)"),
2796    #[rustc_lint_opt_deny_field_access("use `Session::verbose_internals` instead of this field")]
2797    verbose_internals: bool = (false, parse_bool, [TRACKED_NO_CRATE_HASH],
2798        "in general, enable more debug printouts (default: no)"),
2799    #[rustc_lint_opt_deny_field_access("use `Session::verify_llvm_ir` instead of this field")]
2800    verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
2801        "verify LLVM IR (default: no)"),
2802    virtual_function_elimination: bool = (false, parse_bool, [TRACKED],
2803        "enables dead virtual function elimination optimization. \
2804        Requires `-Clto[=[fat,yes]]`"),
2805    wasi_exec_model: Option<WasiExecModel> = (None, parse_wasi_exec_model, [TRACKED],
2806        "whether to build a wasi command or reactor"),
2807    // This option only still exists to provide a more gradual transition path for people who need
2808    // the spec-complaint C ABI to be used.
2809    // FIXME remove this after a couple releases
2810    wasm_c_abi: () = ((), parse_wasm_c_abi, [TRACKED],
2811        "use spec-compliant C ABI for `wasm32-unknown-unknown` (deprecated, always enabled)"),
2812    write_long_types_to_disk: bool = (true, parse_bool, [UNTRACKED],
2813        "whether long type names should be written to files instead of being printed in errors"),
2814    // tidy-alphabetical-end
2815
2816    // If you add a new option, please update:
2817    // - compiler/rustc_interface/src/tests.rs
2818    // - src/doc/unstable-book/src/compiler-flags
2819}