flux_infer/
infer.rs

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