flux_infer/
infer.rs

1use std::{cell::RefCell, fmt, iter};
2
3use flux_common::{bug, dbg, tracked_span_assert_eq, tracked_span_dbg_assert_eq};
4use flux_config::{self as config, InferOpts};
5use flux_macros::{TypeFoldable, TypeVisitable};
6use flux_middle::{
7    FixpointQueryKind,
8    def_id::MaybeExternId,
9    global_env::GlobalEnv,
10    queries::{QueryErr, QueryResult},
11    query_bug,
12    rty::{
13        self, AliasKind, AliasTy, BaseTy, Binder, BoundVariableKinds, CoroutineObligPredicate,
14        Ctor, ESpan, EVid, EarlyBinder, Expr, ExprKind, FieldProj, GenericArg, HoleKind, InferMode,
15        Lambda, List, Loc, Mutability, Name, Path, PolyVariant, PtrKind, RefineArgs, RefineArgsExt,
16        Region, Sort, Ty, TyCtor, TyKind, Var,
17        canonicalize::{Hoister, HoisterDelegate},
18        fold::TypeFoldable,
19    },
20};
21use itertools::{Itertools, izip};
22use rustc_hir::def_id::{DefId, LocalDefId};
23use rustc_macros::extension;
24use rustc_middle::{
25    mir::BasicBlock,
26    ty::{TyCtxt, Variance},
27};
28use rustc_span::Span;
29
30use crate::{
31    evars::{EVarState, EVarStore},
32    fixpoint_encoding::{FixQueryCache, FixpointCtxt, KVarEncoding, KVarGen},
33    projections::NormalizeExt as _,
34    refine_tree::{Cursor, Marker, RefineTree, Scope},
35};
36
37pub type InferResult<T = ()> = std::result::Result<T, InferErr>;
38
39#[derive(PartialEq, Eq, Clone, Copy, Hash)]
40pub struct Tag {
41    pub reason: ConstrReason,
42    pub src_span: Span,
43    pub dst_span: Option<ESpan>,
44}
45
46impl Tag {
47    pub fn new(reason: ConstrReason, span: Span) -> Self {
48        Self { reason, src_span: span, dst_span: None }
49    }
50
51    pub fn with_dst(self, dst_span: Option<ESpan>) -> Self {
52        Self { dst_span, ..self }
53    }
54}
55
56#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
57pub enum SubtypeReason {
58    Input,
59    Output,
60    Requires,
61    Ensures,
62}
63
64#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
65pub enum ConstrReason {
66    Call,
67    Assign,
68    Ret,
69    Fold,
70    FoldLocal,
71    Predicate,
72    Assert(&'static str),
73    Div,
74    Rem,
75    Goto(BasicBlock),
76    Overflow,
77    Subtype(SubtypeReason),
78    Other,
79}
80
81pub struct InferCtxtRoot<'genv, 'tcx> {
82    pub genv: GlobalEnv<'genv, 'tcx>,
83    inner: RefCell<InferCtxtInner>,
84    refine_tree: RefineTree,
85    opts: InferOpts,
86}
87
88pub struct InferCtxtRootBuilder<'a, 'genv, 'tcx> {
89    genv: GlobalEnv<'genv, 'tcx>,
90    opts: InferOpts,
91    params: Vec<(Var, Sort)>,
92    infcx: &'a rustc_infer::infer::InferCtxt<'tcx>,
93    dummy_kvars: bool,
94}
95
96#[extension(pub trait GlobalEnvExt<'genv, 'tcx>)]
97impl<'genv, 'tcx> GlobalEnv<'genv, 'tcx> {
98    fn infcx_root<'a>(
99        self,
100        infcx: &'a rustc_infer::infer::InferCtxt<'tcx>,
101        opts: InferOpts,
102    ) -> InferCtxtRootBuilder<'a, 'genv, 'tcx> {
103        InferCtxtRootBuilder { genv: self, infcx, params: vec![], opts, dummy_kvars: false }
104    }
105}
106
107impl<'genv, 'tcx> InferCtxtRootBuilder<'_, 'genv, 'tcx> {
108    pub fn with_dummy_kvars(mut self) -> Self {
109        self.dummy_kvars = true;
110        self
111    }
112
113    pub fn with_const_generics(mut self, def_id: DefId) -> QueryResult<Self> {
114        self.params.extend(
115            self.genv
116                .generics_of(def_id)?
117                .const_params(self.genv)?
118                .into_iter()
119                .map(|(pcst, sort)| (Var::ConstGeneric(pcst), sort)),
120        );
121        Ok(self)
122    }
123
124    pub fn with_refinement_generics(
125        mut self,
126        def_id: DefId,
127        args: &[GenericArg],
128    ) -> QueryResult<Self> {
129        for (index, param) in self
130            .genv
131            .refinement_generics_of(def_id)?
132            .iter_own_params()
133            .enumerate()
134        {
135            let param = param.instantiate(self.genv.tcx(), args, &[]);
136            let sort = param.sort.normalize_sorts(def_id, self.genv, self.infcx)?;
137
138            let var =
139                Var::EarlyParam(rty::EarlyReftParam { index: index as u32, name: param.name });
140            self.params.push((var, sort));
141        }
142        Ok(self)
143    }
144
145    pub fn identity_for_item(mut self, def_id: DefId) -> QueryResult<Self> {
146        self = self.with_const_generics(def_id)?;
147        let offset = self.params.len();
148        self.genv.refinement_generics_of(def_id)?.fill_item(
149            self.genv,
150            &mut self.params,
151            &mut |param, index| {
152                let index = (index - offset) as u32;
153                let param = param.instantiate_identity();
154                let sort = param.sort.normalize_sorts(def_id, self.genv, self.infcx)?;
155
156                let var = Var::EarlyParam(rty::EarlyReftParam { index, name: param.name });
157                Ok((var, sort))
158            },
159        )?;
160        Ok(self)
161    }
162
163    pub fn build(self) -> QueryResult<InferCtxtRoot<'genv, 'tcx>> {
164        Ok(InferCtxtRoot {
165            genv: self.genv,
166            inner: RefCell::new(InferCtxtInner::new(self.dummy_kvars)),
167            refine_tree: RefineTree::new(self.params),
168            opts: self.opts,
169        })
170    }
171}
172
173impl<'genv, 'tcx> InferCtxtRoot<'genv, 'tcx> {
174    pub fn infcx<'a>(
175        &'a mut self,
176        def_id: DefId,
177        region_infcx: &'a rustc_infer::infer::InferCtxt<'tcx>,
178    ) -> InferCtxt<'a, 'genv, 'tcx> {
179        InferCtxt {
180            genv: self.genv,
181            region_infcx,
182            def_id,
183            cursor: self.refine_tree.cursor_at_root(),
184            inner: &self.inner,
185            check_overflow: self.opts.check_overflow,
186        }
187    }
188
189    pub fn fresh_kvar_in_scope(
190        &self,
191        binders: &[BoundVariableKinds],
192        scope: &Scope,
193        encoding: KVarEncoding,
194    ) -> Expr {
195        let inner = &mut *self.inner.borrow_mut();
196        inner.kvars.fresh(binders, scope.iter(), encoding)
197    }
198
199    pub fn execute_fixpoint_query(
200        self,
201        cache: &mut FixQueryCache,
202        def_id: MaybeExternId,
203        kind: FixpointQueryKind,
204    ) -> QueryResult<Vec<Tag>> {
205        let inner = self.inner.into_inner();
206        let kvars = inner.kvars;
207        let evars = inner.evars;
208
209        let ext = kind.ext();
210
211        let mut refine_tree = self.refine_tree;
212
213        refine_tree.replace_evars(&evars).unwrap();
214
215        if config::dump_constraint() {
216            dbg::dump_item_info(self.genv.tcx(), def_id.resolved_id(), ext, &refine_tree).unwrap();
217        }
218        refine_tree.simplify(self.genv);
219        if config::dump_constraint() {
220            let simp_ext = format!("simp.{}", ext);
221            dbg::dump_item_info(self.genv.tcx(), def_id.resolved_id(), simp_ext, &refine_tree)
222                .unwrap();
223        }
224
225        let mut fcx = FixpointCtxt::new(self.genv, def_id, kvars);
226        let cstr = refine_tree.into_fixpoint(&mut fcx)?;
227
228        let backend = match self.opts.solver {
229            flux_config::SmtSolver::Z3 => liquid_fixpoint::SmtSolver::Z3,
230            flux_config::SmtSolver::CVC5 => liquid_fixpoint::SmtSolver::CVC5,
231        };
232
233        fcx.check(cache, cstr, kind, self.opts.scrape_quals, backend)
234    }
235
236    pub fn split(self) -> (RefineTree, KVarGen) {
237        (self.refine_tree, self.inner.into_inner().kvars)
238    }
239}
240
241pub struct InferCtxt<'infcx, 'genv, 'tcx> {
242    pub genv: GlobalEnv<'genv, 'tcx>,
243    pub region_infcx: &'infcx rustc_infer::infer::InferCtxt<'tcx>,
244    pub def_id: DefId,
245    pub check_overflow: bool,
246    cursor: Cursor<'infcx>,
247    inner: &'infcx RefCell<InferCtxtInner>,
248}
249
250struct InferCtxtInner {
251    kvars: KVarGen,
252    evars: EVarStore,
253}
254
255impl InferCtxtInner {
256    fn new(dummy_kvars: bool) -> Self {
257        Self { kvars: KVarGen::new(dummy_kvars), evars: Default::default() }
258    }
259}
260
261impl<'infcx, 'genv, 'tcx> InferCtxt<'infcx, 'genv, 'tcx> {
262    pub fn at(&mut self, span: Span) -> InferCtxtAt<'_, 'infcx, 'genv, 'tcx> {
263        InferCtxtAt { infcx: self, span }
264    }
265
266    pub fn instantiate_refine_args(
267        &mut self,
268        callee_def_id: DefId,
269        args: &[rty::GenericArg],
270    ) -> InferResult<List<Expr>> {
271        Ok(RefineArgs::for_item(self.genv, callee_def_id, |param, _| {
272            let param = param.instantiate(self.genv.tcx(), args, &[]);
273            Ok(self.fresh_infer_var(&param.sort, param.mode))
274        })?)
275    }
276
277    pub fn instantiate_generic_args(&mut self, args: &[GenericArg]) -> Vec<GenericArg> {
278        args.iter()
279            .map(|a| a.replace_holes(|binders, kind| self.fresh_infer_var_for_hole(binders, kind)))
280            .collect_vec()
281    }
282
283    pub fn fresh_infer_var(&self, sort: &Sort, mode: InferMode) -> Expr {
284        match mode {
285            InferMode::KVar => {
286                let fsort = sort.expect_func().expect_mono();
287                let vars = fsort.inputs().iter().cloned().map_into().collect();
288                let kvar = self.fresh_kvar(&[vars], KVarEncoding::Single);
289                Expr::abs(Lambda::bind_with_fsort(kvar, fsort))
290            }
291            InferMode::EVar => self.fresh_evar(),
292        }
293    }
294
295    pub fn fresh_infer_var_for_hole(
296        &mut self,
297        binders: &[BoundVariableKinds],
298        kind: HoleKind,
299    ) -> Expr {
300        match kind {
301            HoleKind::Pred => self.fresh_kvar(binders, KVarEncoding::Conj),
302            HoleKind::Expr(_) => {
303                // We only use expression holes to infer early param arguments for opaque types
304                // at function calls. These should be well-scoped in the current scope, so we ignore
305                // the extra `binders` around the hole.
306                self.fresh_evar()
307            }
308        }
309    }
310
311    /// Generate a fresh kvar in the _given_ [`Scope`] (similar method in [`InferCtxtRoot`]).
312    pub fn fresh_kvar_in_scope(
313        &self,
314        binders: &[BoundVariableKinds],
315        scope: &Scope,
316        encoding: KVarEncoding,
317    ) -> Expr {
318        let inner = &mut *self.inner.borrow_mut();
319        inner.kvars.fresh(binders, scope.iter(), encoding)
320    }
321
322    /// Generate a fresh kvar in the current scope. See [`KVarGen::fresh`].
323    pub fn fresh_kvar(&self, binders: &[BoundVariableKinds], encoding: KVarEncoding) -> Expr {
324        let inner = &mut *self.inner.borrow_mut();
325        inner.kvars.fresh(binders, self.cursor.vars(), encoding)
326    }
327
328    fn fresh_evar(&self) -> Expr {
329        let evars = &mut self.inner.borrow_mut().evars;
330        Expr::evar(evars.fresh(self.cursor.marker()))
331    }
332
333    pub fn unify_exprs(&self, a: &Expr, b: &Expr) {
334        if a.has_evars() {
335            return;
336        }
337        let evars = &mut self.inner.borrow_mut().evars;
338        if let ExprKind::Var(Var::EVar(evid)) = b.kind()
339            && let EVarState::Unsolved(marker) = evars.get(*evid)
340            && !marker.has_free_vars(a)
341        {
342            evars.solve(*evid, a.clone());
343        }
344    }
345
346    fn enter_exists<T, U>(
347        &mut self,
348        t: &Binder<T>,
349        f: impl FnOnce(&mut InferCtxt<'_, 'genv, 'tcx>, T) -> U,
350    ) -> U
351    where
352        T: TypeFoldable,
353    {
354        self.ensure_resolved_evars(|infcx| {
355            let t = t.replace_bound_refts_with(|sort, mode, _| infcx.fresh_infer_var(sort, mode));
356            Ok(f(infcx, t))
357        })
358        .unwrap()
359    }
360
361    /// Used in conjunction with [`InferCtxt::pop_evar_scope`] to ensure evars are solved at the end
362    /// of some scope, for example, to ensure all evars generated during a function call are solved
363    /// after checking argument subtyping. These functions can be used in a stack-like fashion to
364    /// create nested scopes.
365    pub fn push_evar_scope(&mut self) {
366        self.inner.borrow_mut().evars.push_scope();
367    }
368
369    /// Pop a scope and check all evars have been solved. This only check evars generated from the
370    /// last call to [`InferCtxt::push_evar_scope`].
371    pub fn pop_evar_scope(&mut self) -> InferResult {
372        self.inner
373            .borrow_mut()
374            .evars
375            .pop_scope()
376            .map_err(InferErr::UnsolvedEvar)
377    }
378
379    /// Convenience method pairing [`InferCtxt::push_evar_scope`] and [`InferCtxt::pop_evar_scope`].
380    pub fn ensure_resolved_evars<R>(
381        &mut self,
382        f: impl FnOnce(&mut Self) -> InferResult<R>,
383    ) -> InferResult<R> {
384        self.push_evar_scope();
385        let r = f(self)?;
386        self.pop_evar_scope()?;
387        Ok(r)
388    }
389
390    pub fn fully_resolve_evars<T: TypeFoldable>(&self, t: &T) -> T {
391        self.inner.borrow().evars.replace_evars(t).unwrap()
392    }
393
394    pub fn tcx(&self) -> TyCtxt<'tcx> {
395        self.genv.tcx()
396    }
397
398    pub fn cursor(&self) -> &Cursor<'infcx> {
399        &self.cursor
400    }
401}
402
403/// Methods that interact with the underlying [`Cursor`]
404impl<'infcx, 'genv, 'tcx> InferCtxt<'infcx, 'genv, 'tcx> {
405    pub fn change_item<'a>(
406        &'a mut self,
407        def_id: LocalDefId,
408        region_infcx: &'a rustc_infer::infer::InferCtxt<'tcx>,
409    ) -> InferCtxt<'a, 'genv, 'tcx> {
410        InferCtxt {
411            def_id: def_id.to_def_id(),
412            cursor: self.cursor.branch(),
413            region_infcx,
414            ..*self
415        }
416    }
417
418    pub fn move_to(&mut self, marker: &Marker, clear_children: bool) -> InferCtxt<'_, 'genv, 'tcx> {
419        InferCtxt { cursor: self.cursor.move_to(marker, clear_children).unwrap(), ..*self }
420    }
421
422    pub fn branch(&mut self) -> InferCtxt<'_, 'genv, 'tcx> {
423        InferCtxt { cursor: self.cursor.branch(), ..*self }
424    }
425
426    pub fn define_var(&mut self, sort: &Sort) -> Name {
427        self.cursor.define_var(sort)
428    }
429
430    pub fn check_pred(&mut self, pred: impl Into<Expr>, tag: Tag) {
431        self.cursor.check_pred(pred, tag);
432    }
433
434    pub fn assume_pred(&mut self, pred: impl Into<Expr>) {
435        self.cursor.assume_pred(pred);
436    }
437
438    pub fn unpack(&mut self, ty: &Ty) -> Ty {
439        self.hoister(false).hoist(ty)
440    }
441
442    pub fn marker(&self) -> Marker {
443        self.cursor.marker()
444    }
445
446    pub fn hoister(
447        &mut self,
448        assume_invariants: bool,
449    ) -> Hoister<Unpacker<'_, 'infcx, 'genv, 'tcx>> {
450        Hoister::with_delegate(Unpacker { infcx: self, assume_invariants }).transparent()
451    }
452
453    pub fn assume_invariants(&mut self, ty: &Ty) {
454        self.cursor
455            .assume_invariants(self.genv.tcx(), ty, self.check_overflow);
456    }
457
458    fn check_impl(&mut self, pred1: impl Into<Expr>, pred2: impl Into<Expr>, tag: Tag) {
459        self.cursor.check_impl(pred1, pred2, tag);
460    }
461}
462
463pub struct Unpacker<'a, 'infcx, 'genv, 'tcx> {
464    infcx: &'a mut InferCtxt<'infcx, 'genv, 'tcx>,
465    assume_invariants: bool,
466}
467
468impl HoisterDelegate for Unpacker<'_, '_, '_, '_> {
469    fn hoist_exists(&mut self, ty_ctor: &TyCtor) -> Ty {
470        let ty =
471            ty_ctor.replace_bound_refts_with(|sort, _, _| Expr::fvar(self.infcx.define_var(sort)));
472        if self.assume_invariants {
473            self.infcx.assume_invariants(&ty);
474        }
475        ty
476    }
477
478    fn hoist_constr(&mut self, pred: Expr) {
479        self.infcx.assume_pred(pred);
480    }
481}
482
483impl std::fmt::Debug for InferCtxt<'_, '_, '_> {
484    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485        std::fmt::Debug::fmt(&self.cursor, f)
486    }
487}
488
489#[derive(Debug)]
490pub struct InferCtxtAt<'a, 'infcx, 'genv, 'tcx> {
491    pub infcx: &'a mut InferCtxt<'infcx, 'genv, 'tcx>,
492    pub span: Span,
493}
494
495impl<'genv, 'tcx> InferCtxtAt<'_, '_, 'genv, 'tcx> {
496    fn tag(&self, reason: ConstrReason) -> Tag {
497        Tag::new(reason, self.span)
498    }
499
500    pub fn check_pred(&mut self, pred: impl Into<Expr>, reason: ConstrReason) {
501        let tag = self.tag(reason);
502        self.infcx.check_pred(pred, tag);
503    }
504
505    pub fn check_non_closure_clauses(
506        &mut self,
507        clauses: &[rty::Clause],
508        reason: ConstrReason,
509    ) -> InferResult {
510        for clause in clauses {
511            if let rty::ClauseKind::Projection(projection_pred) = clause.kind_skipping_binder() {
512                let impl_elem = BaseTy::projection(projection_pred.projection_ty)
513                    .to_ty()
514                    .normalize_projections(self)?;
515                let term = projection_pred.term.to_ty().normalize_projections(self)?;
516
517                // TODO: does this really need to be invariant? https://github.com/flux-rs/flux/pull/478#issuecomment-1654035374
518                self.subtyping(&impl_elem, &term, reason)?;
519                self.subtyping(&term, &impl_elem, reason)?;
520            }
521        }
522        Ok(())
523    }
524
525    /// Relate types via subtyping. This is the same as [`InferCtxtAt::subtyping`] except that we
526    /// also require a [`LocEnv`] to handle pointers and strong references
527    pub fn subtyping_with_env(
528        &mut self,
529        env: &mut impl LocEnv,
530        a: &Ty,
531        b: &Ty,
532        reason: ConstrReason,
533    ) -> InferResult {
534        let mut sub = Sub::new(env, reason, self.span);
535        sub.tys(self.infcx, a, b)
536    }
537
538    /// Relate types via subtyping and returns coroutine obligations. This doesn't handle subtyping
539    /// when strong references are involved.
540    ///
541    /// See comment for [`Sub::obligations`].
542    pub fn subtyping(
543        &mut self,
544        a: &Ty,
545        b: &Ty,
546        reason: ConstrReason,
547    ) -> InferResult<Vec<Binder<rty::CoroutineObligPredicate>>> {
548        let mut env = DummyEnv;
549        let mut sub = Sub::new(&mut env, reason, self.span);
550        sub.tys(self.infcx, a, b)?;
551        Ok(sub.obligations)
552    }
553
554    pub fn subtyping_generic_args(
555        &mut self,
556        variance: Variance,
557        a: &GenericArg,
558        b: &GenericArg,
559        reason: ConstrReason,
560    ) -> InferResult<Vec<Binder<rty::CoroutineObligPredicate>>> {
561        let mut env = DummyEnv;
562        let mut sub = Sub::new(&mut env, reason, self.span);
563        sub.generic_args(self.infcx, variance, a, b)?;
564        Ok(sub.obligations)
565    }
566
567    // FIXME(nilehmann) this is similar to `Checker::check_call`, but since is used from
568    // `place_ty::fold` we cannot use that directly. We should try to unify them, because
569    // there are a couple of things missing here (e.g., checking clauses on the struct definition).
570    pub fn check_constructor(
571        &mut self,
572        variant: EarlyBinder<PolyVariant>,
573        generic_args: &[GenericArg],
574        fields: &[Ty],
575        reason: ConstrReason,
576    ) -> InferResult<Ty> {
577        let ret = self.ensure_resolved_evars(|this| {
578            // Replace holes in generic arguments with fresh inference variables
579            let generic_args = this.instantiate_generic_args(generic_args);
580
581            let variant = variant
582                .instantiate(this.tcx(), &generic_args, &[])
583                .replace_bound_refts_with(|sort, mode, _| this.fresh_infer_var(sort, mode));
584
585            // Check arguments
586            for (actual, formal) in iter::zip(fields, variant.fields()) {
587                this.subtyping(actual, formal, reason)?;
588            }
589
590            // Check requires predicates
591            for require in &variant.requires {
592                this.check_pred(require, ConstrReason::Fold);
593            }
594
595            Ok(variant.ret())
596        })?;
597        Ok(self.fully_resolve_evars(&ret))
598    }
599
600    pub fn ensure_resolved_evars<R>(
601        &mut self,
602        f: impl FnOnce(&mut InferCtxtAt<'_, '_, 'genv, 'tcx>) -> InferResult<R>,
603    ) -> InferResult<R> {
604        self.infcx
605            .ensure_resolved_evars(|infcx| f(&mut infcx.at(self.span)))
606    }
607}
608
609impl<'a, 'genv, 'tcx> std::ops::Deref for InferCtxtAt<'_, 'a, 'genv, 'tcx> {
610    type Target = InferCtxt<'a, 'genv, 'tcx>;
611
612    fn deref(&self) -> &Self::Target {
613        self.infcx
614    }
615}
616
617impl std::ops::DerefMut for InferCtxtAt<'_, '_, '_, '_> {
618    fn deref_mut(&mut self) -> &mut Self::Target {
619        self.infcx
620    }
621}
622
623/// Used for debugging to attach a "trace" to the [`RefineTree`] that can be used to print information
624/// to recover the derivation when relating types via subtyping. The code that attaches the trace is
625/// currently commented out because the output is too verbose.
626#[derive(TypeVisitable, TypeFoldable)]
627pub(crate) enum TypeTrace {
628    Types(Ty, Ty),
629    BaseTys(BaseTy, BaseTy),
630}
631
632#[expect(dead_code, reason = "we use this for debugging some time")]
633impl TypeTrace {
634    fn tys(a: &Ty, b: &Ty) -> Self {
635        Self::Types(a.clone(), b.clone())
636    }
637
638    fn btys(a: &BaseTy, b: &BaseTy) -> Self {
639        Self::BaseTys(a.clone(), b.clone())
640    }
641}
642
643impl fmt::Debug for TypeTrace {
644    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645        match self {
646            TypeTrace::Types(a, b) => write!(f, "{a:?} - {b:?}"),
647            TypeTrace::BaseTys(a, b) => write!(f, "{a:?} - {b:?}"),
648        }
649    }
650}
651
652pub trait LocEnv {
653    fn ptr_to_ref(
654        &mut self,
655        infcx: &mut InferCtxtAt,
656        reason: ConstrReason,
657        re: Region,
658        path: &Path,
659        bound: Ty,
660    ) -> InferResult<Ty>;
661
662    fn unfold_strg_ref(&mut self, infcx: &mut InferCtxt, path: &Path, ty: &Ty) -> InferResult<Loc>;
663
664    fn get(&self, path: &Path) -> Ty;
665}
666
667struct DummyEnv;
668
669impl LocEnv for DummyEnv {
670    fn ptr_to_ref(
671        &mut self,
672        _: &mut InferCtxtAt,
673        _: ConstrReason,
674        _: Region,
675        _: &Path,
676        _: Ty,
677    ) -> InferResult<Ty> {
678        bug!("call to `ptr_to_ref` on `DummyEnv`")
679    }
680
681    fn unfold_strg_ref(&mut self, _: &mut InferCtxt, _: &Path, _: &Ty) -> InferResult<Loc> {
682        bug!("call to `unfold_str_ref` on `DummyEnv`")
683    }
684
685    fn get(&self, _: &Path) -> Ty {
686        bug!("call to `get` on `DummyEnv`")
687    }
688}
689
690/// Context used to relate two types `a` and `b` via subtyping
691struct Sub<'a, E> {
692    /// The environment to lookup locations pointed to by [`TyKind::Ptr`].
693    env: &'a mut E,
694    reason: ConstrReason,
695    span: Span,
696    /// FIXME(nilehmann) This is used to store coroutine obligations generated during subtyping when
697    /// relating an opaque type. Other obligations related to relating opaque types are resolved
698    /// directly here. The implementation is really messy and we may be missing some obligations.
699    obligations: Vec<Binder<rty::CoroutineObligPredicate>>,
700}
701
702impl<'a, E: LocEnv> Sub<'a, E> {
703    fn new(env: &'a mut E, reason: ConstrReason, span: Span) -> Self {
704        Self { env, reason, span, obligations: vec![] }
705    }
706
707    fn tag(&self) -> Tag {
708        Tag::new(self.reason, self.span)
709    }
710
711    fn tys(&mut self, infcx: &mut InferCtxt, a: &Ty, b: &Ty) -> InferResult {
712        let infcx = &mut infcx.branch();
713        // infcx.cursor.push_trace(TypeTrace::tys(a, b));
714
715        // We *fully* unpack the lhs before continuing to be able to prove goals like this
716        // ∃a. (i32[a], ∃b. {i32[b] | a > b})} <: ∃a,b. ({i32[a] | b < a}, i32[b])
717        // See S4.5 in https://arxiv.org/pdf/2209.13000v1.pdf
718        let a = infcx.unpack(a);
719
720        match (a.kind(), b.kind()) {
721            (TyKind::Exists(..), _) => {
722                bug!("existentials should have been removed by the unpacking above");
723            }
724            (TyKind::Constr(..), _) => {
725                bug!("constraint types should have been removed by the unpacking above");
726            }
727
728            (_, TyKind::Exists(ctor_b)) => {
729                infcx.enter_exists(ctor_b, |infcx, ty_b| self.tys(infcx, &a, &ty_b))
730            }
731            (_, TyKind::Constr(pred_b, ty_b)) => {
732                infcx.check_pred(pred_b, self.tag());
733                self.tys(infcx, &a, ty_b)
734            }
735
736            (TyKind::Ptr(PtrKind::Mut(_), path_a), TyKind::StrgRef(_, path_b, ty_b)) => {
737                // We should technically remove `path1` from `env`, but we are assuming that functions
738                // always give back ownership of the location so `path1` is going to be overwritten
739                // after the call anyways.
740                let ty_a = self.env.get(path_a);
741                infcx.unify_exprs(&path_a.to_expr(), &path_b.to_expr());
742                self.tys(infcx, &ty_a, ty_b)
743            }
744            (TyKind::StrgRef(_, path_a, ty_a), TyKind::StrgRef(_, path_b, ty_b)) => {
745                // We have to unfold strong references prior to a subtyping check. Normally, when
746                // checking a function body, a `StrgRef` is automatically unfolded i.e. `x:&strg T`
747                // is turned into a `x:ptr(l); l: T` where `l` is some fresh location. However, we
748                // need the below to do a similar unfolding during function subtyping where we just
749                // have the super-type signature that needs to be unfolded. We also add the binding
750                // to the environment so that we can:
751                // (1) UPDATE the location after the call, and
752                // (2) CHECK the relevant `ensures` clauses of the super-sig.
753                // Same as the `Ptr` case above we should remove the location from the environment
754                // after unfolding to consume it, but we are assuming functions always give back
755                // ownership.
756                self.env.unfold_strg_ref(infcx, path_a, ty_a)?;
757                let ty_a = self.env.get(path_a);
758                infcx.unify_exprs(&path_a.to_expr(), &path_b.to_expr());
759                self.tys(infcx, &ty_a, ty_b)
760            }
761            (
762                TyKind::Ptr(PtrKind::Mut(re), path),
763                TyKind::Indexed(BaseTy::Ref(_, bound, Mutability::Mut), idx),
764            ) => {
765                // We sometimes generate evars for the index of references so we need to make sure
766                // we solve them.
767                self.idxs_eq(infcx, &Expr::unit(), idx);
768
769                self.env.ptr_to_ref(
770                    &mut infcx.at(self.span),
771                    self.reason,
772                    *re,
773                    path,
774                    bound.clone(),
775                )?;
776                Ok(())
777            }
778
779            (TyKind::Indexed(bty_a, idx_a), TyKind::Indexed(bty_b, idx_b)) => {
780                self.btys(infcx, bty_a, bty_b)?;
781                self.idxs_eq(infcx, idx_a, idx_b);
782                Ok(())
783            }
784            (TyKind::Ptr(pk_a, path_a), TyKind::Ptr(pk_b, path_b)) => {
785                debug_assert_eq!(pk_a, pk_b);
786                debug_assert_eq!(path_a, path_b);
787                Ok(())
788            }
789            (TyKind::Param(param_ty_a), TyKind::Param(param_ty_b)) => {
790                debug_assert_eq!(param_ty_a, param_ty_b);
791                Ok(())
792            }
793            (_, TyKind::Uninit) => Ok(()),
794            (TyKind::Downcast(.., fields_a), TyKind::Downcast(.., fields_b)) => {
795                debug_assert_eq!(fields_a.len(), fields_b.len());
796                for (ty_a, ty_b) in iter::zip(fields_a, fields_b) {
797                    self.tys(infcx, ty_a, ty_b)?;
798                }
799                Ok(())
800            }
801            _ => Err(query_bug!("incompatible types: `{a:?}` - `{b:?}`"))?,
802        }
803    }
804
805    fn btys(&mut self, infcx: &mut InferCtxt, a: &BaseTy, b: &BaseTy) -> InferResult {
806        // infcx.push_trace(TypeTrace::btys(a, b));
807
808        match (a, b) {
809            (BaseTy::Int(int_ty_a), BaseTy::Int(int_ty_b)) => {
810                debug_assert_eq!(int_ty_a, int_ty_b);
811                Ok(())
812            }
813            (BaseTy::Uint(uint_ty_a), BaseTy::Uint(uint_ty_b)) => {
814                debug_assert_eq!(uint_ty_a, uint_ty_b);
815                Ok(())
816            }
817            (BaseTy::Adt(a_adt, a_args), BaseTy::Adt(b_adt, b_args)) => {
818                tracked_span_dbg_assert_eq!(a_adt.did(), b_adt.did());
819                tracked_span_dbg_assert_eq!(a_args.len(), b_args.len());
820                let variances = infcx.genv.variances_of(a_adt.did());
821                for (variance, ty_a, ty_b) in izip!(variances, a_args.iter(), b_args.iter()) {
822                    self.generic_args(infcx, *variance, ty_a, ty_b)?;
823                }
824                Ok(())
825            }
826            (BaseTy::FnDef(a_def_id, a_args), BaseTy::FnDef(b_def_id, b_args)) => {
827                debug_assert_eq!(a_def_id, b_def_id);
828                debug_assert_eq!(a_args.len(), b_args.len());
829                // NOTE: we don't check subtyping here because the RHS is *really*
830                // the function type, the LHS is just generated by rustc.
831                // we could generate a subtyping constraint but those would
832                // just be trivial (but might cause useless cycles in fixpoint).
833                // Nico: (This is probably ok because) We never do function
834                // subtyping between `FnDef` *except* when (the def_id) is
835                // passed as an argument to a function.
836                for (arg_a, arg_b) in iter::zip(a_args, b_args) {
837                    match (arg_a, arg_b) {
838                        (GenericArg::Ty(ty_a), GenericArg::Ty(ty_b)) => {
839                            let bty_a = ty_a.as_bty_skipping_existentials();
840                            let bty_b = ty_b.as_bty_skipping_existentials();
841                            tracked_span_dbg_assert_eq!(bty_a, bty_b);
842                        }
843                        (GenericArg::Base(ctor_a), GenericArg::Base(ctor_b)) => {
844                            let bty_a = ctor_a.as_bty_skipping_binder();
845                            let bty_b = ctor_b.as_bty_skipping_binder();
846                            tracked_span_dbg_assert_eq!(bty_a, bty_b);
847                        }
848                        (_, _) => tracked_span_dbg_assert_eq!(arg_a, arg_b),
849                    }
850                }
851                Ok(())
852            }
853            (BaseTy::Float(float_ty_a), BaseTy::Float(float_ty_b)) => {
854                debug_assert_eq!(float_ty_a, float_ty_b);
855                Ok(())
856            }
857            (BaseTy::Slice(ty_a), BaseTy::Slice(ty_b)) => self.tys(infcx, ty_a, ty_b),
858            (BaseTy::Ref(_, ty_a, Mutability::Mut), BaseTy::Ref(_, ty_b, Mutability::Mut)) => {
859                self.tys(infcx, ty_a, ty_b)?;
860                self.tys(infcx, ty_b, ty_a)
861            }
862            (BaseTy::Ref(_, ty_a, Mutability::Not), BaseTy::Ref(_, ty_b, Mutability::Not)) => {
863                self.tys(infcx, ty_a, ty_b)
864            }
865            (BaseTy::Tuple(tys_a), BaseTy::Tuple(tys_b)) => {
866                debug_assert_eq!(tys_a.len(), tys_b.len());
867                for (ty_a, ty_b) in iter::zip(tys_a, tys_b) {
868                    self.tys(infcx, ty_a, ty_b)?;
869                }
870                Ok(())
871            }
872            (_, BaseTy::Alias(AliasKind::Opaque, alias_ty_b)) => {
873                if let BaseTy::Alias(AliasKind::Opaque, alias_ty_a) = a {
874                    debug_assert_eq!(alias_ty_a.refine_args.len(), alias_ty_b.refine_args.len());
875                    iter::zip(alias_ty_a.refine_args.iter(), alias_ty_b.refine_args.iter())
876                        .for_each(|(expr_a, expr_b)| infcx.unify_exprs(expr_a, expr_b));
877                }
878                self.handle_opaque_type(infcx, a, alias_ty_b)
879            }
880            (
881                BaseTy::Alias(AliasKind::Projection, alias_ty_a),
882                BaseTy::Alias(AliasKind::Projection, alias_ty_b),
883            ) => {
884                debug_assert_eq!(alias_ty_a, alias_ty_b);
885                Ok(())
886            }
887            (BaseTy::Array(ty_a, len_a), BaseTy::Array(ty_b, len_b)) => {
888                debug_assert_eq!(len_a, len_b);
889                self.tys(infcx, ty_a, ty_b)
890            }
891            (BaseTy::Param(param_a), BaseTy::Param(param_b)) => {
892                debug_assert_eq!(param_a, param_b);
893                Ok(())
894            }
895            (BaseTy::Bool, BaseTy::Bool)
896            | (BaseTy::Str, BaseTy::Str)
897            | (BaseTy::Char, BaseTy::Char)
898            | (BaseTy::RawPtr(_, _), BaseTy::RawPtr(_, _))
899            | (BaseTy::RawPtrMetadata(_), BaseTy::RawPtrMetadata(_)) => Ok(()),
900            (BaseTy::Dynamic(preds_a, _), BaseTy::Dynamic(preds_b, _)) => {
901                tracked_span_assert_eq!(preds_a.erase_regions(), preds_b.erase_regions());
902                Ok(())
903            }
904            (BaseTy::Closure(did1, tys_a, _), BaseTy::Closure(did2, tys_b, _)) if did1 == did2 => {
905                debug_assert_eq!(tys_a.len(), tys_b.len());
906                for (ty_a, ty_b) in iter::zip(tys_a, tys_b) {
907                    self.tys(infcx, ty_a, ty_b)?;
908                }
909                Ok(())
910            }
911            (BaseTy::FnPtr(sig_a), BaseTy::FnPtr(sig_b)) => {
912                tracked_span_assert_eq!(sig_a.erase_regions(), sig_b.erase_regions());
913                Ok(())
914            }
915            _ => Err(query_bug!("incompatible base types: `{a:?}` - `{b:?}`"))?,
916        }
917    }
918
919    fn generic_args(
920        &mut self,
921        infcx: &mut InferCtxt,
922        variance: Variance,
923        a: &GenericArg,
924        b: &GenericArg,
925    ) -> InferResult {
926        let (ty_a, ty_b) = match (a, b) {
927            (GenericArg::Ty(ty_a), GenericArg::Ty(ty_b)) => (ty_a.clone(), ty_b.clone()),
928            (GenericArg::Base(ctor_a), GenericArg::Base(ctor_b)) => {
929                debug_assert_eq!(ctor_a.sort(), ctor_b.sort());
930                (ctor_a.to_ty(), ctor_b.to_ty())
931            }
932            (GenericArg::Lifetime(_), GenericArg::Lifetime(_)) => return Ok(()),
933            (GenericArg::Const(cst_a), GenericArg::Const(cst_b)) => {
934                debug_assert_eq!(cst_a, cst_b);
935                return Ok(());
936            }
937            _ => Err(query_bug!("incompatible generic args: `{a:?}` `{b:?}`"))?,
938        };
939        match variance {
940            Variance::Covariant => self.tys(infcx, &ty_a, &ty_b),
941            Variance::Invariant => {
942                self.tys(infcx, &ty_a, &ty_b)?;
943                self.tys(infcx, &ty_b, &ty_a)
944            }
945            Variance::Contravariant => self.tys(infcx, &ty_b, &ty_a),
946            Variance::Bivariant => Ok(()),
947        }
948    }
949
950    fn idxs_eq(&mut self, infcx: &mut InferCtxt, a: &Expr, b: &Expr) {
951        if a == b {
952            return;
953        }
954        match (a.kind(), b.kind()) {
955            (
956                ExprKind::Ctor(Ctor::Struct(did_a), flds_a),
957                ExprKind::Ctor(Ctor::Struct(did_b), flds_b),
958            ) => {
959                debug_assert_eq!(did_a, did_b);
960                for (a, b) in iter::zip(flds_a, flds_b) {
961                    self.idxs_eq(infcx, a, b);
962                }
963            }
964            (ExprKind::Tuple(flds_a), ExprKind::Tuple(flds_b)) => {
965                for (a, b) in iter::zip(flds_a, flds_b) {
966                    self.idxs_eq(infcx, a, b);
967                }
968            }
969            (_, ExprKind::Tuple(flds_b)) => {
970                for (f, b) in flds_b.iter().enumerate() {
971                    let proj = FieldProj::Tuple { arity: flds_b.len(), field: f as u32 };
972                    let a = a.proj_and_reduce(proj);
973                    self.idxs_eq(infcx, &a, b);
974                }
975            }
976
977            (_, ExprKind::Ctor(Ctor::Struct(def_id), flds_b)) => {
978                for (f, b) in flds_b.iter().enumerate() {
979                    let proj = FieldProj::Adt { def_id: *def_id, field: f as u32 };
980                    let a = a.proj_and_reduce(proj);
981                    self.idxs_eq(infcx, &a, b);
982                }
983            }
984
985            (ExprKind::Tuple(flds_a), _) => {
986                infcx.unify_exprs(a, b);
987                for (f, a) in flds_a.iter().enumerate() {
988                    let proj = FieldProj::Tuple { arity: flds_a.len(), field: f as u32 };
989                    let b = b.proj_and_reduce(proj);
990                    self.idxs_eq(infcx, a, &b);
991                }
992            }
993            (ExprKind::Ctor(Ctor::Struct(def_id), flds_a), _) => {
994                infcx.unify_exprs(a, b);
995                for (f, a) in flds_a.iter().enumerate() {
996                    let proj = FieldProj::Adt { def_id: *def_id, field: f as u32 };
997                    let b = b.proj_and_reduce(proj);
998                    self.idxs_eq(infcx, a, &b);
999                }
1000            }
1001            (ExprKind::Abs(lam_a), ExprKind::Abs(lam_b)) => {
1002                self.abs_eq(infcx, lam_a, lam_b);
1003            }
1004            (_, ExprKind::Abs(lam_b)) => {
1005                self.abs_eq(infcx, &a.eta_expand_abs(lam_b.vars(), lam_b.output()), lam_b);
1006            }
1007            (ExprKind::Abs(lam_a), _) => {
1008                infcx.unify_exprs(a, b);
1009                self.abs_eq(infcx, lam_a, &b.eta_expand_abs(lam_a.vars(), lam_a.output()));
1010            }
1011            (ExprKind::KVar(_), _) | (_, ExprKind::KVar(_)) => {
1012                infcx.check_impl(a, b, self.tag());
1013                infcx.check_impl(b, a, self.tag());
1014            }
1015            _ => {
1016                infcx.unify_exprs(a, b);
1017                let span = b.span();
1018                infcx.check_pred(Expr::binary_op(rty::BinOp::Eq, a, b).at_opt(span), self.tag());
1019            }
1020        }
1021    }
1022
1023    fn abs_eq(&mut self, infcx: &mut InferCtxt, a: &Lambda, b: &Lambda) {
1024        debug_assert_eq!(a.vars().len(), b.vars().len());
1025        let vars = a
1026            .vars()
1027            .iter()
1028            .map(|kind| Expr::fvar(infcx.define_var(kind.expect_sort())))
1029            .collect_vec();
1030        let body_a = a.apply(&vars);
1031        let body_b = b.apply(&vars);
1032        self.idxs_eq(infcx, &body_a, &body_b);
1033    }
1034
1035    fn handle_opaque_type(
1036        &mut self,
1037        infcx: &mut InferCtxt,
1038        bty: &BaseTy,
1039        alias_ty: &AliasTy,
1040    ) -> InferResult {
1041        if let BaseTy::Coroutine(def_id, resume_ty, upvar_tys) = bty {
1042            let obligs = mk_coroutine_obligations(
1043                infcx.genv,
1044                def_id,
1045                resume_ty,
1046                upvar_tys,
1047                &alias_ty.def_id,
1048            )?;
1049            self.obligations.extend(obligs);
1050        } else {
1051            let bounds = infcx.genv.item_bounds(alias_ty.def_id)?.instantiate(
1052                infcx.tcx(),
1053                &alias_ty.args,
1054                &alias_ty.refine_args,
1055            );
1056            for clause in &bounds {
1057                if let rty::ClauseKind::Projection(pred) = clause.kind_skipping_binder() {
1058                    let alias_ty = pred.projection_ty.with_self_ty(bty.to_subset_ty_ctor());
1059                    let ty1 = BaseTy::Alias(AliasKind::Projection, alias_ty)
1060                        .to_ty()
1061                        .normalize_projections(&mut infcx.at(self.span))?;
1062                    let ty2 = pred.term.to_ty();
1063                    self.tys(infcx, &ty1, &ty2)?;
1064                }
1065            }
1066        }
1067        Ok(())
1068    }
1069}
1070
1071fn mk_coroutine_obligations(
1072    genv: GlobalEnv,
1073    generator_did: &DefId,
1074    resume_ty: &Ty,
1075    upvar_tys: &List<Ty>,
1076    opaque_def_id: &DefId,
1077) -> InferResult<Vec<Binder<rty::CoroutineObligPredicate>>> {
1078    let bounds = genv.item_bounds(*opaque_def_id)?.skip_binder();
1079    for bound in &bounds {
1080        if let Some(proj_clause) = bound.as_projection_clause() {
1081            return Ok(vec![proj_clause.map(|proj_clause| {
1082                let output = proj_clause.term;
1083                CoroutineObligPredicate {
1084                    def_id: *generator_did,
1085                    resume_ty: resume_ty.clone(),
1086                    upvar_tys: upvar_tys.clone(),
1087                    output: output.to_ty(),
1088                }
1089            })]);
1090        }
1091    }
1092    bug!("no projection predicate")
1093}
1094
1095#[derive(Debug)]
1096pub enum InferErr {
1097    UnsolvedEvar(EVid),
1098    OpaqueStruct(DefId),
1099    Query(QueryErr),
1100}
1101
1102impl From<QueryErr> for InferErr {
1103    fn from(v: QueryErr) -> Self {
1104        Self::Query(v)
1105    }
1106}
1107
1108mod pretty {
1109    use std::fmt;
1110
1111    use flux_middle::pretty::*;
1112
1113    use super::*;
1114
1115    impl Pretty for Tag {
1116        fn fmt(&self, cx: &PrettyCx, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117            w!(cx, f, "{:?} at {:?}", ^self.reason, self.src_span)
1118        }
1119    }
1120
1121    impl_debug_with_default_cx!(Tag);
1122}