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