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