1use core::intrinsics;
4use std::marker::PhantomData;
5use std::mem;
6use std::num::NonZero;
7use std::ptr::NonNull;
8
9use rustc_ast_ir::visit::VisitorResult;
10use rustc_ast_ir::walk_visitable_list;
11use rustc_data_structures::intern::Interned;
12use rustc_errors::{DiagArgValue, IntoDiagArg};
13use rustc_hir::def_id::DefId;
14use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, extension};
15use rustc_serialize::{Decodable, Encodable};
16use rustc_type_ir::WithCachedTypeInfo;
17use smallvec::SmallVec;
18
19use crate::ty::codec::{TyDecoder, TyEncoder};
20use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
21use crate::ty::visit::{TypeVisitable, TypeVisitor};
22use crate::ty::{
23 self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, InlineConstArgs, Lift, List, Ty, TyCtxt,
24};
25
26pub type GenericArgKind<'tcx> = rustc_type_ir::GenericArgKind<TyCtxt<'tcx>>;
27pub type TermKind<'tcx> = rustc_type_ir::TermKind<TyCtxt<'tcx>>;
28
29#[derive(Copy, Clone, PartialEq, Eq, Hash)]
38pub struct GenericArg<'tcx> {
39 ptr: NonNull<()>,
40 marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>,
41}
42
43impl<'tcx> rustc_type_ir::inherent::GenericArg<TyCtxt<'tcx>> for GenericArg<'tcx> {}
44
45impl<'tcx> rustc_type_ir::inherent::GenericArgs<TyCtxt<'tcx>> for ty::GenericArgsRef<'tcx> {
46 fn rebase_onto(
47 self,
48 tcx: TyCtxt<'tcx>,
49 source_ancestor: DefId,
50 target_args: GenericArgsRef<'tcx>,
51 ) -> GenericArgsRef<'tcx> {
52 self.rebase_onto(tcx, source_ancestor, target_args)
53 }
54
55 fn type_at(self, i: usize) -> Ty<'tcx> {
56 self.type_at(i)
57 }
58
59 fn region_at(self, i: usize) -> ty::Region<'tcx> {
60 self.region_at(i)
61 }
62
63 fn const_at(self, i: usize) -> ty::Const<'tcx> {
64 self.const_at(i)
65 }
66
67 fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::GenericArgsRef<'tcx> {
68 GenericArgs::identity_for_item(tcx, def_id)
69 }
70
71 fn extend_with_error(
72 tcx: TyCtxt<'tcx>,
73 def_id: DefId,
74 original_args: &[ty::GenericArg<'tcx>],
75 ) -> ty::GenericArgsRef<'tcx> {
76 ty::GenericArgs::extend_with_error(tcx, def_id, original_args)
77 }
78
79 fn split_closure_args(self) -> ty::ClosureArgsParts<TyCtxt<'tcx>> {
80 match self[..] {
81 [ref parent_args @ .., closure_kind_ty, closure_sig_as_fn_ptr_ty, tupled_upvars_ty] => {
82 ty::ClosureArgsParts {
83 parent_args,
84 closure_kind_ty: closure_kind_ty.expect_ty(),
85 closure_sig_as_fn_ptr_ty: closure_sig_as_fn_ptr_ty.expect_ty(),
86 tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
87 }
88 }
89 _ => bug!("closure args missing synthetics"),
90 }
91 }
92
93 fn split_coroutine_closure_args(self) -> ty::CoroutineClosureArgsParts<TyCtxt<'tcx>> {
94 match self[..] {
95 [
96 ref parent_args @ ..,
97 closure_kind_ty,
98 signature_parts_ty,
99 tupled_upvars_ty,
100 coroutine_captures_by_ref_ty,
101 coroutine_witness_ty,
102 ] => ty::CoroutineClosureArgsParts {
103 parent_args,
104 closure_kind_ty: closure_kind_ty.expect_ty(),
105 signature_parts_ty: signature_parts_ty.expect_ty(),
106 tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
107 coroutine_captures_by_ref_ty: coroutine_captures_by_ref_ty.expect_ty(),
108 coroutine_witness_ty: coroutine_witness_ty.expect_ty(),
109 },
110 _ => bug!("closure args missing synthetics"),
111 }
112 }
113
114 fn split_coroutine_args(self) -> ty::CoroutineArgsParts<TyCtxt<'tcx>> {
115 match self[..] {
116 [
117 ref parent_args @ ..,
118 kind_ty,
119 resume_ty,
120 yield_ty,
121 return_ty,
122 witness,
123 tupled_upvars_ty,
124 ] => ty::CoroutineArgsParts {
125 parent_args,
126 kind_ty: kind_ty.expect_ty(),
127 resume_ty: resume_ty.expect_ty(),
128 yield_ty: yield_ty.expect_ty(),
129 return_ty: return_ty.expect_ty(),
130 witness: witness.expect_ty(),
131 tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
132 },
133 _ => bug!("coroutine args missing synthetics"),
134 }
135 }
136}
137
138impl<'tcx> rustc_type_ir::inherent::IntoKind for GenericArg<'tcx> {
139 type Kind = GenericArgKind<'tcx>;
140
141 fn kind(self) -> Self::Kind {
142 self.unpack()
143 }
144}
145
146unsafe impl<'tcx> rustc_data_structures::sync::DynSend for GenericArg<'tcx> where
147 &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): rustc_data_structures::sync::DynSend
148{
149}
150unsafe impl<'tcx> rustc_data_structures::sync::DynSync for GenericArg<'tcx> where
151 &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): rustc_data_structures::sync::DynSync
152{
153}
154unsafe impl<'tcx> Send for GenericArg<'tcx> where
155 &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): Send
156{
157}
158unsafe impl<'tcx> Sync for GenericArg<'tcx> where
159 &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): Sync
160{
161}
162
163impl<'tcx> IntoDiagArg for GenericArg<'tcx> {
164 fn into_diag_arg(self) -> DiagArgValue {
165 self.to_string().into_diag_arg()
166 }
167}
168
169const TAG_MASK: usize = 0b11;
170const TYPE_TAG: usize = 0b00;
171const REGION_TAG: usize = 0b01;
172const CONST_TAG: usize = 0b10;
173
174#[extension(trait GenericArgPackExt<'tcx>)]
175impl<'tcx> GenericArgKind<'tcx> {
176 #[inline]
177 fn pack(self) -> GenericArg<'tcx> {
178 let (tag, ptr) = match self {
179 GenericArgKind::Lifetime(lt) => {
180 assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0);
182 (REGION_TAG, NonNull::from(lt.0.0).cast())
183 }
184 GenericArgKind::Type(ty) => {
185 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
187 (TYPE_TAG, NonNull::from(ty.0.0).cast())
188 }
189 GenericArgKind::Const(ct) => {
190 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
192 (CONST_TAG, NonNull::from(ct.0.0).cast())
193 }
194 };
195
196 GenericArg { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
197 }
198}
199
200impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> {
201 #[inline]
202 fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> {
203 GenericArgKind::Lifetime(r).pack()
204 }
205}
206
207impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> {
208 #[inline]
209 fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> {
210 GenericArgKind::Type(ty).pack()
211 }
212}
213
214impl<'tcx> From<ty::Const<'tcx>> for GenericArg<'tcx> {
215 #[inline]
216 fn from(c: ty::Const<'tcx>) -> GenericArg<'tcx> {
217 GenericArgKind::Const(c).pack()
218 }
219}
220
221impl<'tcx> From<ty::Term<'tcx>> for GenericArg<'tcx> {
222 fn from(value: ty::Term<'tcx>) -> Self {
223 match value.unpack() {
224 ty::TermKind::Ty(t) => t.into(),
225 ty::TermKind::Const(c) => c.into(),
226 }
227 }
228}
229
230impl<'tcx> GenericArg<'tcx> {
231 #[inline]
232 pub fn unpack(self) -> GenericArgKind<'tcx> {
233 let ptr =
234 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
235 unsafe {
239 match self.ptr.addr().get() & TAG_MASK {
240 REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked(
241 ptr.cast::<ty::RegionKind<'tcx>>().as_ref(),
242 ))),
243 TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked(
244 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
245 ))),
246 CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked(
247 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
248 ))),
249 _ => intrinsics::unreachable(),
250 }
251 }
252 }
253
254 #[inline]
255 pub fn as_type(self) -> Option<Ty<'tcx>> {
256 match self.unpack() {
257 GenericArgKind::Type(ty) => Some(ty),
258 _ => None,
259 }
260 }
261
262 #[inline]
263 pub fn as_region(self) -> Option<ty::Region<'tcx>> {
264 match self.unpack() {
265 GenericArgKind::Lifetime(re) => Some(re),
266 _ => None,
267 }
268 }
269
270 #[inline]
271 pub fn as_const(self) -> Option<ty::Const<'tcx>> {
272 match self.unpack() {
273 GenericArgKind::Const(ct) => Some(ct),
274 _ => None,
275 }
276 }
277
278 pub fn expect_region(self) -> ty::Region<'tcx> {
280 self.as_region().unwrap_or_else(|| bug!("expected a region, but found another kind"))
281 }
282
283 pub fn expect_ty(self) -> Ty<'tcx> {
287 self.as_type().unwrap_or_else(|| bug!("expected a type, but found another kind"))
288 }
289
290 pub fn expect_const(self) -> ty::Const<'tcx> {
292 self.as_const().unwrap_or_else(|| bug!("expected a const, but found another kind"))
293 }
294
295 pub fn is_non_region_infer(self) -> bool {
296 match self.unpack() {
297 GenericArgKind::Lifetime(_) => false,
298 GenericArgKind::Type(ty) => ty.is_ty_or_numeric_infer(),
300 GenericArgKind::Const(ct) => ct.is_ct_infer(),
301 }
302 }
303}
304
305impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for GenericArg<'a> {
306 type Lifted = GenericArg<'tcx>;
307
308 fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
309 match self.unpack() {
310 GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()),
311 GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()),
312 GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()),
313 }
314 }
315}
316
317impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArg<'tcx> {
318 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
319 self,
320 folder: &mut F,
321 ) -> Result<Self, F::Error> {
322 match self.unpack() {
323 GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into),
324 GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into),
325 GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
326 }
327 }
328}
329
330impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for GenericArg<'tcx> {
331 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
332 match self.unpack() {
333 GenericArgKind::Lifetime(lt) => lt.visit_with(visitor),
334 GenericArgKind::Type(ty) => ty.visit_with(visitor),
335 GenericArgKind::Const(ct) => ct.visit_with(visitor),
336 }
337 }
338}
339
340impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> {
341 fn encode(&self, e: &mut E) {
342 self.unpack().encode(e)
343 }
344}
345
346impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> {
347 fn decode(d: &mut D) -> GenericArg<'tcx> {
348 GenericArgKind::decode(d).pack()
349 }
350}
351
352pub type GenericArgs<'tcx> = List<GenericArg<'tcx>>;
354
355pub type GenericArgsRef<'tcx> = &'tcx GenericArgs<'tcx>;
356
357impl<'tcx> GenericArgs<'tcx> {
358 pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List<Ty<'tcx>> {
364 tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.unpack() {
365 GenericArgKind::Type(ty) => ty,
366 _ => bug!("`into_type_list` called on generic arg with non-types"),
367 }))
368 }
369
370 pub fn as_closure(&'tcx self) -> ClosureArgs<TyCtxt<'tcx>> {
375 ClosureArgs { args: self }
376 }
377
378 pub fn as_coroutine_closure(&'tcx self) -> CoroutineClosureArgs<TyCtxt<'tcx>> {
383 CoroutineClosureArgs { args: self }
384 }
385
386 pub fn as_coroutine(&'tcx self) -> CoroutineArgs<TyCtxt<'tcx>> {
391 CoroutineArgs { args: self }
392 }
393
394 pub fn as_inline_const(&'tcx self) -> InlineConstArgs<'tcx> {
399 InlineConstArgs { args: self }
400 }
401
402 pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> GenericArgsRef<'tcx> {
404 Self::for_item(tcx, def_id.into(), |param, _| tcx.mk_param_from_def(param))
405 }
406
407 pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> GenericArgsRef<'tcx>
413 where
414 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
415 {
416 let defs = tcx.generics_of(def_id);
417 let count = defs.count();
418 let mut args = SmallVec::with_capacity(count);
419 Self::fill_item(&mut args, tcx, defs, &mut mk_kind);
420 tcx.mk_args(&args)
421 }
422
423 pub fn extend_to<F>(
424 &self,
425 tcx: TyCtxt<'tcx>,
426 def_id: DefId,
427 mut mk_kind: F,
428 ) -> GenericArgsRef<'tcx>
429 where
430 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
431 {
432 Self::for_item(tcx, def_id, |param, args| {
433 self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, args))
434 })
435 }
436
437 pub fn fill_item<F>(
438 args: &mut SmallVec<[GenericArg<'tcx>; 8]>,
439 tcx: TyCtxt<'tcx>,
440 defs: &ty::Generics,
441 mk_kind: &mut F,
442 ) where
443 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
444 {
445 if let Some(def_id) = defs.parent {
446 let parent_defs = tcx.generics_of(def_id);
447 Self::fill_item(args, tcx, parent_defs, mk_kind);
448 }
449 Self::fill_single(args, defs, mk_kind)
450 }
451
452 pub fn fill_single<F>(
453 args: &mut SmallVec<[GenericArg<'tcx>; 8]>,
454 defs: &ty::Generics,
455 mk_kind: &mut F,
456 ) where
457 F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
458 {
459 args.reserve(defs.own_params.len());
460 for param in &defs.own_params {
461 let kind = mk_kind(param, args);
462 assert_eq!(param.index as usize, args.len(), "{args:#?}, {defs:#?}");
463 args.push(kind);
464 }
465 }
466
467 pub fn extend_with_error(
470 tcx: TyCtxt<'tcx>,
471 def_id: DefId,
472 original_args: &[GenericArg<'tcx>],
473 ) -> GenericArgsRef<'tcx> {
474 ty::GenericArgs::for_item(tcx, def_id, |def, _| {
475 if let Some(arg) = original_args.get(def.index as usize) {
476 *arg
477 } else {
478 def.to_error(tcx)
479 }
480 })
481 }
482
483 #[inline]
484 pub fn types(&'tcx self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'tcx {
485 self.iter().filter_map(|k| k.as_type())
486 }
487
488 #[inline]
489 pub fn regions(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'tcx {
490 self.iter().filter_map(|k| k.as_region())
491 }
492
493 #[inline]
494 pub fn consts(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Const<'tcx>> + 'tcx {
495 self.iter().filter_map(|k| k.as_const())
496 }
497
498 #[inline]
500 pub fn non_erasable_generics(
501 &'tcx self,
502 ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'tcx {
503 self.iter().filter_map(|k| match k.unpack() {
504 ty::GenericArgKind::Lifetime(_) => None,
505 generic => Some(generic),
506 })
507 }
508
509 #[inline]
510 #[track_caller]
511 pub fn type_at(&self, i: usize) -> Ty<'tcx> {
512 self[i].as_type().unwrap_or_else(|| bug!("expected type for param #{} in {:?}", i, self))
513 }
514
515 #[inline]
516 #[track_caller]
517 pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
518 self[i]
519 .as_region()
520 .unwrap_or_else(|| bug!("expected region for param #{} in {:?}", i, self))
521 }
522
523 #[inline]
524 #[track_caller]
525 pub fn const_at(&self, i: usize) -> ty::Const<'tcx> {
526 self[i].as_const().unwrap_or_else(|| bug!("expected const for param #{} in {:?}", i, self))
527 }
528
529 #[inline]
530 #[track_caller]
531 pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> {
532 self.type_at(def.index as usize).into()
533 }
534
535 pub fn rebase_onto(
554 &self,
555 tcx: TyCtxt<'tcx>,
556 source_ancestor: DefId,
557 target_args: GenericArgsRef<'tcx>,
558 ) -> GenericArgsRef<'tcx> {
559 let defs = tcx.generics_of(source_ancestor);
560 tcx.mk_args_from_iter(target_args.iter().chain(self.iter().skip(defs.count())))
561 }
562
563 pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> GenericArgsRef<'tcx> {
564 tcx.mk_args_from_iter(self.iter().take(generics.count()))
565 }
566
567 pub fn print_as_list(&self) -> String {
568 let v = self.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
569 format!("[{}]", v.join(", "))
570 }
571}
572
573impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> {
574 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
575 self,
576 folder: &mut F,
577 ) -> Result<Self, F::Error> {
578 match self.len() {
585 1 => {
586 let param0 = self[0].try_fold_with(folder)?;
587 if param0 == self[0] { Ok(self) } else { Ok(folder.cx().mk_args(&[param0])) }
588 }
589 2 => {
590 let param0 = self[0].try_fold_with(folder)?;
591 let param1 = self[1].try_fold_with(folder)?;
592 if param0 == self[0] && param1 == self[1] {
593 Ok(self)
594 } else {
595 Ok(folder.cx().mk_args(&[param0, param1]))
596 }
597 }
598 0 => Ok(self),
599 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_args(v)),
600 }
601 }
602}
603
604impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
605 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
606 self,
607 folder: &mut F,
608 ) -> Result<Self, F::Error> {
609 match self.len() {
625 2 => {
626 let param0 = self[0].try_fold_with(folder)?;
627 let param1 = self[1].try_fold_with(folder)?;
628 if param0 == self[0] && param1 == self[1] {
629 Ok(self)
630 } else {
631 Ok(folder.cx().mk_type_list(&[param0, param1]))
632 }
633 }
634 _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_type_list(v)),
635 }
636 }
637}
638
639impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>> for &'tcx ty::List<T> {
640 #[inline]
641 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
642 walk_visitable_list!(visitor, self.iter());
643 V::Result::output()
644 }
645}
646
647#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
650#[derive(HashStable, TypeFoldable, TypeVisitable)]
651pub struct UserArgs<'tcx> {
652 pub args: GenericArgsRef<'tcx>,
654
655 pub user_self_ty: Option<UserSelfTy<'tcx>>,
658}
659
660#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
677#[derive(HashStable, TypeFoldable, TypeVisitable)]
678pub struct UserSelfTy<'tcx> {
679 pub impl_def_id: DefId,
680 pub self_ty: Ty<'tcx>,
681}