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