forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathty.rs
More file actions
1657 lines (1406 loc) · 42.6 KB
/
ty.rs
File metadata and controls
1657 lines (1406 loc) · 42.6 KB
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 std::fmt::{self, Debug, Display, Formatter};
use std::ops::Range;
use serde::Serialize;
use super::abi::ReprOptions;
use super::mir::{Body, Mutability, Safety};
use super::{DefId, Error, Symbol, with};
use crate::abi::{FnAbi, Layout};
use crate::crate_def::{CrateDef, CrateDefItems, CrateDefType};
use crate::mir::alloc::{AllocId, read_target_int, read_target_uint};
use crate::mir::mono::StaticDef;
use crate::target::MachineInfo;
use crate::{Filename, IndexedVal, Opaque, ThreadLocalIndex};
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Ty(usize, ThreadLocalIndex);
impl Debug for Ty {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Ty").field("id", &self.0).field("kind", &self.kind()).finish()
}
}
/// Constructors for `Ty`.
impl Ty {
/// Create a new type from a given kind.
pub fn from_rigid_kind(kind: RigidTy) -> Ty {
with(|cx| cx.new_rigid_ty(kind))
}
/// Create a new array type.
pub fn try_new_array(elem_ty: Ty, size: u64) -> Result<Ty, Error> {
Ok(Ty::from_rigid_kind(RigidTy::Array(elem_ty, TyConst::try_from_target_usize(size)?)))
}
/// Create a new array type from Const length.
pub fn new_array_with_const_len(elem_ty: Ty, len: TyConst) -> Ty {
Ty::from_rigid_kind(RigidTy::Array(elem_ty, len))
}
/// Create a new pointer type.
pub fn new_ptr(pointee_ty: Ty, mutability: Mutability) -> Ty {
Ty::from_rigid_kind(RigidTy::RawPtr(pointee_ty, mutability))
}
/// Create a new reference type.
pub fn new_ref(reg: Region, pointee_ty: Ty, mutability: Mutability) -> Ty {
Ty::from_rigid_kind(RigidTy::Ref(reg, pointee_ty, mutability))
}
/// Create a new pointer type.
pub fn new_tuple(tys: &[Ty]) -> Ty {
Ty::from_rigid_kind(RigidTy::Tuple(Vec::from(tys)))
}
/// Create a new closure type.
pub fn new_closure(def: ClosureDef, args: GenericArgs) -> Ty {
Ty::from_rigid_kind(RigidTy::Closure(def, args))
}
/// Create a new coroutine type.
pub fn new_coroutine(def: CoroutineDef, args: GenericArgs) -> Ty {
Ty::from_rigid_kind(RigidTy::Coroutine(def, args))
}
/// Create a new closure type.
pub fn new_coroutine_closure(def: CoroutineClosureDef, args: GenericArgs) -> Ty {
Ty::from_rigid_kind(RigidTy::CoroutineClosure(def, args))
}
/// Create a new box type that represents `Box<T>`, for the given inner type `T`.
pub fn new_box(inner_ty: Ty) -> Ty {
with(|cx| cx.new_box_ty(inner_ty))
}
/// Create a type representing `usize`.
pub fn usize_ty() -> Ty {
Ty::from_rigid_kind(RigidTy::Uint(UintTy::Usize))
}
/// Create a type representing `bool`.
pub fn bool_ty() -> Ty {
Ty::from_rigid_kind(RigidTy::Bool)
}
/// Create a type representing a signed integer.
pub fn signed_ty(inner: IntTy) -> Ty {
Ty::from_rigid_kind(RigidTy::Int(inner))
}
/// Create a type representing an unsigned integer.
pub fn unsigned_ty(inner: UintTy) -> Ty {
Ty::from_rigid_kind(RigidTy::Uint(inner))
}
/// Get a type layout.
pub fn layout(self) -> Result<Layout, Error> {
with(|cx| cx.ty_layout(self))
}
}
impl Ty {
pub fn kind(&self) -> TyKind {
with(|context| context.ty_kind(*self))
}
}
/// Represents a pattern in the type system
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum Pattern {
Range { start: Option<TyConst>, end: Option<TyConst>, include_end: bool },
}
/// Represents a constant in the type system
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct TyConst {
pub(crate) kind: TyConstKind,
pub id: TyConstId,
}
impl TyConst {
pub fn new(kind: TyConstKind, id: TyConstId) -> TyConst {
Self { kind, id }
}
/// Retrieve the constant kind.
pub fn kind(&self) -> &TyConstKind {
&self.kind
}
/// Creates an interned usize constant.
pub fn try_from_target_usize(val: u64) -> Result<Self, Error> {
with(|cx| cx.try_new_ty_const_uint(val.into(), UintTy::Usize))
}
/// Try to evaluate to a target `usize`.
pub fn eval_target_usize(&self) -> Result<u64, Error> {
with(|cx| cx.eval_target_usize_ty(self))
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub enum TyConstKind {
Param(ParamConst),
Bound(DebruijnIndex, BoundVar),
Unevaluated(ConstDef, GenericArgs),
// FIXME: These should be a valtree
Value(Ty, Allocation),
ZSTValue(Ty),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct TyConstId(usize, ThreadLocalIndex);
/// Represents a constant in MIR
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct MirConst {
/// The constant kind.
pub(crate) kind: ConstantKind,
/// The constant type.
pub(crate) ty: Ty,
/// Used for internal tracking of the internal constant.
pub id: MirConstId,
}
impl MirConst {
/// Build a constant. Note that this should only be used by the compiler.
pub fn new(kind: ConstantKind, ty: Ty, id: MirConstId) -> MirConst {
MirConst { kind, ty, id }
}
/// Retrieve the constant kind.
pub fn kind(&self) -> &ConstantKind {
&self.kind
}
/// Get the constant type.
pub fn ty(&self) -> Ty {
self.ty
}
/// Try to evaluate to a target `usize`.
pub fn eval_target_usize(&self) -> Result<u64, Error> {
with(|cx| cx.eval_target_usize(self))
}
/// Create a constant that represents a new zero-sized constant of type T.
/// Fails if the type is not a ZST or if it doesn't have a known size.
pub fn try_new_zero_sized(ty: Ty) -> Result<MirConst, Error> {
with(|cx| cx.try_new_const_zst(ty))
}
/// Build a new constant that represents the given string.
///
/// Note that there is no guarantee today about duplication of the same constant.
/// I.e.: Calling this function multiple times with the same argument may or may not return
/// the same allocation.
pub fn from_str(value: &str) -> MirConst {
with(|cx| cx.new_const_str(value))
}
/// Build a new constant that represents the given boolean value.
pub fn from_bool(value: bool) -> MirConst {
with(|cx| cx.new_const_bool(value))
}
/// Build a new constant that represents the given unsigned integer.
pub fn try_from_uint(value: u128, uint_ty: UintTy) -> Result<MirConst, Error> {
with(|cx| cx.try_new_const_uint(value, uint_ty))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MirConstId(usize, ThreadLocalIndex);
type Ident = Opaque;
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct Region {
pub kind: RegionKind,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub enum RegionKind {
ReEarlyParam(EarlyParamRegion),
ReBound(DebruijnIndex, BoundRegion),
ReStatic,
RePlaceholder(Placeholder<BoundRegion>),
ReErased,
}
pub(crate) type DebruijnIndex = u32;
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct EarlyParamRegion {
pub index: u32,
pub name: Symbol,
}
pub(crate) type BoundVar = u32;
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct BoundRegion {
pub var: BoundVar,
pub kind: BoundRegionKind,
}
pub(crate) type UniverseIndex = u32;
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct Placeholder<T> {
pub universe: UniverseIndex,
pub bound: T,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Span(usize, ThreadLocalIndex);
impl Debug for Span {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Span")
.field("id", &self.0)
.field("repr", &with(|cx| cx.span_to_string(*self)))
.finish()
}
}
impl Span {
/// Return filename for diagnostic purposes
pub fn get_filename(&self) -> Filename {
with(|c| c.get_filename(self))
}
/// Return lines that correspond to this `Span`
pub fn get_lines(&self) -> LineInfo {
with(|c| c.get_lines(self))
}
/// Return the span location to be printed in diagnostic messages.
///
/// This may leak local file paths and should not be used to build artifacts that may be
/// distributed.
pub fn diagnostic(&self) -> String {
with(|c| c.span_to_string(*self))
}
}
#[derive(Clone, Copy, Debug, Serialize)]
/// Information you get from `Span` in a struct form.
/// Line and col start from 1.
pub struct LineInfo {
pub start_line: usize,
pub start_col: usize,
pub end_line: usize,
pub end_col: usize,
}
impl LineInfo {
pub fn from(lines: (usize, usize, usize, usize)) -> Self {
LineInfo { start_line: lines.0, start_col: lines.1, end_line: lines.2, end_col: lines.3 }
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum TyKind {
RigidTy(RigidTy),
Alias(AliasKind, AliasTy),
Param(ParamTy),
Bound(usize, BoundTy),
}
impl TyKind {
pub fn rigid(&self) -> Option<&RigidTy> {
if let TyKind::RigidTy(inner) = self { Some(inner) } else { None }
}
#[inline]
pub fn is_unit(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Tuple(data)) if data.is_empty())
}
#[inline]
pub fn is_bool(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Bool))
}
#[inline]
pub fn is_char(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Char))
}
#[inline]
pub fn is_trait(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Dynamic(_, _)))
}
#[inline]
pub fn is_enum(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.kind() == AdtKind::Enum)
}
#[inline]
pub fn is_struct(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.kind() == AdtKind::Struct)
}
#[inline]
pub fn is_union(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.kind() == AdtKind::Union)
}
#[inline]
pub fn is_adt(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Adt(..)))
}
#[inline]
pub fn is_ref(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Ref(..)))
}
#[inline]
pub fn is_fn(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::FnDef(..)))
}
#[inline]
pub fn is_fn_ptr(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::FnPtr(..)))
}
#[inline]
pub fn is_primitive(&self) -> bool {
matches!(
self,
TyKind::RigidTy(
RigidTy::Bool
| RigidTy::Char
| RigidTy::Int(_)
| RigidTy::Uint(_)
| RigidTy::Float(_)
)
)
}
#[inline]
pub fn is_float(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Float(_)))
}
#[inline]
pub fn is_integral(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Int(_) | RigidTy::Uint(_)))
}
#[inline]
pub fn is_numeric(&self) -> bool {
self.is_integral() || self.is_float()
}
#[inline]
pub fn is_signed(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Int(_)))
}
#[inline]
pub fn is_str(&self) -> bool {
*self == TyKind::RigidTy(RigidTy::Str)
}
#[inline]
pub fn is_cstr(&self) -> bool {
let TyKind::RigidTy(RigidTy::Adt(def, _)) = self else {
return false;
};
with(|cx| cx.adt_is_cstr(*def))
}
#[inline]
pub fn is_slice(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Slice(_)))
}
#[inline]
pub fn is_array(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Array(..)))
}
#[inline]
pub fn is_mutable_ptr(&self) -> bool {
matches!(
self,
TyKind::RigidTy(RigidTy::RawPtr(_, Mutability::Mut))
| TyKind::RigidTy(RigidTy::Ref(_, _, Mutability::Mut))
)
}
#[inline]
pub fn is_raw_ptr(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::RawPtr(..)))
}
/// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
#[inline]
pub fn is_any_ptr(&self) -> bool {
self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
}
#[inline]
pub fn is_coroutine(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Coroutine(..)))
}
#[inline]
pub fn is_closure(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Closure(..)))
}
#[inline]
pub fn is_box(&self) -> bool {
match self {
TyKind::RigidTy(RigidTy::Adt(def, _)) => def.is_box(),
_ => false,
}
}
#[inline]
pub fn is_simd(&self) -> bool {
matches!(self, TyKind::RigidTy(RigidTy::Adt(def, _)) if def.is_simd())
}
pub fn trait_principal(&self) -> Option<Binder<ExistentialTraitRef>> {
if let TyKind::RigidTy(RigidTy::Dynamic(predicates, _)) = self {
if let Some(Binder { value: ExistentialPredicate::Trait(trait_ref), bound_vars }) =
predicates.first()
{
Some(Binder { value: trait_ref.clone(), bound_vars: bound_vars.clone() })
} else {
None
}
} else {
None
}
}
/// Returns the type of `ty[i]` for builtin types.
pub fn builtin_index(&self) -> Option<Ty> {
match self.rigid()? {
RigidTy::Array(ty, _) | RigidTy::Slice(ty) => Some(*ty),
_ => None,
}
}
/// Returns the type and mutability of `*ty` for builtin types.
///
/// The parameter `explicit` indicates if this is an *explicit* dereference.
/// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut> {
match self.rigid()? {
RigidTy::Adt(def, args) if def.is_box() => {
Some(TypeAndMut { ty: *args.0.first()?.ty()?, mutability: Mutability::Not })
}
RigidTy::Ref(_, ty, mutability) => {
Some(TypeAndMut { ty: *ty, mutability: *mutability })
}
RigidTy::RawPtr(ty, mutability) if explicit => {
Some(TypeAndMut { ty: *ty, mutability: *mutability })
}
_ => None,
}
}
/// Get the function signature for function like types (Fn, FnPtr, and Closure)
pub fn fn_sig(&self) -> Option<PolyFnSig> {
match self {
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Some(with(|cx| cx.fn_sig(*def, args))),
TyKind::RigidTy(RigidTy::FnPtr(sig)) => Some(sig.clone()),
TyKind::RigidTy(RigidTy::Closure(_def, args)) => Some(with(|cx| cx.closure_sig(args))),
_ => None,
}
}
/// Get the discriminant type for this type.
pub fn discriminant_ty(&self) -> Option<Ty> {
self.rigid().map(|ty| with(|cx| cx.rigid_ty_discriminant_ty(ty)))
}
/// Deconstruct a function type if this is one.
pub fn fn_def(&self) -> Option<(FnDef, &GenericArgs)> {
if let TyKind::RigidTy(RigidTy::FnDef(def, args)) = self {
Some((*def, args))
} else {
None
}
}
}
pub struct TypeAndMut {
pub ty: Ty,
pub mutability: Mutability,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum RigidTy {
Bool,
Char,
Int(IntTy),
Uint(UintTy),
Float(FloatTy),
Adt(AdtDef, GenericArgs),
Foreign(ForeignDef),
Str,
Array(Ty, TyConst),
Pat(Ty, Pattern),
Slice(Ty),
RawPtr(Ty, Mutability),
Ref(Region, Ty, Mutability),
FnDef(FnDef, GenericArgs),
FnPtr(PolyFnSig),
Closure(ClosureDef, GenericArgs),
Coroutine(CoroutineDef, GenericArgs),
CoroutineClosure(CoroutineClosureDef, GenericArgs),
Dynamic(Vec<Binder<ExistentialPredicate>>, Region),
Never,
Tuple(Vec<Ty>),
CoroutineWitness(CoroutineWitnessDef, GenericArgs),
}
impl RigidTy {
/// Get the discriminant type for this type.
pub fn discriminant_ty(&self) -> Ty {
with(|cx| cx.rigid_ty_discriminant_ty(self))
}
}
impl From<RigidTy> for TyKind {
fn from(value: RigidTy) -> Self {
TyKind::RigidTy(value)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum IntTy {
Isize,
I8,
I16,
I32,
I64,
I128,
}
impl IntTy {
pub fn num_bytes(self) -> usize {
match self {
IntTy::Isize => MachineInfo::target_pointer_width().bytes(),
IntTy::I8 => 1,
IntTy::I16 => 2,
IntTy::I32 => 4,
IntTy::I64 => 8,
IntTy::I128 => 16,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum UintTy {
Usize,
U8,
U16,
U32,
U64,
U128,
}
impl UintTy {
pub fn num_bytes(self) -> usize {
match self {
UintTy::Usize => MachineInfo::target_pointer_width().bytes(),
UintTy::U8 => 1,
UintTy::U16 => 2,
UintTy::U32 => 4,
UintTy::U64 => 8,
UintTy::U128 => 16,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum FloatTy {
F16,
F32,
F64,
F128,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum Movability {
Static,
Movable,
}
crate_def! {
#[derive(Serialize)]
pub ForeignModuleDef;
}
impl ForeignModuleDef {
pub fn module(&self) -> ForeignModule {
with(|cx| cx.foreign_module(*self))
}
}
pub struct ForeignModule {
pub def_id: ForeignModuleDef,
pub abi: Abi,
}
impl ForeignModule {
pub fn items(&self) -> Vec<ForeignDef> {
with(|cx| cx.foreign_items(self.def_id))
}
}
crate_def_with_ty! {
/// Hold information about a ForeignItem in a crate.
#[derive(Serialize)]
pub ForeignDef;
}
impl ForeignDef {
pub fn kind(&self) -> ForeignItemKind {
with(|cx| cx.foreign_item_kind(*self))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)]
pub enum ForeignItemKind {
Fn(FnDef),
Static(StaticDef),
Type(Ty),
}
crate_def_with_ty! {
/// Hold information about a function definition in a crate.
#[derive(Serialize)]
pub FnDef;
}
impl FnDef {
// Get the function body if available.
pub fn body(&self) -> Option<Body> {
with(|ctx| ctx.has_body(self.0).then(|| ctx.mir_body(self.0)))
}
// Check if the function body is available.
pub fn has_body(&self) -> bool {
with(|ctx| ctx.has_body(self.0))
}
/// Get the information of the intrinsic if this function is a definition of one.
pub fn as_intrinsic(&self) -> Option<IntrinsicDef> {
with(|cx| cx.intrinsic(self.def_id()))
}
/// Check if the function is an intrinsic.
#[inline]
pub fn is_intrinsic(&self) -> bool {
self.as_intrinsic().is_some()
}
/// Get the function signature for this function definition.
pub fn fn_sig(&self) -> PolyFnSig {
let kind = self.ty().kind();
kind.fn_sig().unwrap()
}
}
crate_def_with_ty! {
#[derive(Serialize)]
pub IntrinsicDef;
}
impl IntrinsicDef {
/// Returns the plain name of the intrinsic.
/// e.g., `transmute` for `core::intrinsics::transmute`.
pub fn fn_name(&self) -> Symbol {
with(|cx| cx.intrinsic_name(*self))
}
/// Returns whether the intrinsic has no meaningful body and all backends
/// need to shim all calls to it.
pub fn must_be_overridden(&self) -> bool {
with(|cx| !cx.has_body(self.0))
}
}
impl From<IntrinsicDef> for FnDef {
fn from(def: IntrinsicDef) -> Self {
FnDef(def.0)
}
}
crate_def! {
#[derive(Serialize)]
pub ClosureDef;
}
impl ClosureDef {
/// Retrieves the body of the closure definition. Returns None if the body
/// isn't available.
pub fn body(&self) -> Option<Body> {
with(|ctx| ctx.has_body(self.0).then(|| ctx.mir_body(self.0)))
}
}
crate_def! {
#[derive(Serialize)]
pub CoroutineDef;
}
impl CoroutineDef {
/// Retrieves the body of the coroutine definition. Returns None if the body
/// isn't available.
pub fn body(&self) -> Option<Body> {
with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0)))
}
pub fn discriminant_for_variant(&self, args: &GenericArgs, idx: VariantIdx) -> Discr {
with(|cx| cx.coroutine_discr_for_variant(*self, args, idx))
}
}
crate_def! {
#[derive(Serialize)]
pub CoroutineClosureDef;
}
crate_def! {
#[derive(Serialize)]
pub ParamDef;
}
crate_def! {
#[derive(Serialize)]
pub BrNamedDef;
}
crate_def! {
#[derive(Serialize)]
pub AdtDef;
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)]
pub enum AdtKind {
Enum,
Union,
Struct,
}
impl AdtDef {
pub fn kind(&self) -> AdtKind {
with(|cx| cx.adt_kind(*self))
}
/// Retrieve the type of this Adt.
pub fn ty(&self) -> Ty {
with(|cx| cx.def_ty(self.0))
}
/// Retrieve the type of this Adt by instantiating and normalizing it with the given arguments.
///
/// This will assume the type can be instantiated with these arguments.
pub fn ty_with_args(&self, args: &GenericArgs) -> Ty {
with(|cx| cx.def_ty_with_args(self.0, args))
}
pub fn is_box(&self) -> bool {
with(|cx| cx.adt_is_box(*self))
}
pub fn is_simd(&self) -> bool {
with(|cx| cx.adt_is_simd(*self))
}
/// The number of variants in this ADT.
pub fn num_variants(&self) -> usize {
with(|cx| cx.adt_variants_len(*self))
}
/// Retrieve the variants in this ADT.
pub fn variants(&self) -> Vec<VariantDef> {
self.variants_iter().collect()
}
/// Iterate over the variants in this ADT.
pub fn variants_iter(&self) -> impl Iterator<Item = VariantDef> {
(0..self.num_variants())
.map(|idx| VariantDef { idx: VariantIdx::to_val(idx), adt_def: *self })
}
pub fn variant(&self, idx: VariantIdx) -> Option<VariantDef> {
(idx.to_index() < self.num_variants()).then_some(VariantDef { idx, adt_def: *self })
}
pub fn repr(&self) -> ReprOptions {
with(|cx| cx.adt_repr(*self))
}
pub fn discriminant_for_variant(&self, idx: VariantIdx) -> Discr {
with(|cx| cx.adt_discr_for_variant(*self, idx))
}
}
pub struct Discr {
pub val: u128,
pub ty: Ty,
}
/// Definition of a variant, which can be either a struct / union field or an enum variant.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
pub struct VariantDef {
/// The variant index.
pub(crate) idx: VariantIdx,
/// The data type where this variant comes from.
/// For now, we use this to retrieve information about the variant itself so we don't need to
/// cache more information.
pub(crate) adt_def: AdtDef,
}
impl VariantDef {
/// The name of the variant, struct or union.
///
/// This will not include the name of the enum or qualified path.
pub fn name(&self) -> Symbol {
with(|cx| cx.variant_name(*self))
}
/// Retrieve all the fields in this variant.
// We expect user to cache this and use it directly since today it is expensive to generate all
// fields name.
pub fn fields(&self) -> Vec<FieldDef> {
with(|cx| cx.variant_fields(*self))
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FieldDef {
/// The field definition.
pub(crate) def: DefId,
/// The field name.
pub name: Symbol,
}
impl FieldDef {
/// Retrieve the type of this field instantiating and normalizing it with the given arguments.
///
/// This will assume the type can be instantiated with these arguments.
pub fn ty_with_args(&self, args: &GenericArgs) -> Ty {
with(|cx| cx.def_ty_with_args(self.def, args))
}
/// Retrieve the type of this field.
pub fn ty(&self) -> Ty {
with(|cx| cx.def_ty(self.def))
}
}
impl Display for AdtKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
AdtKind::Enum => "enum",
AdtKind::Union => "union",
AdtKind::Struct => "struct",
})
}
}
impl AdtKind {
pub fn is_enum(&self) -> bool {
matches!(self, AdtKind::Enum)
}
pub fn is_struct(&self) -> bool {
matches!(self, AdtKind::Struct)
}
pub fn is_union(&self) -> bool {
matches!(self, AdtKind::Union)
}
}
crate_def! {
#[derive(Serialize)]
pub AliasDef;
}
crate_def! {
/// A trait's definition.
#[derive(Serialize)]
pub TraitDef;
}
impl_crate_def_items! {
TraitDef;
}
impl TraitDef {
pub fn declaration(trait_def: &TraitDef) -> TraitDecl {
with(|cx| cx.trait_decl(trait_def))
}
}
crate_def! {
#[derive(Serialize)]
pub GenericDef;
}
crate_def_with_ty! {
#[derive(Serialize)]
pub ConstDef;
}
crate_def! {
/// A trait impl definition.
#[derive(Serialize)]
pub ImplDef;
}
impl_crate_def_items! {
ImplDef;
}
impl ImplDef {
/// Retrieve information about this implementation.
pub fn trait_impl(&self) -> ImplTrait {
with(|cx| cx.trait_impl(self))
}
}
crate_def! {
#[derive(Serialize)]
pub RegionDef;
}
crate_def! {
#[derive(Serialize)]
pub CoroutineWitnessDef;
}
/// A list of generic arguments.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
pub struct GenericArgs(pub Vec<GenericArgKind>);
impl std::ops::Index<ParamTy> for GenericArgs {
type Output = Ty;
fn index(&self, index: ParamTy) -> &Self::Output {