-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
options.rs
1913 lines (1796 loc) · 86.7 KB
/
options.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::config::*;
use crate::search_paths::SearchPath;
use crate::utils::NativeLib;
use crate::{lint, EarlyErrorHandler};
use rustc_data_structures::profiling::TimePassesFormat;
use rustc_errors::ColorConfig;
use rustc_errors::{LanguageIdentifier, TerminalUrl};
use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, SanitizerSet};
use rustc_target::spec::{
RelocModel, RelroLevel, SplitDebuginfo, StackProtector, TargetTriple, TlsModel,
};
use rustc_feature::UnstableFeatures;
use rustc_span::edition::Edition;
use rustc_span::RealFileName;
use rustc_span::SourceFileHashAlgorithm;
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::num::{IntErrorKind, NonZeroUsize};
use std::path::PathBuf;
use std::str;
macro_rules! insert {
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => {
if $sub_hashes
.insert(stringify!($opt_name), $opt_expr as &dyn dep_tracking::DepTrackingHash)
.is_some()
{
panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
}
};
}
macro_rules! hash_opt {
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [UNTRACKED]) => {{}};
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [TRACKED]) => {{ insert!($opt_name, $opt_expr, $sub_hashes) }};
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $for_crate_hash: ident, [TRACKED_NO_CRATE_HASH]) => {{
if !$for_crate_hash {
insert!($opt_name, $opt_expr, $sub_hashes)
}
}};
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [SUBSTRUCT]) => {{}};
}
macro_rules! hash_substruct {
($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [UNTRACKED]) => {{}};
($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED]) => {{}};
($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED_NO_CRATE_HASH]) => {{}};
($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [SUBSTRUCT]) => {
use crate::config::dep_tracking::DepTrackingHash;
$opt_expr.dep_tracking_hash($for_crate_hash, $error_format).hash(
$hasher,
$error_format,
$for_crate_hash,
);
};
}
macro_rules! top_level_options {
( $( #[$top_level_attr:meta] )* pub struct Options { $(
$( #[$attr:meta] )*
$opt:ident : $t:ty [$dep_tracking_marker:ident],
)* } ) => (
#[derive(Clone)]
$( #[$top_level_attr] )*
pub struct Options {
$(
$( #[$attr] )*
pub $opt: $t
),*
}
impl Options {
pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> u64 {
let mut sub_hashes = BTreeMap::new();
$({
hash_opt!($opt,
&self.$opt,
&mut sub_hashes,
for_crate_hash,
[$dep_tracking_marker]);
})*
let mut hasher = DefaultHasher::new();
dep_tracking::stable_hash(sub_hashes,
&mut hasher,
self.error_format,
for_crate_hash);
$({
hash_substruct!($opt,
&self.$opt,
self.error_format,
for_crate_hash,
&mut hasher,
[$dep_tracking_marker]);
})*
hasher.finish()
}
}
);
}
top_level_options!(
/// The top-level command-line options struct.
///
/// For each option, one has to specify how it behaves with regard to the
/// dependency tracking system of incremental compilation. This is done via the
/// square-bracketed directive after the field type. The options are:
///
/// - `[TRACKED]`
/// A change in the given field will cause the compiler to completely clear the
/// incremental compilation cache before proceeding.
///
/// - `[TRACKED_NO_CRATE_HASH]`
/// Same as `[TRACKED]`, but will not affect the crate hash. This is useful for options that only
/// affect the incremental cache.
///
/// - `[UNTRACKED]`
/// Incremental compilation is not influenced by this option.
///
/// - `[SUBSTRUCT]`
/// Second-level sub-structs containing more options.
///
/// If you add a new option to this struct or one of the sub-structs like
/// `CodegenOptions`, think about how it influences incremental compilation. If in
/// doubt, specify `[TRACKED]`, which is always "correct" but might lead to
/// unnecessary re-compilation.
#[rustc_lint_opt_ty]
pub struct Options {
/// The crate config requested for the session, which may be combined
/// with additional crate configurations during the compile process.
#[rustc_lint_opt_deny_field_access("use `Session::crate_types` instead of this field")]
crate_types: Vec<CrateType> [TRACKED],
optimize: OptLevel [TRACKED],
/// Include the `debug_assertions` flag in dependency tracking, since it
/// can influence whether overflow checks are done or not.
debug_assertions: bool [TRACKED],
debuginfo: DebugInfo [TRACKED],
debuginfo_compression: DebugInfoCompression [TRACKED],
lint_opts: Vec<(String, lint::Level)> [TRACKED_NO_CRATE_HASH],
lint_cap: Option<lint::Level> [TRACKED_NO_CRATE_HASH],
describe_lints: bool [UNTRACKED],
output_types: OutputTypes [TRACKED],
search_paths: Vec<SearchPath> [UNTRACKED],
libs: Vec<NativeLib> [TRACKED],
maybe_sysroot: Option<PathBuf> [UNTRACKED],
target_triple: TargetTriple [TRACKED],
test: bool [TRACKED],
error_format: ErrorOutputType [UNTRACKED],
diagnostic_width: Option<usize> [UNTRACKED],
/// If `Some`, enable incremental compilation, using the given
/// directory to store intermediate results.
incremental: Option<PathBuf> [UNTRACKED],
assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],
unstable_opts: UnstableOptions [SUBSTRUCT],
prints: Vec<PrintRequest> [UNTRACKED],
cg: CodegenOptions [SUBSTRUCT],
externs: Externs [UNTRACKED],
crate_name: Option<String> [TRACKED],
/// Indicates how the compiler should treat unstable features.
unstable_features: UnstableFeatures [TRACKED],
/// Indicates whether this run of the compiler is actually rustdoc. This
/// is currently just a hack and will be removed eventually, so please
/// try to not rely on this too much.
actually_rustdoc: bool [TRACKED],
/// Whether name resolver should resolve documentation links.
resolve_doc_links: ResolveDocLinks [TRACKED],
/// Control path trimming.
trimmed_def_paths: TrimmedDefPaths [TRACKED],
/// Specifications of codegen units / ThinLTO which are forced as a
/// result of parsing command line options. These are not necessarily
/// what rustc was invoked with, but massaged a bit to agree with
/// commands like `--emit llvm-ir` which they're often incompatible with
/// if we otherwise use the defaults of rustc.
#[rustc_lint_opt_deny_field_access("use `Session::codegen_units` instead of this field")]
cli_forced_codegen_units: Option<usize> [UNTRACKED],
#[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
cli_forced_local_thinlto_off: bool [UNTRACKED],
/// Remap source path prefixes in all output (messages, object files, debug, etc.).
remap_path_prefix: Vec<(PathBuf, PathBuf)> [TRACKED_NO_CRATE_HASH],
/// Base directory containing the `src/` for the Rust standard library, and
/// potentially `rustc` as well, if we can find it. Right now it's always
/// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
///
/// This directory is what the virtual `/rustc/$hash` is translated back to,
/// if Rust was built with path remapping to `/rustc/$hash` enabled
/// (the `rust.remap-debuginfo` option in `config.toml`).
real_rust_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
edition: Edition [TRACKED],
/// `true` if we're emitting JSON blobs about each artifact produced
/// by the compiler.
json_artifact_notifications: bool [TRACKED],
/// `true` if we're emitting a JSON blob containing the unused externs
json_unused_externs: JsonUnusedExterns [UNTRACKED],
/// `true` if we're emitting a JSON job containing a future-incompat report for lints
json_future_incompat: bool [TRACKED],
pretty: Option<PpMode> [UNTRACKED],
/// The (potentially remapped) working directory
working_dir: RealFileName [TRACKED],
color: ColorConfig [UNTRACKED],
}
);
/// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
/// macro is to define an interface that can be programmatically used by the option parser
/// to initialize the struct without hardcoding field names all over the place.
///
/// The goal is to invoke this macro once with the correct fields, and then this macro generates all
/// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
/// generated code to parse an option into its respective field in the struct. There are a few
/// hand-written parsers for parsing specific types of values in this module.
macro_rules! options {
($struct_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr,
$($( #[$attr:meta] )* $opt:ident : $t:ty = (
$init:expr,
$parse:ident,
[$dep_tracking_marker:ident],
$desc:expr)
),* ,) =>
(
#[derive(Clone)]
#[rustc_lint_opt_ty]
pub struct $struct_name { $( $( #[$attr] )* pub $opt: $t),* }
impl Default for $struct_name {
fn default() -> $struct_name {
$struct_name { $($opt: $init),* }
}
}
impl $struct_name {
pub fn build(
handler: &EarlyErrorHandler,
matches: &getopts::Matches,
) -> $struct_name {
build_options(handler, matches, $stat, $prefix, $outputname)
}
fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 {
let mut sub_hashes = BTreeMap::new();
$({
hash_opt!($opt,
&self.$opt,
&mut sub_hashes,
for_crate_hash,
[$dep_tracking_marker]);
})*
let mut hasher = DefaultHasher::new();
dep_tracking::stable_hash(sub_hashes,
&mut hasher,
error_format,
for_crate_hash
);
hasher.finish()
}
}
pub const $stat: OptionDescrs<$struct_name> =
&[ $( (stringify!($opt), $optmod::$opt, desc::$parse, $desc) ),* ];
mod $optmod {
$(
pub(super) fn $opt(cg: &mut super::$struct_name, v: Option<&str>) -> bool {
super::parse::$parse(&mut redirect_field!(cg.$opt), v)
}
)*
}
) }
impl CodegenOptions {
// JUSTIFICATION: defn of the suggested wrapper fn
#[allow(rustc::bad_opt_access)]
pub fn instrument_coverage(&self) -> InstrumentCoverage {
self.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
}
}
// Sometimes different options need to build a common structure.
// That structure can be kept in one of the options' fields, the others become dummy.
macro_rules! redirect_field {
($cg:ident.link_arg) => {
$cg.link_args
};
($cg:ident.pre_link_arg) => {
$cg.pre_link_args
};
($cg:ident.$field:ident) => {
$cg.$field
};
}
type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)];
fn build_options<O: Default>(
handler: &EarlyErrorHandler,
matches: &getopts::Matches,
descrs: OptionDescrs<O>,
prefix: &str,
outputname: &str,
) -> O {
let mut op = O::default();
for option in matches.opt_strs(prefix) {
let (key, value) = match option.split_once('=') {
None => (option, None),
Some((k, v)) => (k.to_string(), Some(v)),
};
let option_to_lookup = key.replace('-', "_");
match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
Some((_, setter, type_desc, _)) => {
if !setter(&mut op, value) {
match value {
None => handler.early_error(
format!(
"{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)"
),
),
Some(value) => handler.early_error(
format!(
"incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
),
),
}
}
}
None => handler.early_error(format!("unknown {outputname} option: `{key}`")),
}
}
return op;
}
#[allow(non_upper_case_globals)]
mod desc {
pub const parse_no_flag: &str = "no value";
pub const parse_bool: &str = "one of: `y`, `yes`, `on`, `true`, `n`, `no`, `off` or `false`";
pub const parse_opt_bool: &str = parse_bool;
pub const parse_string: &str = "a string";
pub const parse_opt_string: &str = parse_string;
pub const parse_string_push: &str = parse_string;
pub const parse_opt_langid: &str = "a language identifier";
pub const parse_opt_pathbuf: &str = "a path";
pub const parse_list: &str = "a space-separated list of strings";
pub const parse_list_with_polarity: &str =
"a comma-separated list of strings, with elements beginning with + or -";
pub const parse_opt_comma_list: &str = "a comma-separated list of strings";
pub const parse_number: &str = "a number";
pub const parse_opt_number: &str = parse_number;
pub const parse_threads: &str = parse_number;
pub const parse_time_passes_format: &str = "`text` (default) or `json`";
pub const parse_passes: &str = "a space-separated list of passes, or `all`";
pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
pub const parse_oom_strategy: &str = "either `panic` or `abort`";
pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
pub const parse_sanitizers: &str = "comma separated list of sanitizers: `address`, `cfi`, `hwaddress`, `kcfi`, `kernel-address`, `leak`, `memory`, `memtag`, `safestack`, `shadow-call-stack`, or `thread`";
pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
pub const parse_cfguard: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), `checks`, or `nochecks`";
pub const parse_cfprotection: &str = "`none`|`no`|`n` (default), `branch`, `return`, or `full`|`yes`|`y` (equivalent to `branch` and `return`)";
pub const parse_debuginfo: &str = "either an integer (0, 1, 2), `none`, `line-directives-only`, `line-tables-only`, `limited`, or `full`";
pub const parse_debuginfo_compression: &str = "one of `none`, `zlib`, or `zstd`";
pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
pub const parse_optimization_fuel: &str = "crate=integer";
pub const parse_mir_spanview: &str = "`statement` (default), `terminator`, or `block`";
pub const parse_dump_mono_stats: &str = "`markdown` (default) or `json`";
pub const parse_instrument_coverage: &str =
"`all` (default), `except-unused-generics`, `except-unused-functions`, or `off`";
pub const parse_instrument_xray: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or a comma separated list of settings: `always` or `never` (mutually exclusive), `ignore-loops`, `instruction-threshold=N`, `skip-entry`, `skip-exit`";
pub const parse_unpretty: &str = "`string` or `string=string`";
pub const parse_treat_err_as_bug: &str = "either no value or a non-negative number";
pub const parse_trait_solver: &str =
"one of the supported solver modes (`classic`, `next`, or `next-coherence`)";
pub const parse_lto: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
pub const parse_linker_plugin_lto: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
pub const parse_location_detail: &str = "either `none`, or a comma separated list of location details to track: `file`, `line`, or `column`";
pub const parse_switch_with_opt_path: &str =
"an optional path to the profiling data output directory";
pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
pub const parse_relocation_model: &str =
"one of supported relocation models (`rustc --print relocation-models`)";
pub const parse_code_model: &str = "one of supported code models (`rustc --print code-models`)";
pub const parse_tls_model: &str = "one of supported TLS models (`rustc --print tls-models`)";
pub const parse_target_feature: &str = parse_string;
pub const parse_terminal_url: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), or `auto`";
pub const parse_wasi_exec_model: &str = "either `command` or `reactor`";
pub const parse_split_debuginfo: &str =
"one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)";
pub const parse_split_dwarf_kind: &str =
"one of supported split dwarf modes (`split` or `single`)";
pub const parse_gcc_ld: &str = "one of: no value, `lld`";
pub const parse_link_self_contained: &str = "one of: `y`, `yes`, `on`, `n`, `no`, `off`, or a list of enabled (`+` prefix) and disabled (`-` prefix) \
components: `crto`, `libc`, `unwind`, `linker`, `sanitizers`, `mingw`";
pub const parse_stack_protector: &str =
"one of (`none` (default), `basic`, `strong`, or `all`)";
pub const parse_branch_protection: &str =
"a `,` separated combination of `bti`, `b-key`, `pac-ret`, or `leaf`";
pub const parse_proc_macro_execution_strategy: &str =
"one of supported execution strategies (`same-thread`, or `cross-thread`)";
pub const parse_dump_solver_proof_tree: &str = "one of: `always`, `on-request`, `on-error`";
}
mod parse {
pub(crate) use super::*;
use std::str::FromStr;
/// This is for boolean options that don't take a value and start with
/// `no-`. This style of option is deprecated.
pub(crate) fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool {
match v {
None => {
*slot = true;
true
}
Some(_) => false,
}
}
/// Use this for any boolean option that has a static default.
pub(crate) fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
match v {
Some("y") | Some("yes") | Some("on") | Some("true") | None => {
*slot = true;
true
}
Some("n") | Some("no") | Some("off") | Some("false") => {
*slot = false;
true
}
_ => false,
}
}
/// Use this for any boolean option that lacks a static default. (The
/// actions taken when such an option is not specified will depend on
/// other factors, such as other options, or target options.)
pub(crate) fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
match v {
Some("y") | Some("yes") | Some("on") | Some("true") | None => {
*slot = Some(true);
true
}
Some("n") | Some("no") | Some("off") | Some("false") => {
*slot = Some(false);
true
}
_ => false,
}
}
/// Use this for any string option that has a static default.
pub(crate) fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
match v {
Some(s) => {
*slot = s.to_string();
true
}
None => false,
}
}
/// Use this for any string option that lacks a static default.
pub(crate) fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
match v {
Some(s) => {
*slot = Some(s.to_string());
true
}
None => false,
}
}
/// Parse an optional language identifier, e.g. `en-US` or `zh-CN`.
pub(crate) fn parse_opt_langid(slot: &mut Option<LanguageIdentifier>, v: Option<&str>) -> bool {
match v {
Some(s) => {
*slot = rustc_errors::LanguageIdentifier::from_str(s).ok();
true
}
None => false,
}
}
pub(crate) fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
match v {
Some(s) => {
*slot = Some(PathBuf::from(s));
true
}
None => false,
}
}
pub(crate) fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
match v {
Some(s) => {
slot.push(s.to_string());
true
}
None => false,
}
}
pub(crate) fn parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
match v {
Some(s) => {
slot.extend(s.split_whitespace().map(|s| s.to_string()));
true
}
None => false,
}
}
pub(crate) fn parse_list_with_polarity(
slot: &mut Vec<(String, bool)>,
v: Option<&str>,
) -> bool {
match v {
Some(s) => {
for s in s.split(',') {
let Some(pass_name) = s.strip_prefix(&['+', '-'][..]) else { return false };
slot.push((pass_name.to_string(), &s[..1] == "+"));
}
true
}
None => false,
}
}
pub(crate) fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool {
if let Some(v) = v {
ld.line = false;
ld.file = false;
ld.column = false;
if v == "none" {
return true;
}
for s in v.split(',') {
match s {
"file" => ld.file = true,
"line" => ld.line = true,
"column" => ld.column = true,
_ => return false,
}
}
true
} else {
false
}
}
pub(crate) fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
match v {
Some(s) => {
let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
v.sort_unstable();
*slot = Some(v);
true
}
None => false,
}
}
pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
match v.and_then(|s| s.parse().ok()) {
Some(0) => {
*slot = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
true
}
Some(i) => {
*slot = i;
true
}
None => false,
}
}
/// Use this for any numeric option that has a static default.
pub(crate) fn parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool {
match v.and_then(|s| s.parse().ok()) {
Some(i) => {
*slot = i;
true
}
None => false,
}
}
/// Use this for any numeric option that lacks a static default.
pub(crate) fn parse_opt_number<T: Copy + FromStr>(
slot: &mut Option<T>,
v: Option<&str>,
) -> bool {
match v {
Some(s) => {
*slot = s.parse().ok();
slot.is_some()
}
None => false,
}
}
pub(crate) fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
match v {
Some("all") => {
*slot = Passes::All;
true
}
v => {
let mut passes = vec![];
if parse_list(&mut passes, v) {
slot.extend(passes);
true
} else {
false
}
}
}
}
pub(crate) fn parse_opt_panic_strategy(
slot: &mut Option<PanicStrategy>,
v: Option<&str>,
) -> bool {
match v {
Some("unwind") => *slot = Some(PanicStrategy::Unwind),
Some("abort") => *slot = Some(PanicStrategy::Abort),
_ => return false,
}
true
}
pub(crate) fn parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool {
match v {
Some("unwind") => *slot = PanicStrategy::Unwind,
Some("abort") => *slot = PanicStrategy::Abort,
_ => return false,
}
true
}
pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool {
match v {
Some("panic") => *slot = OomStrategy::Panic,
Some("abort") => *slot = OomStrategy::Abort,
_ => return false,
}
true
}
pub(crate) fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
match v {
Some(s) => match s.parse::<RelroLevel>() {
Ok(level) => *slot = Some(level),
_ => return false,
},
_ => return false,
}
true
}
pub(crate) fn parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool {
if let Some(v) = v {
for s in v.split(',') {
*slot |= match s {
"address" => SanitizerSet::ADDRESS,
"cfi" => SanitizerSet::CFI,
"kcfi" => SanitizerSet::KCFI,
"kernel-address" => SanitizerSet::KERNELADDRESS,
"leak" => SanitizerSet::LEAK,
"memory" => SanitizerSet::MEMORY,
"memtag" => SanitizerSet::MEMTAG,
"shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
"thread" => SanitizerSet::THREAD,
"hwaddress" => SanitizerSet::HWADDRESS,
"safestack" => SanitizerSet::SAFESTACK,
_ => return false,
}
}
true
} else {
false
}
}
pub(crate) fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
match v {
Some("2") | None => {
*slot = 2;
true
}
Some("1") => {
*slot = 1;
true
}
Some("0") => {
*slot = 0;
true
}
Some(_) => false,
}
}
pub(crate) fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
match v {
Some("none") => *slot = Strip::None,
Some("debuginfo") => *slot = Strip::Debuginfo,
Some("symbols") => *slot = Strip::Symbols,
_ => return false,
}
true
}
pub(crate) fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
if v.is_some() {
let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) {
*slot = if bool_arg.unwrap() { CFGuard::Checks } else { CFGuard::Disabled };
return true;
}
}
*slot = match v {
None => CFGuard::Checks,
Some("checks") => CFGuard::Checks,
Some("nochecks") => CFGuard::NoChecks,
Some(_) => return false,
};
true
}
pub(crate) fn parse_cfprotection(slot: &mut CFProtection, v: Option<&str>) -> bool {
if v.is_some() {
let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) {
*slot = if bool_arg.unwrap() { CFProtection::Full } else { CFProtection::None };
return true;
}
}
*slot = match v {
None | Some("none") => CFProtection::None,
Some("branch") => CFProtection::Branch,
Some("return") => CFProtection::Return,
Some("full") => CFProtection::Full,
Some(_) => return false,
};
true
}
pub(crate) fn parse_debuginfo(slot: &mut DebugInfo, v: Option<&str>) -> bool {
match v {
Some("0") | Some("none") => *slot = DebugInfo::None,
Some("line-directives-only") => *slot = DebugInfo::LineDirectivesOnly,
Some("line-tables-only") => *slot = DebugInfo::LineTablesOnly,
Some("1") | Some("limited") => *slot = DebugInfo::Limited,
Some("2") | Some("full") => *slot = DebugInfo::Full,
_ => return false,
}
true
}
pub(crate) fn parse_debuginfo_compression(
slot: &mut DebugInfoCompression,
v: Option<&str>,
) -> bool {
match v {
Some("none") => *slot = DebugInfoCompression::None,
Some("zlib") => *slot = DebugInfoCompression::Zlib,
Some("zstd") => *slot = DebugInfoCompression::Zstd,
_ => return false,
};
true
}
pub(crate) fn parse_linker_flavor(slot: &mut Option<LinkerFlavorCli>, v: Option<&str>) -> bool {
match v.and_then(LinkerFlavorCli::from_str) {
Some(lf) => *slot = Some(lf),
_ => return false,
}
true
}
pub(crate) fn parse_optimization_fuel(
slot: &mut Option<(String, u64)>,
v: Option<&str>,
) -> bool {
match v {
None => false,
Some(s) => {
let parts = s.split('=').collect::<Vec<_>>();
if parts.len() != 2 {
return false;
}
let crate_name = parts[0].to_string();
let fuel = parts[1].parse::<u64>();
if fuel.is_err() {
return false;
}
*slot = Some((crate_name, fuel.unwrap()));
true
}
}
}
pub(crate) fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
match v {
None => false,
Some(s) if s.split('=').count() <= 2 => {
*slot = Some(s.to_string());
true
}
_ => false,
}
}
pub(crate) fn parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>) -> bool {
if v.is_some() {
let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) {
*slot = bool_arg.unwrap().then_some(MirSpanview::Statement);
return true;
}
}
let Some(v) = v else {
*slot = Some(MirSpanview::Statement);
return true;
};
*slot = Some(match v.trim_end_matches('s') {
"statement" | "stmt" => MirSpanview::Statement,
"terminator" | "term" => MirSpanview::Terminator,
"block" | "basicblock" => MirSpanview::Block,
_ => return false,
});
true
}
pub(crate) fn parse_time_passes_format(slot: &mut TimePassesFormat, v: Option<&str>) -> bool {
match v {
None => true,
Some("json") => {
*slot = TimePassesFormat::Json;
true
}
Some("text") => {
*slot = TimePassesFormat::Text;
true
}
Some(_) => false,
}
}
pub(crate) fn parse_dump_mono_stats(slot: &mut DumpMonoStatsFormat, v: Option<&str>) -> bool {
match v {
None => true,
Some("json") => {
*slot = DumpMonoStatsFormat::Json;
true
}
Some("markdown") => {
*slot = DumpMonoStatsFormat::Markdown;
true
}
Some(_) => false,
}
}
pub(crate) fn parse_instrument_coverage(
slot: &mut Option<InstrumentCoverage>,
v: Option<&str>,
) -> bool {
if v.is_some() {
let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) {
*slot = bool_arg.unwrap().then_some(InstrumentCoverage::All);
return true;
}
}
let Some(v) = v else {
*slot = Some(InstrumentCoverage::All);
return true;
};
*slot = Some(match v {
"all" => InstrumentCoverage::All,
"except-unused-generics" | "except_unused_generics" => {
InstrumentCoverage::ExceptUnusedGenerics
}
"except-unused-functions" | "except_unused_functions" => {
InstrumentCoverage::ExceptUnusedFunctions
}
"off" | "no" | "n" | "false" | "0" => InstrumentCoverage::Off,
_ => return false,
});
true
}
pub(crate) fn parse_instrument_xray(
slot: &mut Option<InstrumentXRay>,
v: Option<&str>,
) -> bool {
if v.is_some() {
let mut bool_arg = None;
if parse_opt_bool(&mut bool_arg, v) {
*slot = if bool_arg.unwrap() { Some(InstrumentXRay::default()) } else { None };
return true;
}
}
let options = slot.get_or_insert_default();
let mut seen_always = false;
let mut seen_never = false;
let mut seen_ignore_loops = false;
let mut seen_instruction_threshold = false;
let mut seen_skip_entry = false;
let mut seen_skip_exit = false;
for option in v.into_iter().flat_map(|v| v.split(',')) {
match option {
"always" if !seen_always && !seen_never => {
options.always = true;
options.never = false;
seen_always = true;
}
"never" if !seen_never && !seen_always => {
options.never = true;
options.always = false;
seen_never = true;
}
"ignore-loops" if !seen_ignore_loops => {
options.ignore_loops = true;
seen_ignore_loops = true;
}
option
if option.starts_with("instruction-threshold")
&& !seen_instruction_threshold =>
{
let Some(("instruction-threshold", n)) = option.split_once('=') else {
return false;
};
match n.parse() {
Ok(n) => options.instruction_threshold = Some(n),
Err(_) => return false,
}
seen_instruction_threshold = true;
}
"skip-entry" if !seen_skip_entry => {
options.skip_entry = true;
seen_skip_entry = true;
}
"skip-exit" if !seen_skip_exit => {
options.skip_exit = true;
seen_skip_exit = true;
}
_ => return false,
}
}
true
}
pub(crate) fn parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool {
match v {
Some(s) => match s.parse() {
Ok(val) => {
*slot = Some(val);
true
}
Err(e) => {
*slot = None;
e.kind() == &IntErrorKind::Zero
}
},
None => {
*slot = NonZeroUsize::new(1);