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