-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
config.rs
3498 lines (3135 loc) · 120 KB
/
config.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
//! Contains infrastructure for configuring the compiler, including parsing
//! command-line options.
#![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
pub use crate::options::*;
use crate::errors::FileWriteFail;
use crate::search_paths::SearchPath;
use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind};
use crate::{filesearch, lint, HashStableContext};
use crate::{EarlyDiagCtxt, Session};
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
use rustc_data_structures::stable_hasher::{StableOrd, ToStableHashKey};
use rustc_errors::emitter::HumanReadableErrorType;
use rustc_errors::{ColorConfig, DiagArgValue, DiagCtxtFlags, IntoDiagArg};
use rustc_feature::UnstableFeatures;
use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION};
use rustc_span::source_map::FilePathMapping;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm};
use rustc_target::abi::Align;
use rustc_target::spec::LinkSelfContainedComponents;
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, SplitDebuginfo};
use rustc_target::spec::{Target, TargetTriple, TARGETS};
use std::collections::btree_map::{
Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter,
};
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::hash::Hash;
use std::iter;
use std::path::{Path, PathBuf};
use std::str::{self, FromStr};
use std::sync::LazyLock;
pub mod sigpipe;
/// The different settings that the `-C strip` flag can have.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum Strip {
/// Do not strip at all.
None,
/// Strip debuginfo.
Debuginfo,
/// Strip all symbols.
Symbols,
}
/// The different settings that the `-C control-flow-guard` flag can have.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum CFGuard {
/// Do not emit Control Flow Guard metadata or checks.
Disabled,
/// Emit Control Flow Guard metadata but no checks.
NoChecks,
/// Emit Control Flow Guard metadata and checks.
Checks,
}
/// The different settings that the `-Z cf-protection` flag can have.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum CFProtection {
/// Do not enable control-flow protection
None,
/// Emit control-flow protection for branches (enables indirect branch tracking).
Branch,
/// Emit control-flow protection for returns.
Return,
/// Emit control-flow protection for both branches and returns.
Full,
}
#[derive(Clone, Copy, Debug, PartialEq, Hash, HashStable_Generic)]
pub enum OptLevel {
No, // -O0
Less, // -O1
Default, // -O2
Aggressive, // -O3
Size, // -Os
SizeMin, // -Oz
}
/// This is what the `LtoCli` values get mapped to after resolving defaults and
/// and taking other command line options into account.
///
/// Note that linker plugin-based LTO is a different mechanism entirely.
#[derive(Clone, PartialEq)]
pub enum Lto {
/// Don't do any LTO whatsoever.
No,
/// Do a full-crate-graph (inter-crate) LTO with ThinLTO.
Thin,
/// Do a local ThinLTO (intra-crate, over the CodeGen Units of the local crate only). This is
/// only relevant if multiple CGUs are used.
ThinLocal,
/// Do a full-crate-graph (inter-crate) LTO with "fat" LTO.
Fat,
}
/// The different settings that the `-C lto` flag can have.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum LtoCli {
/// `-C lto=no`
No,
/// `-C lto=yes`
Yes,
/// `-C lto`
NoParam,
/// `-C lto=thin`
Thin,
/// `-C lto=fat`
Fat,
/// No `-C lto` flag passed
Unspecified,
}
/// The different settings that the `-C instrument-coverage` flag can have.
///
/// Coverage instrumentation now supports combining `-C instrument-coverage`
/// with compiler and linker optimization (enabled with `-O` or `-C opt-level=1`
/// and higher). Nevertheless, there are many variables, depending on options
/// selected, code structure, and enabled attributes. If errors are encountered,
/// either while compiling or when generating `llvm-cov show` reports, consider
/// lowering the optimization level, or including/excluding `-C link-dead-code`.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum InstrumentCoverage {
/// `-C instrument-coverage=no` (or `off`, `false` etc.)
No,
/// `-C instrument-coverage` or `-C instrument-coverage=yes`
Yes,
}
/// Individual flag values controlled by `-Z coverage-options`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct CoverageOptions {
/// Add branch coverage instrumentation.
pub branch: bool,
}
/// Settings for `-Z instrument-xray` flag.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct InstrumentXRay {
/// `-Z instrument-xray=always`, force instrumentation
pub always: bool,
/// `-Z instrument-xray=never`, disable instrumentation
pub never: bool,
/// `-Z instrument-xray=ignore-loops`, ignore presence of loops,
/// instrument functions based only on instruction count
pub ignore_loops: bool,
/// `-Z instrument-xray=instruction-threshold=N`, explicitly set instruction threshold
/// for instrumentation, or `None` to use compiler's default
pub instruction_threshold: Option<usize>,
/// `-Z instrument-xray=skip-entry`, do not instrument function entry
pub skip_entry: bool,
/// `-Z instrument-xray=skip-exit`, do not instrument function exit
pub skip_exit: bool,
}
#[derive(Clone, PartialEq, Hash, Debug)]
pub enum LinkerPluginLto {
LinkerPlugin(PathBuf),
LinkerPluginAuto,
Disabled,
}
impl LinkerPluginLto {
pub fn enabled(&self) -> bool {
match *self {
LinkerPluginLto::LinkerPlugin(_) | LinkerPluginLto::LinkerPluginAuto => true,
LinkerPluginLto::Disabled => false,
}
}
}
/// The different values `-C link-self-contained` can take: a list of individually enabled or
/// disabled components used during linking, coming from the rustc distribution, instead of being
/// found somewhere on the host system.
///
/// They can be set in bulk via `-C link-self-contained=yes|y|on` or `-C
/// link-self-contained=no|n|off`, and those boolean values are the historical defaults.
///
/// But each component is fine-grained, and can be unstably targeted, to use:
/// - some CRT objects
/// - the libc static library
/// - libgcc/libunwind libraries
/// - a linker we distribute
/// - some sanitizer runtime libraries
/// - all other MinGW libraries and Windows import libs
///
#[derive(Default, Clone, PartialEq, Debug)]
pub struct LinkSelfContained {
/// Whether the user explicitly set `-C link-self-contained` on or off, the historical values.
/// Used for compatibility with the existing opt-in and target inference.
pub explicitly_set: Option<bool>,
/// The components that are enabled on the CLI, using the `+component` syntax or one of the
/// `true` shorcuts.
enabled_components: LinkSelfContainedComponents,
/// The components that are disabled on the CLI, using the `-component` syntax or one of the
/// `false` shortcuts.
disabled_components: LinkSelfContainedComponents,
}
impl LinkSelfContained {
/// Incorporates an enabled or disabled component as specified on the CLI, if possible.
/// For example: `+linker`, and `-crto`.
pub(crate) fn handle_cli_component(&mut self, component: &str) -> Option<()> {
// Note that for example `-Cself-contained=y -Cself-contained=-linker` is not an explicit
// set of all values like `y` or `n` used to be. Therefore, if this flag had previously been
// set in bulk with its historical values, then manually setting a component clears that
// `explicitly_set` state.
if let Some(component_to_enable) = component.strip_prefix('+') {
self.explicitly_set = None;
self.enabled_components
.insert(LinkSelfContainedComponents::from_str(component_to_enable)?);
Some(())
} else if let Some(component_to_disable) = component.strip_prefix('-') {
self.explicitly_set = None;
self.disabled_components
.insert(LinkSelfContainedComponents::from_str(component_to_disable)?);
Some(())
} else {
None
}
}
/// Turns all components on or off and records that this was done explicitly for compatibility
/// purposes.
pub(crate) fn set_all_explicitly(&mut self, enabled: bool) {
self.explicitly_set = Some(enabled);
if enabled {
self.enabled_components = LinkSelfContainedComponents::all();
self.disabled_components = LinkSelfContainedComponents::empty();
} else {
self.enabled_components = LinkSelfContainedComponents::empty();
self.disabled_components = LinkSelfContainedComponents::all();
}
}
/// Helper creating a fully enabled `LinkSelfContained` instance. Used in tests.
pub fn on() -> Self {
let mut on = LinkSelfContained::default();
on.set_all_explicitly(true);
on
}
/// To help checking CLI usage while some of the values are unstable: returns whether one of the
/// components was set individually. This would also require the `-Zunstable-options` flag, to
/// be allowed.
fn are_unstable_variants_set(&self) -> bool {
let any_component_set =
!self.enabled_components.is_empty() || !self.disabled_components.is_empty();
self.explicitly_set.is_none() && any_component_set
}
/// Returns whether the self-contained linker component was enabled on the CLI, using the
/// `-C link-self-contained=+linker` syntax, or one of the `true` shorcuts.
pub fn is_linker_enabled(&self) -> bool {
self.enabled_components.contains(LinkSelfContainedComponents::LINKER)
}
/// Returns whether the self-contained linker component was disabled on the CLI, using the
/// `-C link-self-contained=-linker` syntax, or one of the `false` shorcuts.
pub fn is_linker_disabled(&self) -> bool {
self.disabled_components.contains(LinkSelfContainedComponents::LINKER)
}
/// Returns CLI inconsistencies to emit errors: individual components were both enabled and
/// disabled.
fn check_consistency(&self) -> Option<LinkSelfContainedComponents> {
if self.explicitly_set.is_some() {
None
} else {
let common = self.enabled_components.intersection(self.disabled_components);
if common.is_empty() { None } else { Some(common) }
}
}
}
/// Used with `-Z assert-incr-state`.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum IncrementalStateAssertion {
/// Found and loaded an existing session directory.
///
/// Note that this says nothing about whether any particular query
/// will be found to be red or green.
Loaded,
/// Did not load an existing session directory.
NotLoaded,
}
/// The different settings that can be enabled via the `-Z location-detail` flag.
#[derive(Copy, Clone, PartialEq, Hash, Debug)]
pub struct LocationDetail {
pub file: bool,
pub line: bool,
pub column: bool,
}
impl LocationDetail {
pub(crate) fn all() -> Self {
Self { file: true, line: true, column: true }
}
}
#[derive(Clone, PartialEq, Hash, Debug)]
pub enum SwitchWithOptPath {
Enabled(Option<PathBuf>),
Disabled,
}
impl SwitchWithOptPath {
pub fn enabled(&self) -> bool {
match *self {
SwitchWithOptPath::Enabled(_) => true,
SwitchWithOptPath::Disabled => false,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic)]
#[derive(Encodable, Decodable)]
pub enum SymbolManglingVersion {
Legacy,
V0,
Hashed,
}
#[derive(Clone, Copy, Debug, PartialEq, Hash)]
pub enum DebugInfo {
None,
LineDirectivesOnly,
LineTablesOnly,
Limited,
Full,
}
#[derive(Clone, Copy, Debug, PartialEq, Hash)]
pub enum DebugInfoCompression {
None,
Zlib,
Zstd,
}
impl ToString for DebugInfoCompression {
fn to_string(&self) -> String {
match self {
DebugInfoCompression::None => "none",
DebugInfoCompression::Zlib => "zlib",
DebugInfoCompression::Zstd => "zstd",
}
.to_owned()
}
}
/// Split debug-information is enabled by `-C split-debuginfo`, this enum is only used if split
/// debug-information is enabled (in either `Packed` or `Unpacked` modes), and the platform
/// uses DWARF for debug-information.
///
/// Some debug-information requires link-time relocation and some does not. LLVM can partition
/// the debuginfo into sections depending on whether or not it requires link-time relocation. Split
/// DWARF provides a mechanism which allows the linker to skip the sections which don't require
/// link-time relocation - either by putting those sections in DWARF object files, or by keeping
/// them in the object file in such a way that the linker will skip them.
#[derive(Clone, Copy, Debug, PartialEq, Hash)]
pub enum SplitDwarfKind {
/// Sections which do not require relocation are written into object file but ignored by the
/// linker.
Single,
/// Sections which do not require relocation are written into a DWARF object (`.dwo`) file
/// which is ignored by the linker.
Split,
}
impl FromStr for SplitDwarfKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
Ok(match s {
"single" => SplitDwarfKind::Single,
"split" => SplitDwarfKind::Split,
_ => return Err(()),
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, HashStable_Generic)]
#[derive(Encodable, Decodable)]
pub enum OutputType {
Bitcode,
Assembly,
LlvmAssembly,
Mir,
Metadata,
Object,
Exe,
DepInfo,
}
// Safety: Trivial C-Style enums have a stable sort order across compilation sessions.
unsafe impl StableOrd for OutputType {
const CAN_USE_UNSTABLE_SORT: bool = true;
}
impl<HCX: HashStableContext> ToStableHashKey<HCX> for OutputType {
type KeyType = Self;
fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
*self
}
}
impl OutputType {
fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
match *self {
OutputType::Exe | OutputType::DepInfo | OutputType::Metadata => true,
OutputType::Bitcode
| OutputType::Assembly
| OutputType::LlvmAssembly
| OutputType::Mir
| OutputType::Object => false,
}
}
pub fn shorthand(&self) -> &'static str {
match *self {
OutputType::Bitcode => "llvm-bc",
OutputType::Assembly => "asm",
OutputType::LlvmAssembly => "llvm-ir",
OutputType::Mir => "mir",
OutputType::Object => "obj",
OutputType::Metadata => "metadata",
OutputType::Exe => "link",
OutputType::DepInfo => "dep-info",
}
}
fn from_shorthand(shorthand: &str) -> Option<Self> {
Some(match shorthand {
"asm" => OutputType::Assembly,
"llvm-ir" => OutputType::LlvmAssembly,
"mir" => OutputType::Mir,
"llvm-bc" => OutputType::Bitcode,
"obj" => OutputType::Object,
"metadata" => OutputType::Metadata,
"link" => OutputType::Exe,
"dep-info" => OutputType::DepInfo,
_ => return None,
})
}
fn shorthands_display() -> String {
format!(
"`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
OutputType::Bitcode.shorthand(),
OutputType::Assembly.shorthand(),
OutputType::LlvmAssembly.shorthand(),
OutputType::Mir.shorthand(),
OutputType::Object.shorthand(),
OutputType::Metadata.shorthand(),
OutputType::Exe.shorthand(),
OutputType::DepInfo.shorthand(),
)
}
pub fn extension(&self) -> &'static str {
match *self {
OutputType::Bitcode => "bc",
OutputType::Assembly => "s",
OutputType::LlvmAssembly => "ll",
OutputType::Mir => "mir",
OutputType::Object => "o",
OutputType::Metadata => "rmeta",
OutputType::DepInfo => "d",
OutputType::Exe => "",
}
}
pub fn is_text_output(&self) -> bool {
match *self {
OutputType::Assembly
| OutputType::LlvmAssembly
| OutputType::Mir
| OutputType::DepInfo => true,
OutputType::Bitcode | OutputType::Object | OutputType::Metadata | OutputType::Exe => {
false
}
}
}
}
/// The type of diagnostics output to generate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorOutputType {
/// Output meant for the consumption of humans.
HumanReadable(HumanReadableErrorType),
/// Output that's consumed by other tools such as `rustfix` or the `RLS`.
Json {
/// Render the JSON in a human readable way (with indents and newlines).
pretty: bool,
/// The JSON output includes a `rendered` field that includes the rendered
/// human output.
json_rendered: HumanReadableErrorType,
},
}
impl Default for ErrorOutputType {
fn default() -> Self {
Self::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto))
}
}
#[derive(Clone, Hash, Debug)]
pub enum ResolveDocLinks {
/// Do not resolve doc links.
None,
/// Resolve doc links on exported items only for crate types that have metadata.
ExportedMetadata,
/// Resolve doc links on exported items.
Exported,
/// Resolve doc links on all items.
All,
}
/// Use tree-based collections to cheaply get a deterministic `Hash` implementation.
/// *Do not* switch `BTreeMap` out for an unsorted container type! That would break
/// dependency tracking for command-line arguments. Also only hash keys, since tracking
/// should only depend on the output types, not the paths they're written to.
#[derive(Clone, Debug, Hash, HashStable_Generic, Encodable, Decodable)]
pub struct OutputTypes(BTreeMap<OutputType, Option<OutFileName>>);
impl OutputTypes {
pub fn new(entries: &[(OutputType, Option<OutFileName>)]) -> OutputTypes {
OutputTypes(BTreeMap::from_iter(entries.iter().map(|&(k, ref v)| (k, v.clone()))))
}
pub(crate) fn get(&self, key: &OutputType) -> Option<&Option<OutFileName>> {
self.0.get(key)
}
pub fn contains_key(&self, key: &OutputType) -> bool {
self.0.contains_key(key)
}
/// Returns `true` if user specified a name and not just produced type
pub fn contains_explicit_name(&self, key: &OutputType) -> bool {
self.0.get(key).map_or(false, |f| f.is_some())
}
pub fn iter(&self) -> BTreeMapIter<'_, OutputType, Option<OutFileName>> {
self.0.iter()
}
pub fn keys(&self) -> BTreeMapKeysIter<'_, OutputType, Option<OutFileName>> {
self.0.keys()
}
pub fn values(&self) -> BTreeMapValuesIter<'_, OutputType, Option<OutFileName>> {
self.0.values()
}
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `true` if any of the output types require codegen or linking.
pub fn should_codegen(&self) -> bool {
self.0.keys().any(|k| match *k {
OutputType::Bitcode
| OutputType::Assembly
| OutputType::LlvmAssembly
| OutputType::Mir
| OutputType::Object
| OutputType::Exe => true,
OutputType::Metadata | OutputType::DepInfo => false,
})
}
/// Returns `true` if any of the output types require linking.
pub fn should_link(&self) -> bool {
self.0.keys().any(|k| match *k {
OutputType::Bitcode
| OutputType::Assembly
| OutputType::LlvmAssembly
| OutputType::Mir
| OutputType::Metadata
| OutputType::Object
| OutputType::DepInfo => false,
OutputType::Exe => true,
})
}
}
/// Use tree-based collections to cheaply get a deterministic `Hash` implementation.
/// *Do not* switch `BTreeMap` or `BTreeSet` out for an unsorted container type! That
/// would break dependency tracking for command-line arguments.
#[derive(Clone)]
pub struct Externs(BTreeMap<String, ExternEntry>);
#[derive(Clone, Debug)]
pub struct ExternEntry {
pub location: ExternLocation,
/// Indicates this is a "private" dependency for the
/// `exported_private_dependencies` lint.
///
/// This can be set with the `priv` option like
/// `--extern priv:name=foo.rlib`.
pub is_private_dep: bool,
/// Add the extern entry to the extern prelude.
///
/// This can be disabled with the `noprelude` option like
/// `--extern noprelude:name`.
pub add_prelude: bool,
/// The extern entry shouldn't be considered for unused dependency warnings.
///
/// `--extern nounused:std=/path/to/lib/libstd.rlib`. This is used to
/// suppress `unused-crate-dependencies` warnings.
pub nounused_dep: bool,
/// If the extern entry is not referenced in the crate, force it to be resolved anyway.
///
/// Allows a dependency satisfying, for instance, a missing panic handler to be injected
/// without modifying source:
/// `--extern force:extras=/path/to/lib/libstd.rlib`
pub force: bool,
}
#[derive(Clone, Debug)]
pub enum ExternLocation {
/// Indicates to look for the library in the search paths.
///
/// Added via `--extern name`.
FoundInLibrarySearchDirectories,
/// The locations where this extern entry must be found.
///
/// The `CrateLoader` is responsible for loading these and figuring out
/// which one to use.
///
/// Added via `--extern prelude_name=some_file.rlib`
ExactPaths(BTreeSet<CanonicalizedPath>),
}
impl Externs {
/// Used for testing.
pub fn new(data: BTreeMap<String, ExternEntry>) -> Externs {
Externs(data)
}
pub fn get(&self, key: &str) -> Option<&ExternEntry> {
self.0.get(key)
}
pub fn iter(&self) -> BTreeMapIter<'_, String, ExternEntry> {
self.0.iter()
}
}
impl ExternEntry {
fn new(location: ExternLocation) -> ExternEntry {
ExternEntry {
location,
is_private_dep: false,
add_prelude: false,
nounused_dep: false,
force: false,
}
}
pub fn files(&self) -> Option<impl Iterator<Item = &CanonicalizedPath>> {
match &self.location {
ExternLocation::ExactPaths(set) => Some(set.iter()),
_ => None,
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct PrintRequest {
pub kind: PrintKind,
pub out: OutFileName,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PrintKind {
FileNames,
Sysroot,
TargetLibdir,
CrateName,
Cfg,
CallingConventions,
TargetList,
TargetCPUs,
TargetFeatures,
RelocationModels,
CodeModels,
TlsModels,
TargetSpec,
AllTargetSpecs,
NativeStaticLibs,
StackProtectorStrategies,
LinkArgs,
SplitDebuginfo,
DeploymentTarget,
}
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct NextSolverConfig {
/// Whether the new trait solver should be enabled in coherence.
pub coherence: bool,
/// Whether the new trait solver should be enabled everywhere.
/// This is only `true` if `coherence` is also enabled.
pub globally: bool,
/// Whether to dump proof trees after computing a proof tree.
pub dump_tree: DumpSolverProofTree,
}
#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum DumpSolverProofTree {
Always,
OnError,
#[default]
Never,
}
pub enum Input {
/// Load source code from a file.
File(PathBuf),
/// Load source code from a string.
Str {
/// A string that is shown in place of a filename.
name: FileName,
/// An anonymous string containing the source code.
input: String,
},
}
impl Input {
pub fn filestem(&self) -> &str {
match *self {
Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
Input::Str { .. } => "rust_out",
}
}
pub fn source_name(&self) -> FileName {
match *self {
Input::File(ref ifile) => ifile.clone().into(),
Input::Str { ref name, .. } => name.clone(),
}
}
pub fn opt_path(&self) -> Option<&Path> {
match self {
Input::File(file) => Some(file),
Input::Str { name, .. } => match name {
FileName::Real(real) => real.local_path(),
FileName::QuoteExpansion(_) => None,
FileName::Anon(_) => None,
FileName::MacroExpansion(_) => None,
FileName::ProcMacroSourceCode(_) => None,
FileName::CliCrateAttr(_) => None,
FileName::Custom(_) => None,
FileName::DocTest(path, _) => Some(path),
FileName::InlineAsm(_) => None,
},
}
}
}
#[derive(Clone, Hash, Debug, HashStable_Generic, PartialEq, Encodable, Decodable)]
pub enum OutFileName {
Real(PathBuf),
Stdout,
}
impl OutFileName {
pub fn parent(&self) -> Option<&Path> {
match *self {
OutFileName::Real(ref path) => path.parent(),
OutFileName::Stdout => None,
}
}
pub fn filestem(&self) -> Option<&OsStr> {
match *self {
OutFileName::Real(ref path) => path.file_stem(),
OutFileName::Stdout => Some(OsStr::new("stdout")),
}
}
pub fn is_stdout(&self) -> bool {
match *self {
OutFileName::Real(_) => false,
OutFileName::Stdout => true,
}
}
pub fn is_tty(&self) -> bool {
use std::io::IsTerminal;
match *self {
OutFileName::Real(_) => false,
OutFileName::Stdout => std::io::stdout().is_terminal(),
}
}
pub fn as_path(&self) -> &Path {
match *self {
OutFileName::Real(ref path) => path.as_ref(),
OutFileName::Stdout => Path::new("stdout"),
}
}
/// For a given output filename, return the actual name of the file that
/// can be used to write codegen data of type `flavor`. For real-path
/// output filenames, this would be trivial as we can just use the path.
/// Otherwise for stdout, return a temporary path so that the codegen data
/// may be later copied to stdout.
pub fn file_for_writing(
&self,
outputs: &OutputFilenames,
flavor: OutputType,
codegen_unit_name: Option<&str>,
) -> PathBuf {
match *self {
OutFileName::Real(ref path) => path.clone(),
OutFileName::Stdout => outputs.temp_path(flavor, codegen_unit_name),
}
}
pub fn overwrite(&self, content: &str, sess: &Session) {
match self {
OutFileName::Stdout => print!("{content}"),
OutFileName::Real(path) => {
if let Err(e) = fs::write(path, content) {
sess.dcx().emit_fatal(FileWriteFail { path, err: e.to_string() });
}
}
}
}
}
#[derive(Clone, Hash, Debug, HashStable_Generic, Encodable, Decodable)]
pub struct OutputFilenames {
pub(crate) out_directory: PathBuf,
/// Crate name. Never contains '-'.
crate_stem: String,
/// Typically based on `.rs` input file name. Any '-' is preserved.
filestem: String,
pub single_output_file: Option<OutFileName>,
temps_directory: Option<PathBuf>,
pub outputs: OutputTypes,
}
pub const RLINK_EXT: &str = "rlink";
pub const RUST_CGU_EXT: &str = "rcgu";
pub const DWARF_OBJECT_EXT: &str = "dwo";
impl OutputFilenames {
pub fn new(
out_directory: PathBuf,
out_crate_name: String,
out_filestem: String,
single_output_file: Option<OutFileName>,
temps_directory: Option<PathBuf>,
extra: String,
outputs: OutputTypes,
) -> Self {
OutputFilenames {
out_directory,
single_output_file,
temps_directory,
outputs,
crate_stem: format!("{out_crate_name}{extra}"),
filestem: format!("{out_filestem}{extra}"),
}
}
pub fn path(&self, flavor: OutputType) -> OutFileName {
self.outputs
.get(&flavor)
.and_then(|p| p.to_owned())
.or_else(|| self.single_output_file.clone())
.unwrap_or_else(|| OutFileName::Real(self.output_path(flavor)))
}
/// Gets the output path where a compilation artifact of the given type
/// should be placed on disk.
fn output_path(&self, flavor: OutputType) -> PathBuf {
let extension = flavor.extension();
match flavor {
OutputType::Metadata => {
self.out_directory.join(format!("lib{}.{}", self.crate_stem, extension))
}
_ => self.with_directory_and_extension(&self.out_directory, extension),
}
}
/// Gets the path where a compilation artifact of the given type for the
/// given codegen unit should be placed on disk. If codegen_unit_name is
/// None, a path distinct from those of any codegen unit will be generated.
pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
let extension = flavor.extension();
self.temp_path_ext(extension, codegen_unit_name)
}
/// Like `temp_path`, but specifically for dwarf objects.
pub fn temp_path_dwo(&self, codegen_unit_name: Option<&str>) -> PathBuf {
self.temp_path_ext(DWARF_OBJECT_EXT, codegen_unit_name)
}
/// Like `temp_path`, but also supports things where there is no corresponding
/// OutputType, like noopt-bitcode or lto-bitcode.
pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
let mut extension = String::new();
if let Some(codegen_unit_name) = codegen_unit_name {
extension.push_str(codegen_unit_name);
}
if !ext.is_empty() {
if !extension.is_empty() {
extension.push('.');
extension.push_str(RUST_CGU_EXT);
extension.push('.');
}
extension.push_str(ext);
}
let temps_directory = self.temps_directory.as_ref().unwrap_or(&self.out_directory);
self.with_directory_and_extension(temps_directory, &extension)
}
pub fn with_extension(&self, extension: &str) -> PathBuf {
self.with_directory_and_extension(&self.out_directory, extension)
}
fn with_directory_and_extension(&self, directory: &PathBuf, extension: &str) -> PathBuf {
let mut path = directory.join(&self.filestem);
path.set_extension(extension);
path
}
/// Returns the path for the Split DWARF file - this can differ depending on which Split DWARF
/// mode is being used, which is the logic that this function is intended to encapsulate.
pub fn split_dwarf_path(
&self,
split_debuginfo_kind: SplitDebuginfo,
split_dwarf_kind: SplitDwarfKind,
cgu_name: Option<&str>,
) -> Option<PathBuf> {
let obj_out = self.temp_path(OutputType::Object, cgu_name);
let dwo_out = self.temp_path_dwo(cgu_name);
match (split_debuginfo_kind, split_dwarf_kind) {
(SplitDebuginfo::Off, SplitDwarfKind::Single | SplitDwarfKind::Split) => None,
// Single mode doesn't change how DWARF is emitted, but does add Split DWARF attributes
// (pointing at the path which is being determined here). Use the path to the current
// object file.
(SplitDebuginfo::Packed | SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => {
Some(obj_out)
}
// Split mode emits the DWARF into a different file, use that path.
(SplitDebuginfo::Packed | SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => {
Some(dwo_out)
}
}
}
}
bitflags::bitflags! {
/// Scopes used to determined if it need to apply to --remap-path-prefix
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct RemapPathScopeComponents: u8 {
/// Apply remappings to the expansion of std::file!() macro
const MACRO = 1 << 0;
/// Apply remappings to printed compiler diagnostics
const DIAGNOSTICS = 1 << 1;
/// Apply remappings to debug informations
const DEBUGINFO = 1 << 3;
/// An alias for `macro` and `debuginfo`. This ensures all paths in compiled
/// executables or libraries are remapped but not elsewhere.
const OBJECT = Self::MACRO.bits() | Self::DEBUGINFO.bits();
}
}