1 //! Unification and canonicalization logic.
3 use std::{fmt, mem, sync::Arc};
6 cast::Cast, fold::Fold, interner::HasInterner, zip::Zip, FloatTy, IntTy, TyVariableKind,
9 use chalk_solve::infer::ParameterEnaVariableExt;
10 use ena::unify::UnifyKey;
12 use super::{InferOk, InferResult, InferenceContext, TypeError};
14 db::HirDatabase, fold_tys, static_lifetime, AliasEq, AliasTy, BoundVar, Canonical,
15 DebruijnIndex, GenericArg, Goal, Guidance, InEnvironment, InferenceVar, Interner, ProjectionTy,
16 Scalar, Solution, Substitution, TraitEnvironment, Ty, TyKind, VariableKind,
19 impl<'a> InferenceContext<'a> {
20 pub(super) fn canonicalize<T: Fold<Interner> + HasInterner<Interner = Interner>>(
23 ) -> Canonicalized<T::Result>
25 T::Result: HasInterner<Interner = Interner>,
27 // try to resolve obligations before canonicalizing, since this might
28 // result in new knowledge about variables
29 self.resolve_obligations_as_possible();
30 self.table.canonicalize(t)
34 #[derive(Debug, Clone)]
35 pub(super) struct Canonicalized<T>
37 T: HasInterner<Interner = Interner>,
39 pub(super) value: Canonical<T>,
40 free_vars: Vec<GenericArg>,
43 impl<T: HasInterner<Interner = Interner>> Canonicalized<T> {
44 pub(super) fn decanonicalize_ty(&self, ty: Ty) -> Ty {
45 chalk_ir::Substitute::apply(&self.free_vars, ty, &Interner)
48 pub(super) fn apply_solution(
50 ctx: &mut InferenceTable,
51 solution: Canonical<Substitution>,
53 // the solution may contain new variables, which we need to convert to new inference vars
54 let new_vars = Substitution::from_iter(
56 solution.binders.iter(&Interner).map(|k| match k.kind {
57 VariableKind::Ty(TyVariableKind::General) => ctx.new_type_var().cast(&Interner),
58 VariableKind::Ty(TyVariableKind::Integer) => ctx.new_integer_var().cast(&Interner),
59 VariableKind::Ty(TyVariableKind::Float) => ctx.new_float_var().cast(&Interner),
60 // Chalk can sometimes return new lifetime variables. We just use the static lifetime everywhere
61 VariableKind::Lifetime => static_lifetime().cast(&Interner),
62 _ => panic!("const variable in solution"),
65 for (i, v) in solution.value.iter(&Interner).enumerate() {
66 let var = self.free_vars[i].clone();
67 if let Some(ty) = v.ty(&Interner) {
68 // eagerly replace projections in the type; we may be getting types
69 // e.g. from where clauses where this hasn't happened yet
70 let ty = ctx.normalize_associated_types_in(new_vars.apply(ty.clone(), &Interner));
71 ctx.unify(var.assert_ty_ref(&Interner), &ty);
73 let _ = ctx.try_unify(&var, &new_vars.apply(v.clone(), &Interner));
81 env: Arc<TraitEnvironment>,
82 tys: &Canonical<(Ty, Ty)>,
84 unify(db, env, tys).is_some()
89 env: Arc<TraitEnvironment>,
90 tys: &Canonical<(Ty, Ty)>,
91 ) -> Option<Substitution> {
92 let mut table = InferenceTable::new(db, env);
93 let vars = Substitution::from_iter(
97 // we always use type vars here because we want everything to
98 // fallback to Unknown in the end (kind of hacky, as below)
99 .map(|_| table.new_type_var()),
101 let ty1_with_vars = vars.apply(tys.value.0.clone(), &Interner);
102 let ty2_with_vars = vars.apply(tys.value.1.clone(), &Interner);
103 if !table.unify(&ty1_with_vars, &ty2_with_vars) {
106 // default any type vars that weren't unified back to their original bound vars
108 let find_var = |iv| {
109 vars.iter(&Interner).position(|v| match v.interned() {
110 chalk_ir::GenericArgData::Ty(ty) => ty.inference_var(&Interner),
111 chalk_ir::GenericArgData::Lifetime(lt) => lt.inference_var(&Interner),
112 chalk_ir::GenericArgData::Const(c) => c.inference_var(&Interner),
115 let fallback = |iv, kind, default, binder| match kind {
116 chalk_ir::VariableKind::Ty(_ty_kind) => find_var(iv)
117 .map_or(default, |i| BoundVar::new(binder, i).to_ty(&Interner).cast(&Interner)),
118 chalk_ir::VariableKind::Lifetime => find_var(iv)
119 .map_or(default, |i| BoundVar::new(binder, i).to_lifetime(&Interner).cast(&Interner)),
120 chalk_ir::VariableKind::Const(ty) => find_var(iv)
121 .map_or(default, |i| BoundVar::new(binder, i).to_const(&Interner, ty).cast(&Interner)),
123 Some(Substitution::from_iter(
126 .map(|v| table.resolve_with_fallback(v.assert_ty_ref(&Interner).clone(), fallback)),
130 #[derive(Copy, Clone, Debug)]
131 pub(crate) struct TypeVariableData {
135 type ChalkInferenceTable = chalk_solve::infer::InferenceTable<Interner>;
138 pub(crate) struct InferenceTable<'a> {
139 pub(crate) db: &'a dyn HirDatabase,
140 pub(crate) trait_env: Arc<TraitEnvironment>,
141 var_unification_table: ChalkInferenceTable,
142 type_variable_table: Vec<TypeVariableData>,
143 pending_obligations: Vec<Canonicalized<InEnvironment<Goal>>>,
146 impl<'a> InferenceTable<'a> {
147 pub(crate) fn new(db: &'a dyn HirDatabase, trait_env: Arc<TraitEnvironment>) -> Self {
151 var_unification_table: ChalkInferenceTable::new(),
152 type_variable_table: Vec::new(),
153 pending_obligations: Vec::new(),
157 /// Chalk doesn't know about the `diverging` flag, so when it unifies two
158 /// type variables of which one is diverging, the chosen root might not be
159 /// diverging and we have no way of marking it as such at that time. This
160 /// function goes through all type variables and make sure their root is
161 /// marked as diverging if necessary, so that resolving them gives the right
163 pub(super) fn propagate_diverging_flag(&mut self) {
164 for i in 0..self.type_variable_table.len() {
165 if !self.type_variable_table[i].diverging {
168 let v = InferenceVar::from(i as u32);
169 let root = self.var_unification_table.inference_var_root(v);
170 if let Some(data) = self.type_variable_table.get_mut(root.index() as usize) {
171 data.diverging = true;
176 pub(super) fn set_diverging(&mut self, iv: InferenceVar, diverging: bool) {
177 self.type_variable_table[iv.index() as usize].diverging = diverging;
180 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty {
184 .get(iv.index() as usize)
185 .map_or(false, |data| data.diverging) =>
189 TyVariableKind::General => TyKind::Error,
190 TyVariableKind::Integer => TyKind::Scalar(Scalar::Int(IntTy::I32)),
191 TyVariableKind::Float => TyKind::Scalar(Scalar::Float(FloatTy::F64)),
196 pub(super) fn canonicalize<T: Fold<Interner> + HasInterner<Interner = Interner>>(
199 ) -> Canonicalized<T::Result>
201 T::Result: HasInterner<Interner = Interner>,
203 let result = self.var_unification_table.canonicalize(&Interner, t);
204 let free_vars = result
207 .map(|free_var| free_var.to_generic_arg(&Interner))
209 Canonicalized { value: result.quantified, free_vars }
212 /// Recurses through the given type, normalizing associated types mentioned
213 /// in it by replacing them by type variables and registering obligations to
214 /// resolve later. This should be done once for every type we get from some
215 /// type annotation (e.g. from a let type annotation, field type or function
216 /// call). `make_ty` handles this already, but e.g. for field types we need
217 /// to do it as well.
218 pub(super) fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
221 |ty, _| match ty.kind(&Interner) {
222 TyKind::Alias(AliasTy::Projection(proj_ty)) => {
223 self.normalize_projection_ty(proj_ty.clone())
227 DebruijnIndex::INNERMOST,
231 pub(super) fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty {
232 let var = self.new_type_var();
233 let alias_eq = AliasEq { alias: AliasTy::Projection(proj_ty), ty: var.clone() };
234 let obligation = alias_eq.cast(&Interner);
235 self.register_obligation(obligation);
239 fn extend_type_variable_table(&mut self, to_index: usize) {
240 self.type_variable_table.extend(
241 (0..1 + to_index - self.type_variable_table.len())
242 .map(|_| TypeVariableData { diverging: false }),
246 fn new_var(&mut self, kind: TyVariableKind, diverging: bool) -> Ty {
247 let var = self.var_unification_table.new_variable(UniverseIndex::ROOT);
248 // Chalk might have created some type variables for its own purposes that we don't know about...
249 self.extend_type_variable_table(var.index() as usize);
250 assert_eq!(var.index() as usize, self.type_variable_table.len() - 1);
251 self.type_variable_table[var.index() as usize].diverging = diverging;
252 var.to_ty_with_kind(&Interner, kind)
255 pub(crate) fn new_type_var(&mut self) -> Ty {
256 self.new_var(TyVariableKind::General, false)
259 pub(crate) fn new_integer_var(&mut self) -> Ty {
260 self.new_var(TyVariableKind::Integer, false)
263 pub(crate) fn new_float_var(&mut self) -> Ty {
264 self.new_var(TyVariableKind::Float, false)
267 pub(crate) fn new_maybe_never_var(&mut self) -> Ty {
268 self.new_var(TyVariableKind::General, true)
271 pub(crate) fn resolve_with_fallback<T>(
274 fallback: impl Fn(InferenceVar, VariableKind, GenericArg, DebruijnIndex) -> GenericArg,
277 T: HasInterner<Interner = Interner> + Fold<Interner>,
279 self.resolve_with_fallback_inner(&mut Vec::new(), t, &fallback)
282 fn resolve_with_fallback_inner<T>(
284 var_stack: &mut Vec<InferenceVar>,
286 fallback: &impl Fn(InferenceVar, VariableKind, GenericArg, DebruijnIndex) -> GenericArg,
289 T: HasInterner<Interner = Interner> + Fold<Interner>,
292 &mut resolve::Resolver { table: self, var_stack, fallback },
293 DebruijnIndex::INNERMOST,
295 .expect("fold failed unexpectedly")
298 pub(crate) fn resolve_completely<T>(&mut self, t: T) -> T::Result
300 T: HasInterner<Interner = Interner> + Fold<Interner>,
302 self.resolve_with_fallback(t, |_, _, d, _| d)
305 /// Unify two types and register new trait goals that arise from that.
306 pub(crate) fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
307 let result = if let Ok(r) = self.try_unify(ty1, ty2) {
312 self.register_infer_ok(result);
316 /// Unify two types and return new trait goals arising from it, so the
317 /// caller needs to deal with them.
318 pub(crate) fn try_unify<T: Zip<Interner>>(&mut self, t1: &T, t2: &T) -> InferResult {
319 match self.var_unification_table.relate(
323 chalk_ir::Variance::Invariant,
327 Ok(result) => Ok(InferOk { goals: result.goals }),
328 Err(chalk_ir::NoSolution) => Err(TypeError),
332 /// If `ty` is a type variable with known type, returns that type;
333 /// otherwise, return ty.
334 pub(crate) fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
335 self.var_unification_table.normalize_ty_shallow(&Interner, ty).unwrap_or_else(|| ty.clone())
338 pub(crate) fn register_obligation(&mut self, goal: Goal) {
339 let in_env = InEnvironment::new(&self.trait_env.env, goal);
340 self.register_obligation_in_env(in_env)
343 fn register_obligation_in_env(&mut self, goal: InEnvironment<Goal>) {
344 let canonicalized = self.canonicalize(goal);
345 if !self.try_resolve_obligation(&canonicalized) {
346 self.pending_obligations.push(canonicalized);
350 pub(crate) fn register_infer_ok(&mut self, infer_ok: InferOk) {
351 infer_ok.goals.into_iter().for_each(|goal| self.register_obligation_in_env(goal));
354 pub(crate) fn resolve_obligations_as_possible(&mut self) {
355 let _span = profile::span("resolve_obligations_as_possible");
356 let mut changed = true;
357 let mut obligations = Vec::new();
360 mem::swap(&mut self.pending_obligations, &mut obligations);
361 for canonicalized in obligations.drain(..) {
362 if !self.check_changed(&canonicalized) {
363 self.pending_obligations.push(canonicalized);
367 let uncanonical = chalk_ir::Substitute::apply(
368 &canonicalized.free_vars,
369 canonicalized.value.value,
372 self.register_obligation_in_env(uncanonical);
377 /// This checks whether any of the free variables in the `canonicalized`
378 /// have changed (either been unified with another variable, or with a
379 /// value). If this is not the case, we don't need to try to solve the goal
380 /// again -- it'll give the same result as last time.
381 fn check_changed(&mut self, canonicalized: &Canonicalized<InEnvironment<Goal>>) -> bool {
382 canonicalized.free_vars.iter().any(|var| {
383 let iv = match var.data(&Interner) {
384 chalk_ir::GenericArgData::Ty(ty) => ty.inference_var(&Interner),
385 chalk_ir::GenericArgData::Lifetime(lt) => lt.inference_var(&Interner),
386 chalk_ir::GenericArgData::Const(c) => c.inference_var(&Interner),
388 .expect("free var is not inference var");
389 if self.var_unification_table.probe_var(iv).is_some() {
392 let root = self.var_unification_table.inference_var_root(iv);
397 fn try_resolve_obligation(
399 canonicalized: &Canonicalized<InEnvironment<Goal>>,
401 let solution = self.db.trait_solve(self.trait_env.krate, canonicalized.value.clone());
404 Some(Solution::Unique(canonical_subst)) => {
405 canonicalized.apply_solution(
408 binders: canonical_subst.binders,
409 // FIXME: handle constraints
410 value: canonical_subst.value.subst,
415 Some(Solution::Ambig(Guidance::Definite(substs))) => {
416 canonicalized.apply_solution(self, substs);
420 // FIXME use this when trying to resolve everything at the end
424 // FIXME obligation cannot be fulfilled => diagnostic
431 impl<'a> fmt::Debug for InferenceTable<'a> {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.debug_struct("InferenceTable").field("num_vars", &self.type_variable_table.len()).finish()
438 use super::InferenceTable;
440 ConcreteConst, Const, ConstData, ConstValue, DebruijnIndex, GenericArg, InferenceVar,
441 Interner, Lifetime, Ty, TyVariableKind, VariableKind,
445 fold::{Fold, Folder},
448 use hir_def::type_ref::ConstScalar;
450 pub(super) struct Resolver<'a, 'b, F> {
451 pub(super) table: &'a mut InferenceTable<'b>,
452 pub(super) var_stack: &'a mut Vec<InferenceVar>,
453 pub(super) fallback: F,
455 impl<'a, 'b, 'i, F> Folder<'i, Interner> for Resolver<'a, 'b, F>
457 F: Fn(InferenceVar, VariableKind, GenericArg, DebruijnIndex) -> GenericArg + 'i,
459 fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
463 fn interner(&self) -> &'i Interner {
467 fn fold_inference_ty(
470 kind: TyVariableKind,
471 outer_binder: DebruijnIndex,
473 let var = self.table.var_unification_table.inference_var_root(var);
474 if self.var_stack.contains(&var) {
476 let default = self.table.fallback_value(var, kind).cast(&Interner);
477 return Ok((self.fallback)(var, VariableKind::Ty(kind), default, outer_binder)
478 .assert_ty_ref(&Interner)
481 let result = if let Some(known_ty) = self.table.var_unification_table.probe_var(var) {
482 // known_ty may contain other variables that are known by now
483 self.var_stack.push(var);
485 known_ty.fold_with(self, outer_binder).expect("fold failed unexpectedly");
486 self.var_stack.pop();
487 result.assert_ty_ref(&Interner).clone()
489 let default = self.table.fallback_value(var, kind).cast(&Interner);
490 (self.fallback)(var, VariableKind::Ty(kind), default, outer_binder)
491 .assert_ty_ref(&Interner)
497 fn fold_inference_const(
501 outer_binder: DebruijnIndex,
502 ) -> Fallible<Const> {
503 let var = self.table.var_unification_table.inference_var_root(var);
504 let default = ConstData {
506 value: ConstValue::Concrete(ConcreteConst { interned: ConstScalar::Unknown }),
510 if self.var_stack.contains(&var) {
512 return Ok((self.fallback)(var, VariableKind::Const(ty), default, outer_binder)
513 .assert_const_ref(&Interner)
516 let result = if let Some(known_ty) = self.table.var_unification_table.probe_var(var) {
517 // known_ty may contain other variables that are known by now
518 self.var_stack.push(var);
520 known_ty.fold_with(self, outer_binder).expect("fold failed unexpectedly");
521 self.var_stack.pop();
522 result.assert_const_ref(&Interner).clone()
524 (self.fallback)(var, VariableKind::Const(ty), default, outer_binder)
525 .assert_const_ref(&Interner)
531 fn fold_inference_lifetime(
534 _outer_binder: DebruijnIndex,
535 ) -> Fallible<Lifetime> {
536 // fall back all lifetimes to 'static -- currently we don't deal
537 // with any lifetimes, but we can sometimes get some lifetime
538 // variables through Chalk's unification, and this at least makes
539 // sure we don't leak them outside of inference
540 Ok(crate::static_lifetime())