-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
sty.rs
1985 lines (1723 loc) · 65.4 KB
/
sty.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
//! This module contains `TyKind` and its major components.
#![allow(rustc::usage_of_ty_tykind)]
use std::assert_matches::debug_assert_matches;
use std::borrow::Cow;
use std::iter;
use std::ops::{ControlFlow, Range};
use hir::def::{CtorKind, DefKind};
use rustc_data_structures::captures::Captures;
use rustc_errors::{ErrorGuaranteed, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::LangItem;
use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};
use rustc_target::spec::abi;
use rustc_type_ir::visit::TypeVisitableExt;
use rustc_type_ir::TyKind::*;
use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind};
use ty::util::{AsyncDropGlueMorphology, IntTypeExt};
use super::GenericParamDefKind;
use crate::infer::canonical::Canonical;
use crate::ty::InferTy::*;
use crate::ty::{
self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv,
Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor,
};
// Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here
#[rustc_diagnostic_item = "TyKind"]
pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
pub trait Article {
fn article(&self) -> &'static str;
}
impl<'tcx> Article for TyKind<'tcx> {
/// Get the article ("a" or "an") to use with this type.
fn article(&self) -> &'static str {
match self {
Int(_) | Float(_) | Array(_, _) => "an",
Adt(def, _) if def.is_enum() => "an",
// This should never happen, but ICEing and causing the user's code
// to not compile felt too harsh.
Error(_) => "a",
_ => "a",
}
}
}
#[extension(pub trait CoroutineArgsExt<'tcx>)]
impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
/// Coroutine has not been resumed yet.
const UNRESUMED: usize = 0;
/// Coroutine has returned or is completed.
const RETURNED: usize = 1;
/// Coroutine has been poisoned.
const POISONED: usize = 2;
/// Number of variants to reserve in coroutine state. Corresponds to
/// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`
/// (end of a coroutine) states.
const RESERVED_VARIANTS: usize = 3;
const UNRESUMED_NAME: &'static str = "Unresumed";
const RETURNED_NAME: &'static str = "Returned";
const POISONED_NAME: &'static str = "Panicked";
/// The valid variant indices of this coroutine.
#[inline]
fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
// FIXME requires optimized MIR
FIRST_VARIANT
..tcx.coroutine_layout(def_id, tcx.types.unit).unwrap().variant_fields.next_index()
}
/// The discriminant for the given variant. Panics if the `variant_index` is
/// out of range.
#[inline]
fn discriminant_for_variant(
&self,
def_id: DefId,
tcx: TyCtxt<'tcx>,
variant_index: VariantIdx,
) -> Discr<'tcx> {
// Coroutines don't support explicit discriminant values, so they are
// the same as the variant index.
assert!(self.variant_range(def_id, tcx).contains(&variant_index));
Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
}
/// The set of all discriminants for the coroutine, enumerated with their
/// variant indices.
#[inline]
fn discriminants(
self,
def_id: DefId,
tcx: TyCtxt<'tcx>,
) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
self.variant_range(def_id, tcx).map(move |index| {
(index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
})
}
/// Calls `f` with a reference to the name of the enumerator for the given
/// variant `v`.
fn variant_name(v: VariantIdx) -> Cow<'static, str> {
match v.as_usize() {
Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
Self::RETURNED => Cow::from(Self::RETURNED_NAME),
Self::POISONED => Cow::from(Self::POISONED_NAME),
_ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
}
}
/// The type of the state discriminant used in the coroutine type.
#[inline]
fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
tcx.types.u32
}
/// This returns the types of the MIR locals which had to be stored across suspension points.
/// It is calculated in rustc_mir_transform::coroutine::StateTransform.
/// All the types here must be in the tuple in CoroutineInterior.
///
/// The locals are grouped by their variant number. Note that some locals may
/// be repeated in multiple variants.
#[inline]
fn state_tys(
self,
def_id: DefId,
tcx: TyCtxt<'tcx>,
) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
let layout = tcx.coroutine_layout(def_id, self.kind_ty()).unwrap();
layout.variant_fields.iter().map(move |variant| {
variant.iter().map(move |field| {
ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args)
})
})
}
/// This is the types of the fields of a coroutine which are not stored in a
/// variant.
#[inline]
fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
self.upvar_tys()
}
}
#[derive(Debug, Copy, Clone, HashStable, TypeFoldable, TypeVisitable)]
pub enum UpvarArgs<'tcx> {
Closure(GenericArgsRef<'tcx>),
Coroutine(GenericArgsRef<'tcx>),
CoroutineClosure(GenericArgsRef<'tcx>),
}
impl<'tcx> UpvarArgs<'tcx> {
/// Returns an iterator over the list of types of captured paths by the closure/coroutine.
/// In case there was a type error in figuring out the types of the captured path, an
/// empty iterator is returned.
#[inline]
pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
let tupled_tys = match self {
UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
};
match tupled_tys.kind() {
TyKind::Error(_) => ty::List::empty(),
TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
}
}
#[inline]
pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
match self {
UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
}
}
}
/// An inline const is modeled like
/// ```ignore (illustrative)
/// const InlineConst<'l0...'li, T0...Tj, R>: R;
/// ```
/// where:
///
/// - 'l0...'li and T0...Tj are the generic parameters
/// inherited from the item that defined the inline const,
/// - R represents the type of the constant.
///
/// When the inline const is instantiated, `R` is instantiated as the actual inferred
/// type of the constant. The reason that `R` is represented as an extra type parameter
/// is the same reason that [`ty::ClosureArgs`] have `CS` and `U` as type parameters:
/// inline const can reference lifetimes that are internal to the creating function.
#[derive(Copy, Clone, Debug)]
pub struct InlineConstArgs<'tcx> {
/// Generic parameters from the enclosing item,
/// concatenated with the inferred type of the constant.
pub args: GenericArgsRef<'tcx>,
}
/// Struct returned by `split()`.
pub struct InlineConstArgsParts<'tcx, T> {
pub parent_args: &'tcx [GenericArg<'tcx>],
pub ty: T,
}
impl<'tcx> InlineConstArgs<'tcx> {
/// Construct `InlineConstArgs` from `InlineConstArgsParts`.
pub fn new(
tcx: TyCtxt<'tcx>,
parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
) -> InlineConstArgs<'tcx> {
InlineConstArgs {
args: tcx.mk_args_from_iter(
parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
),
}
}
/// Divides the inline const args into their respective components.
/// The ordering assumed here must match that used by `InlineConstArgs::new` above.
fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
match self.args[..] {
[ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
_ => bug!("inline const args missing synthetics"),
}
}
/// Returns the generic parameters of the inline const's parent.
pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
self.split().parent_args
}
/// Returns the type of this inline const.
pub fn ty(self) -> Ty<'tcx> {
self.split().ty.expect_ty()
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub enum BoundVariableKind {
Ty(BoundTyKind),
Region(BoundRegionKind),
Const,
}
impl BoundVariableKind {
pub fn expect_region(self) -> BoundRegionKind {
match self {
BoundVariableKind::Region(lt) => lt,
_ => bug!("expected a region, but found another kind"),
}
}
pub fn expect_ty(self) -> BoundTyKind {
match self {
BoundVariableKind::Ty(ty) => ty,
_ => bug!("expected a type, but found another kind"),
}
}
pub fn expect_const(self) {
match self {
BoundVariableKind::Const => (),
_ => bug!("expected a const, but found another kind"),
}
}
}
pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub struct ParamTy {
pub index: u32,
pub name: Symbol,
}
impl rustc_type_ir::inherent::ParamLike for ParamTy {
fn index(self) -> u32 {
self.index
}
}
impl<'tcx> ParamTy {
pub fn new(index: u32, name: Symbol) -> ParamTy {
ParamTy { index, name }
}
pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
ParamTy::new(def.index, def.name)
}
#[inline]
pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
Ty::new_param(tcx, self.index, self.name)
}
pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
let generics = tcx.generics_of(item_with_generics);
let type_param = generics.type_param(self, tcx);
tcx.def_span(type_param.def_id)
}
}
#[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
#[derive(HashStable)]
pub struct ParamConst {
pub index: u32,
pub name: Symbol,
}
impl rustc_type_ir::inherent::ParamLike for ParamConst {
fn index(self) -> u32 {
self.index
}
}
impl ParamConst {
pub fn new(index: u32, name: Symbol) -> ParamConst {
ParamConst { index, name }
}
pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
ParamConst::new(def.index, def.name)
}
pub fn find_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
// `ConstArgHasType` are never desugared to be higher ranked.
match clause.kind().skip_binder() {
ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
assert!(!(param_ct, ty).has_escaping_bound_vars());
match param_ct.kind() {
ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
_ => None,
}
}
_ => None,
}
});
let ty = candidates.next().unwrap();
assert!(candidates.next().is_none());
ty
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub struct BoundTy {
pub var: BoundVar,
pub kind: BoundTyKind,
}
impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundTy {
fn var(self) -> BoundVar {
self.var
}
fn assert_eq(self, var: ty::BoundVariableKind) {
assert_eq!(self.kind, var.expect_ty())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub enum BoundTyKind {
Anon,
Param(DefId, Symbol),
}
impl From<BoundVar> for BoundTy {
fn from(var: BoundVar) -> Self {
BoundTy { var, kind: BoundTyKind::Anon }
}
}
/// Constructors for `Ty`
impl<'tcx> Ty<'tcx> {
/// Avoid using this in favour of more specific `new_*` methods, where possible.
/// The more specific methods will often optimize their creation.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
tcx.mk_ty_from_kind(st)
}
#[inline]
pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
Ty::new(tcx, TyKind::Infer(infer))
}
#[inline]
pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.ty_vars
.get(v.as_usize())
.copied()
.unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
}
#[inline]
pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
Ty::new_infer(tcx, IntVar(v))
}
#[inline]
pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
Ty::new_infer(tcx, FloatVar(v))
}
#[inline]
pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
}
#[inline]
pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_int_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
}
#[inline]
pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
// Use a pre-interned one when possible.
tcx.types
.fresh_float_tys
.get(n as usize)
.copied()
.unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
}
#[inline]
pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
tcx.mk_ty_from_kind(Param(ParamTy { index, name }))
}
#[inline]
pub fn new_bound(
tcx: TyCtxt<'tcx>,
index: ty::DebruijnIndex,
bound_ty: ty::BoundTy,
) -> Ty<'tcx> {
Ty::new(tcx, Bound(index, bound_ty))
}
#[inline]
pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Ty<'tcx> {
Ty::new(tcx, Placeholder(placeholder))
}
#[inline]
pub fn new_alias(
tcx: TyCtxt<'tcx>,
kind: ty::AliasTyKind,
alias_ty: ty::AliasTy<'tcx>,
) -> Ty<'tcx> {
debug_assert_matches!(
(kind, tcx.def_kind(alias_ty.def_id)),
(ty::Opaque, DefKind::OpaqueTy)
| (ty::Projection | ty::Inherent, DefKind::AssocTy)
| (ty::Weak, DefKind::TyAlias)
);
Ty::new(tcx, Alias(kind, alias_ty))
}
#[inline]
pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, Pat(base, pat))
}
#[inline]
pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
Ty::new_alias(tcx, ty::Opaque, AliasTy::new_from_args(tcx, def_id, args))
}
/// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
Ty::new(tcx, Error(guar))
}
/// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` to ensure it gets used.
#[track_caller]
pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
}
/// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` with the given `msg` to
/// ensure it gets used.
#[track_caller]
pub fn new_error_with_message<S: Into<MultiSpan>>(
tcx: TyCtxt<'tcx>,
span: S,
msg: impl Into<Cow<'static, str>>,
) -> Ty<'tcx> {
let reported = tcx.dcx().span_delayed_bug(span, msg);
Ty::new(tcx, Error(reported))
}
#[inline]
pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
use ty::IntTy::*;
match i {
Isize => tcx.types.isize,
I8 => tcx.types.i8,
I16 => tcx.types.i16,
I32 => tcx.types.i32,
I64 => tcx.types.i64,
I128 => tcx.types.i128,
}
}
#[inline]
pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
use ty::UintTy::*;
match ui {
Usize => tcx.types.usize,
U8 => tcx.types.u8,
U16 => tcx.types.u16,
U32 => tcx.types.u32,
U64 => tcx.types.u64,
U128 => tcx.types.u128,
}
}
#[inline]
pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
use ty::FloatTy::*;
match f {
F16 => tcx.types.f16,
F32 => tcx.types.f32,
F64 => tcx.types.f64,
F128 => tcx.types.f128,
}
}
#[inline]
pub fn new_ref(
tcx: TyCtxt<'tcx>,
r: Region<'tcx>,
ty: Ty<'tcx>,
mutbl: ty::Mutability,
) -> Ty<'tcx> {
Ty::new(tcx, Ref(r, ty, mutbl))
}
#[inline]
pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
}
#[inline]
pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
}
#[inline]
pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
Ty::new(tcx, ty::RawPtr(ty, mutbl))
}
#[inline]
pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
}
#[inline]
pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new_ptr(tcx, ty, hir::Mutability::Not)
}
#[inline]
pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
tcx.debug_assert_args_compatible(def.did(), args);
Ty::new(tcx, Adt(def, args))
}
#[inline]
pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
Ty::new(tcx, Foreign(def_id))
}
#[inline]
pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
}
#[inline]
pub fn new_array_with_const_len(
tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>,
ct: ty::Const<'tcx>,
) -> Ty<'tcx> {
Ty::new(tcx, Array(ty, ct))
}
#[inline]
pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
Ty::new(tcx, Slice(ty))
}
#[inline]
pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
}
pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
where
I: Iterator<Item = T>,
T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
{
T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
}
#[inline]
pub fn new_fn_def(
tcx: TyCtxt<'tcx>,
def_id: DefId,
args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
debug_assert_matches!(
tcx.def_kind(def_id),
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
);
let args = tcx.check_and_mk_args(def_id, args);
Ty::new(tcx, FnDef(def_id, args))
}
#[inline]
pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
let (sig_tys, hdr) = fty.split();
Ty::new(tcx, FnPtr(sig_tys, hdr))
}
#[inline]
pub fn new_dynamic(
tcx: TyCtxt<'tcx>,
obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
reg: ty::Region<'tcx>,
repr: DynKind,
) -> Ty<'tcx> {
Ty::new(tcx, Dynamic(obj, reg, repr))
}
#[inline]
pub fn new_projection_from_args(
tcx: TyCtxt<'tcx>,
item_def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
) -> Ty<'tcx> {
Ty::new_alias(tcx, ty::Projection, AliasTy::new_from_args(tcx, item_def_id, args))
}
#[inline]
pub fn new_projection(
tcx: TyCtxt<'tcx>,
item_def_id: DefId,
args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> Ty<'tcx> {
Ty::new_alias(tcx, ty::Projection, AliasTy::new(tcx, item_def_id, args))
}
#[inline]
pub fn new_closure(
tcx: TyCtxt<'tcx>,
def_id: DefId,
closure_args: GenericArgsRef<'tcx>,
) -> Ty<'tcx> {
tcx.debug_assert_args_compatible(def_id, closure_args);
Ty::new(tcx, Closure(def_id, closure_args))
}
#[inline]
pub fn new_coroutine_closure(
tcx: TyCtxt<'tcx>,
def_id: DefId,
closure_args: GenericArgsRef<'tcx>,
) -> Ty<'tcx> {
tcx.debug_assert_args_compatible(def_id, closure_args);
Ty::new(tcx, CoroutineClosure(def_id, closure_args))
}
#[inline]
pub fn new_coroutine(
tcx: TyCtxt<'tcx>,
def_id: DefId,
coroutine_args: GenericArgsRef<'tcx>,
) -> Ty<'tcx> {
tcx.debug_assert_args_compatible(def_id, coroutine_args);
Ty::new(tcx, Coroutine(def_id, coroutine_args))
}
#[inline]
pub fn new_coroutine_witness(
tcx: TyCtxt<'tcx>,
id: DefId,
args: GenericArgsRef<'tcx>,
) -> Ty<'tcx> {
Ty::new(tcx, CoroutineWitness(id, args))
}
// misc
#[inline]
pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
}
#[inline]
pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
if tcx.features().never_type_fallback { tcx.types.never } else { tcx.types.unit }
}
// lang and diagnostic tys
fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
let adt_def = tcx.adt_def(wrapper_def_id);
let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
GenericParamDefKind::Type { has_default, .. } => {
if param.index == 0 {
ty_param.into()
} else {
assert!(has_default);
tcx.type_of(param.def_id).instantiate(tcx, args).into()
}
}
});
Ty::new(tcx, Adt(adt_def, args))
}
#[inline]
pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
let def_id = tcx.lang_items().get(item)?;
Some(Ty::new_generic_adt(tcx, def_id, ty))
}
#[inline]
pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
let def_id = tcx.get_diagnostic_item(name)?;
Some(Ty::new_generic_adt(tcx, def_id, ty))
}
#[inline]
pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = tcx.require_lang_item(LangItem::OwnedBox, None);
Ty::new_generic_adt(tcx, def_id, ty)
}
#[inline]
pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
let def_id = tcx.require_lang_item(LangItem::MaybeUninit, None);
Ty::new_generic_adt(tcx, def_id, ty)
}
/// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
let context_did = tcx.require_lang_item(LangItem::Context, None);
let context_adt_ref = tcx.adt_def(context_did);
let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
}
}
impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
tcx.types.bool
}
fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
tcx.types.u8
}
fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
Ty::new_infer(tcx, infer)
}
fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
Ty::new_var(tcx, vid)
}
fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
Ty::new_param(tcx, param.index, param.name)
}
fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Self {
Ty::new_placeholder(tcx, placeholder)
}
fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self {
Ty::new_bound(interner, debruijn, var)
}
fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
}
fn new_alias(
interner: TyCtxt<'tcx>,
kind: ty::AliasTyKind,
alias_ty: ty::AliasTy<'tcx>,
) -> Self {
Ty::new_alias(interner, kind, alias_ty)
}
fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
Ty::new_error(interner, guar)
}
fn new_adt(
interner: TyCtxt<'tcx>,
adt_def: ty::AdtDef<'tcx>,
args: ty::GenericArgsRef<'tcx>,
) -> Self {
Ty::new_adt(interner, adt_def, args)
}
fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
Ty::new_foreign(interner, def_id)
}
fn new_dynamic(
interner: TyCtxt<'tcx>,
preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
region: ty::Region<'tcx>,
kind: ty::DynKind,
) -> Self {
Ty::new_dynamic(interner, preds, region, kind)
}
fn new_coroutine(
interner: TyCtxt<'tcx>,
def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
) -> Self {
Ty::new_coroutine(interner, def_id, args)
}
fn new_coroutine_closure(
interner: TyCtxt<'tcx>,
def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
) -> Self {
Ty::new_coroutine_closure(interner, def_id, args)
}
fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
Ty::new_closure(interner, def_id, args)
}
fn new_coroutine_witness(
interner: TyCtxt<'tcx>,
def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
) -> Self {
Ty::new_coroutine_witness(interner, def_id, args)
}
fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
Ty::new_ptr(interner, ty, mutbl)
}
fn new_ref(
interner: TyCtxt<'tcx>,
region: ty::Region<'tcx>,
ty: Self,
mutbl: hir::Mutability,
) -> Self {
Ty::new_ref(interner, region, ty, mutbl)
}
fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
Ty::new_array_with_const_len(interner, ty, len)
}
fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
Ty::new_slice(interner, ty)
}
fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
Ty::new_tup(interner, tys)
}
fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
where
It: Iterator<Item = T>,
T: CollectAndApply<Self, Self>,
{
Ty::new_tup_from_iter(interner, iter)
}
fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
self.tuple_fields()
}
fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
self.to_opt_closure_kind()
}
fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
Ty::from_closure_kind(interner, kind)
}
fn from_coroutine_closure_kind(
interner: TyCtxt<'tcx>,
kind: rustc_type_ir::ClosureKind,
) -> Self {
Ty::from_coroutine_closure_kind(interner, kind)
}
fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
Ty::new_fn_def(interner, def_id, args)
}
fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
Ty::new_fn_ptr(interner, sig)
}
fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
Ty::new_pat(interner, ty, pat)
}
fn new_unit(interner: TyCtxt<'tcx>) -> Self {
interner.types.unit
}
fn new_usize(interner: TyCtxt<'tcx>) -> Self {
interner.types.usize
}
fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
self.discriminant_ty(interner)
}
fn async_destructor_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
self.async_destructor_ty(interner)
}
}
/// Type utilities
impl<'tcx> Ty<'tcx> {
// It would be nicer if this returned the value instead of a reference,
// like how `Predicate::kind` and `Region::kind` do. (It would result in
// many fewer subsequent dereferences.) But that gives a small but
// noticeable performance hit. See #126069 for details.
#[inline(always)]
pub fn kind(self) -> &'tcx TyKind<'tcx> {
self.0.0
}
// FIXME(compiler-errors): Think about removing this.
#[inline(always)]
pub fn flags(self) -> TypeFlags {
self.0.0.flags
}
#[inline]
pub fn is_unit(self) -> bool {
match self.kind() {
Tuple(tys) => tys.is_empty(),
_ => false,
}
}
#[inline]
pub fn is_never(self) -> bool {
matches!(self.kind(), Never)
}