1//! Freshening is the process of replacing unknown variables with fresh types. The idea is that
2//! the type, after freshening, contains no inference variables but instead contains either a
3//! value for each variable or fresh "arbitrary" types wherever a variable would have been.
4//!
5//! Freshening is used primarily to get a good type for inserting into a cache. The result
6//! summarizes what the type inferencer knows "so far". The primary place it is used right now is
7//! in the trait matching algorithm, which needs to be able to cache whether an `impl` self type
8//! matches some other type X -- *without* affecting `X`. That means that if the type `X` is in
9//! fact an unbound type variable, we want the match to be regarded as ambiguous, because depending
10//! on what type that type variable is ultimately assigned, the match may or may not succeed.
11//!
12//! To handle closures, freshened types also have to contain the signature and kind of any
13//! closure in the local inference context, as otherwise the cache key might be invalidated.
14//! The way this is done is somewhat hacky - the closure signature is appended to the args,
15//! as well as the closure kind "encoded" as a type. Also, special handling is needed when
16//! the closure signature contains a reference to the original closure.
17//!
18//! Note that you should be careful not to allow the output of freshening to leak to the user in
19//! error messages or in any other form. Freshening is only really useful as an internal detail.
20//!
21//! Because of the manipulation required to handle closures, doing arbitrary operations on
22//! freshened types is not recommended. However, in addition to doing equality/hash
23//! comparisons (for caching), it is possible to do a `ty::_match` operation between
24//! two freshened types - this works even with the closure encoding.
25//!
26//! __An important detail concerning regions.__ The freshener also replaces *all* free regions with
27//! 'erased. The reason behind this is that, in general, we do not take region relationships into
28//! account when making type-overloaded decisions. This is important because of the design of the
29//! region inferencer, which is not based on unification but rather on accumulating and then
30//! solving a set of constraints. In contrast, the type inferencer assigns a value to each type
31//! variable only once, and it does so as soon as it can, so it is reasonable to ask what the type
32//! inferencer knows "so far".
3334use std::collections::hash_map::Entry;
3536use rustc_data_structures::fx::FxHashMap;
37use rustc_middle::bug;
38use rustc_middle::ty::{
39self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
40};
4142use super::InferCtxt;
4344pub struct TypeFreshener<'a, 'tcx> {
45 infcx: &'a InferCtxt<'tcx>,
46 ty_freshen_count: u32,
47 const_freshen_count: u32,
48 ty_freshen_map: FxHashMap<ty::InferTy, Ty<'tcx>>,
49 const_freshen_map: FxHashMap<ty::InferConst, ty::Const<'tcx>>,
50}
5152impl<'a, 'tcx> TypeFreshener<'a, 'tcx> {
53pub fn new(infcx: &'a InferCtxt<'tcx>) -> TypeFreshener<'a, 'tcx> {
54TypeFreshener {
55infcx,
56 ty_freshen_count: 0,
57 const_freshen_count: 0,
58 ty_freshen_map: Default::default(),
59 const_freshen_map: Default::default(),
60 }
61 }
6263fn freshen_ty<F>(&mut self, input: ty::InferTy, mk_fresh: F) -> Ty<'tcx>
64where
65F: FnOnce(u32) -> Ty<'tcx>,
66 {
67match self.ty_freshen_map.entry(input) {
68 Entry::Occupied(entry) => *entry.get(),
69 Entry::Vacant(entry) => {
70let index = self.ty_freshen_count;
71self.ty_freshen_count += 1;
72let t = mk_fresh(index);
73entry.insert(t);
74t75 }
76 }
77 }
7879fn freshen_const<F>(&mut self, input: ty::InferConst, freshener: F) -> ty::Const<'tcx>
80where
81F: FnOnce(u32) -> ty::InferConst,
82 {
83match self.const_freshen_map.entry(input) {
84 Entry::Occupied(entry) => *entry.get(),
85 Entry::Vacant(entry) => {
86let index = self.const_freshen_count;
87self.const_freshen_count += 1;
88let ct = ty::Const::new_infer(self.infcx.tcx, freshener(index));
89entry.insert(ct);
90ct91 }
92 }
93 }
94}
9596impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for TypeFreshener<'a, 'tcx> {
97fn cx(&self) -> TyCtxt<'tcx> {
98self.infcx.tcx
99 }
100101fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
102match r.kind() {
103// Leave bound regions alone, since they affect selection via the leak check.
104ty::ReBound(..) => r,
105// Leave error regions alone, since they affect selection b/c of incompleteness.
106ty::ReError(_) => r,
107108 ty::ReEarlyParam(..)
109 | ty::ReLateParam(_)
110 | ty::ReVar(_)
111 | ty::RePlaceholder(..)
112 | ty::ReStatic113 | ty::ReErased => self.cx().lifetimes.re_erased,
114 }
115 }
116117#[inline]
118fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
119if !t.has_infer() && !t.has_erasable_regions() {
120t121 } else {
122match *t.kind() {
123 ty::Infer(v) => self.fold_infer_ty(v),
124125// This code is hot enough that a non-debug assertion here makes a noticeable
126 // difference on benchmarks like `wg-grammar`.
127#[cfg(debug_assertions)]
128 ty::Placeholder(..) | ty::Bound(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0:?}", t))bug!("unexpected type {:?}", t),
129130_ => t.super_fold_with(self),
131 }
132 }
133 }
134135fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
136match ct.kind() {
137 ty::ConstKind::Infer(ty::InferConst::Var(v)) => {
138let mut inner = self.infcx.inner.borrow_mut();
139match inner.const_unification_table().probe_value(v).known() {
140Some(const_) => {
141drop(inner);
142const_.fold_with(self)
143 }
144None => {
145let input =
146 ty::InferConst::Var(inner.const_unification_table().find(v).vid);
147self.freshen_const(input, ty::InferConst::Fresh)
148 }
149 }
150 }
151 ty::ConstKind::Infer(ty::InferConst::Fresh(_)) => {
152::rustc_middle::util::bug::bug_fmt(format_args!("trying to freshen already-freshened const {0:?}",
ct));bug!("trying to freshen already-freshened const {ct:?}");
153 }
154155 ty::ConstKind::Bound(..) | ty::ConstKind::Placeholder(_) => {
156::rustc_middle::util::bug::bug_fmt(format_args!("unexpected const {0:?}", ct))bug!("unexpected const {ct:?}")157 }
158159 ty::ConstKind::Param(_)
160 | ty::ConstKind::Value(_)
161 | ty::ConstKind::Alias(..)
162 | ty::ConstKind::Expr(..)
163 | ty::ConstKind::Error(_) => ct.super_fold_with(self),
164 }
165 }
166}
167168impl<'a, 'tcx> TypeFreshener<'a, 'tcx> {
169// This is separate from `fold_ty` to keep that method small and inlinable.
170#[inline(never)]
171fn fold_infer_ty(&mut self, ty: ty::InferTy) -> Ty<'tcx> {
172match ty {
173 ty::TyVar(v) => {
174let mut inner = self.infcx.inner.borrow_mut();
175match inner.type_variables().probe(v).known() {
176Some(ty) => {
177drop(inner);
178ty.fold_with(self)
179 }
180None => {
181let input = ty::TyVar(inner.type_variables().root_var(v));
182self.freshen_ty(input, |n| Ty::new_fresh(self.infcx.tcx, n))
183 }
184 }
185 }
186187 ty::IntVar(v) => {
188let mut inner = self.infcx.inner.borrow_mut();
189let value = inner.int_unification_table().probe_value(v);
190match value {
191 ty::IntVarValue::IntType(ty) => Ty::new_int(self.infcx.tcx, ty),
192 ty::IntVarValue::UintType(ty) => Ty::new_uint(self.infcx.tcx, ty),
193 ty::IntVarValue::Unknown => {
194let input = ty::IntVar(inner.int_unification_table().find(v));
195self.freshen_ty(input, |n| Ty::new_fresh_int(self.infcx.tcx, n))
196 }
197 }
198 }
199200 ty::FloatVar(v) => {
201let mut inner = self.infcx.inner.borrow_mut();
202let value = inner.float_unification_table().probe_value(v);
203match value {
204 ty::FloatVarValue::Known(ty) => Ty::new_float(self.infcx.tcx, ty),
205 ty::FloatVarValue::Unknown => {
206let input = ty::FloatVar(inner.float_unification_table().find(v));
207self.freshen_ty(input, |n| Ty::new_fresh_float(self.infcx.tcx, n))
208 }
209 }
210 }
211212 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => {
213::rustc_middle::util::bug::bug_fmt(format_args!("trying to freshen already-freshened type {0:?}",
ty));bug!("trying to freshen already-freshened type {ty:?}");
214 }
215 }
216 }
217}