flux_refineck/
checker.rs

1use std::{collections::hash_map::Entry, iter, vec};
2
3use flux_common::{
4    bug, dbg, dbg::SpanTrace, index::IndexVec, iter::IterExt, span_bug, tracked_span_bug,
5    tracked_span_dbg_assert_eq,
6};
7use flux_config::{self as config, InferOpts};
8use flux_infer::{
9    infer::{
10        ConstrReason, GlobalEnvExt as _, InferCtxt, InferCtxtRoot, InferResult, SubtypeReason,
11    },
12    projections::NormalizeExt as _,
13    refine_tree::{Marker, RefineCtxtTrace},
14};
15use flux_middle::{
16    PanicSpec,
17    global_env::GlobalEnv,
18    pretty::PrettyCx,
19    queries::{QueryResult, try_query},
20    query_bug,
21    rty::{
22        self, AdtDef, BaseTy, Binder, Bool, Clause, Constant, CoroutineObligPredicate, EarlyBinder,
23        Expr, FnOutput, FnSig, FnTraitPredicate, GenericArg, GenericArgsExt as _, Int, IntTy,
24        Mutability, Path, PolyFnSig, PtrKind, RefineArgs, RefineArgsExt,
25        Region::ReErased,
26        Ty, TyKind, Uint, UintTy, VariantIdx,
27        fold::{TypeFoldable, TypeFolder, TypeSuperFoldable},
28        refining::{Refine, Refiner},
29    },
30};
31use flux_rustc_bridge::{
32    self, ToRustc,
33    mir::{
34        self, AggregateKind, AssertKind, BasicBlock, Body, BodyRoot, BorrowKind, CastKind,
35        ConstOperand, Location, NonDivergingIntrinsic, Operand, Place, Rvalue, START_BLOCK,
36        Statement, StatementKind, Terminator, TerminatorKind, UnOp,
37    },
38    ty::{self, GenericArgsExt as _},
39};
40use itertools::{Itertools, izip};
41use rustc_data_structures::{
42    graph::dominators::Dominators,
43    unord::{UnordMap, UnordSet},
44};
45use rustc_hash::FxHashMap;
46use rustc_hir::{
47    LangItem,
48    def_id::{DefId, LocalDefId},
49};
50use rustc_index::{IndexSlice, bit_set::DenseBitSet};
51use rustc_infer::infer::TyCtxtInferExt;
52use rustc_middle::{
53    mir::{Promoted, SwitchTargets},
54    ty::{TyCtxt, TypeSuperVisitable as _, TypeVisitable as _, TypingMode},
55};
56use rustc_span::{
57    Span, Symbol,
58    sym::{self},
59};
60
61use self::errors::{CheckerError, ResultExt};
62use crate::{
63    ghost_statements::{CheckerId, GhostStatement, GhostStatements, Point},
64    primops,
65    queue::WorkQueue,
66    rty::Char,
67    type_env::{BasicBlockEnv, BasicBlockEnvShape, PtrToRefBound, TypeEnv, TypeEnvTrace},
68};
69
70type Result<T = ()> = std::result::Result<T, CheckerError>;
71
72pub(crate) struct Checker<'ck, 'genv, 'tcx, M> {
73    genv: GlobalEnv<'genv, 'tcx>,
74    /// [`CheckerId`] of the function-like item being checked.
75    checker_id: CheckerId,
76    inherited: Inherited<'ck, M>,
77    body: &'ck Body<'tcx>,
78    /// The type used for the `resume` argument if we are checking a generator.
79    resume_ty: Option<Ty>,
80    fn_sig: FnSig,
81    /// A marker to the node in the refinement tree at the end of the basic block after applying
82    /// the effects of the terminator.
83    markers: IndexVec<BasicBlock, Option<Marker>>,
84    visited: DenseBitSet<BasicBlock>,
85    queue: WorkQueue<'ck>,
86    default_refiner: Refiner<'genv, 'tcx>,
87    /// The templates for the promoted bodies of the current function
88    promoted: &'ck IndexSlice<Promoted, Ty>,
89}
90
91/// Fields shared by the top-level function and its nested closure/generators
92struct Inherited<'ck, M> {
93    /// [`Expr`]s used to instantiate the early bound refinement parameters of the top-level function
94    /// signature
95    ghost_stmts: &'ck UnordMap<CheckerId, GhostStatements>,
96    mode: &'ck mut M,
97
98    /// This map has the "templates" generated for the closures constructed (in [`Checker::check_rvalue_closure`]).
99    /// The [`PolyFnSig`] can have free variables (inside the scope of kvars), so we need to be
100    /// careful and only use it in the correct scope.
101    closures: &'ck mut UnordMap<DefId, PolyFnSig>,
102}
103
104#[derive(Debug)]
105struct ResolvedCall {
106    output: Ty,
107    /// The refine arguments given to the call
108    _early_args: Vec<Expr>,
109    /// The refine arguments given to the call
110    _late_args: Vec<Expr>,
111}
112
113impl<'ck, M: Mode> Inherited<'ck, M> {
114    fn new(
115        mode: &'ck mut M,
116        ghost_stmts: &'ck UnordMap<CheckerId, GhostStatements>,
117        closures: &'ck mut UnordMap<DefId, PolyFnSig>,
118    ) -> Self {
119        Self { ghost_stmts, mode, closures }
120    }
121
122    fn reborrow(&mut self) -> Inherited<'_, M> {
123        Inherited { ghost_stmts: self.ghost_stmts, mode: self.mode, closures: self.closures }
124    }
125}
126
127pub(crate) trait Mode: Sized {
128    #[expect(dead_code)]
129    const NAME: &str;
130
131    fn enter_basic_block<'ck, 'genv, 'tcx>(
132        ck: &mut Checker<'ck, 'genv, 'tcx, Self>,
133        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
134        bb: BasicBlock,
135    ) -> TypeEnv<'ck>;
136
137    fn check_goto_join_point<'genv, 'tcx>(
138        ck: &mut Checker<'_, 'genv, 'tcx, Self>,
139        infcx: InferCtxt<'_, 'genv, 'tcx>,
140        env: TypeEnv,
141        terminator_span: Span,
142        target: BasicBlock,
143    ) -> Result<bool>;
144
145    fn clear(ck: &mut Checker<Self>, bb: BasicBlock);
146}
147
148pub(crate) struct ShapeMode {
149    bb_envs: FxHashMap<CheckerId, FxHashMap<BasicBlock, BasicBlockEnvShape>>,
150}
151
152pub(crate) struct RefineMode {
153    bb_envs: FxHashMap<CheckerId, FxHashMap<BasicBlock, BasicBlockEnv>>,
154}
155
156/// The result of running the shape phase.
157pub(crate) struct ShapeResult(FxHashMap<CheckerId, FxHashMap<BasicBlock, BasicBlockEnvShape>>);
158
159/// A `Guard` describes extra "control" information that holds at the start of a successor basic block
160#[derive(Debug)]
161enum Guard {
162    /// No extra information holds, e.g., for a plain goto.
163    None,
164    /// A predicate that can be assumed, e.g., in the branches of an if-then-else.
165    Pred(Expr),
166    /// The corresponding place was found to be of a particular variant.
167    Match(Place, VariantIdx),
168}
169
170impl<'genv, 'tcx> Checker<'_, 'genv, 'tcx, ShapeMode> {
171    pub(crate) fn run_in_shape_mode<'ck>(
172        genv: GlobalEnv<'genv, 'tcx>,
173        local_id: LocalDefId,
174        ghost_stmts: &'ck UnordMap<CheckerId, GhostStatements>,
175        closures: &'ck mut UnordMap<DefId, PolyFnSig>,
176        opts: InferOpts,
177        poly_sig: &PolyFnSig,
178    ) -> Result<ShapeResult> {
179        let def_id = local_id.to_def_id();
180        dbg::shape_mode_span!(genv.tcx(), local_id).in_scope(|| {
181            let span = genv.tcx().def_span(local_id);
182            let mut mode = ShapeMode { bb_envs: FxHashMap::default() };
183
184            let body = genv.mir(local_id).with_span(span)?;
185
186            // In shape mode we don't care about kvars
187            let mut root_ctxt = try_query(|| {
188                genv.infcx_root(&body.infcx, opts)
189                    .with_dummy_kvars()
190                    .identity_for_item(def_id)?
191                    .build()
192            })
193            .with_span(span)?;
194
195            let inherited = Inherited::new(&mut mode, ghost_stmts, closures);
196
197            let infcx = root_ctxt.infcx(def_id, &body.infcx);
198            Checker::run(infcx, local_id, inherited, poly_sig.clone())?;
199
200            Ok(ShapeResult(mode.bb_envs))
201        })
202    }
203}
204
205impl<'genv, 'tcx> Checker<'_, 'genv, 'tcx, RefineMode> {
206    pub(crate) fn run_in_refine_mode<'ck>(
207        genv: GlobalEnv<'genv, 'tcx>,
208        local_id: LocalDefId,
209        ghost_stmts: &'ck UnordMap<CheckerId, GhostStatements>,
210        closures: &'ck mut UnordMap<DefId, PolyFnSig>,
211        bb_env_shapes: ShapeResult,
212        opts: InferOpts,
213        poly_sig: &PolyFnSig,
214    ) -> Result<InferCtxtRoot<'genv, 'tcx>> {
215        let def_id = local_id.to_def_id();
216        let span = genv.tcx().def_span(def_id);
217
218        let body = genv.mir(local_id).with_span(span)?;
219        let mut root_ctxt = try_query(|| {
220            genv.infcx_root(&body.infcx, opts)
221                .identity_for_item(def_id)?
222                .build()
223        })
224        .with_span(span)?;
225        let bb_envs = bb_env_shapes.into_bb_envs(&mut root_ctxt, &body.body);
226
227        dbg::refine_mode_span!(genv.tcx(), def_id, bb_envs).in_scope(|| {
228            // Check the body of the function def_id against its signature
229            let mut mode = RefineMode { bb_envs };
230            let inherited = Inherited::new(&mut mode, ghost_stmts, closures);
231            let infcx = root_ctxt.infcx(def_id, &body.infcx);
232            Checker::run(infcx, local_id, inherited, poly_sig.clone())?;
233
234            Ok(root_ctxt)
235        })
236    }
237}
238
239/// `SubFn` lets us reuse _most_ of the same code for `check_fn_subtyping` for both the case where
240/// we have an early-bound function signature (e.g., for a trait method???) and versions without,
241/// e.g. a plain closure against its FnTraitPredicate obligation.
242#[derive(Debug)]
243pub enum SubFn {
244    Poly(DefId, EarlyBinder<rty::PolyFnSig>, rty::GenericArgs),
245    Mono(rty::PolyFnSig),
246}
247
248impl SubFn {
249    pub fn as_ref(&self) -> &rty::PolyFnSig {
250        match self {
251            SubFn::Poly(_, sig, _) => sig.skip_binder_ref(),
252            SubFn::Mono(sig) => sig,
253        }
254    }
255}
256
257/// The function `check_fn_subtyping` does a function subtyping check between
258/// the sub-type (T_f) corresponding to the type of `def_id` @ `args` and the
259/// super-type (T_g) corresponding to the `oblig_sig`. This subtyping is handled
260/// as akin to the code
261///
262///   T_f := (S1,...,Sn) -> S
263///   T_g := (T1,...,Tn) -> T
264///   T_f <: T_g
265///
266///  fn g(x1:T1,...,xn:Tn) -> T {
267///      f(x1,...,xn)
268///  }
269fn check_fn_subtyping(
270    infcx: &mut InferCtxt,
271    sub_sig: SubFn,
272    super_sig: &rty::PolyFnSig,
273    span: Span,
274) -> InferResult {
275    let mut infcx = infcx.branch();
276    let mut infcx = infcx.at(span);
277    let tcx = infcx.genv.tcx();
278
279    let super_sig = super_sig
280        .replace_bound_vars(
281            |_| rty::ReErased,
282            |sort, _, kind| Expr::fvar(infcx.define_bound_reft_var(sort, kind)),
283        )
284        .deeply_normalize(&mut infcx)?;
285
286    // 1. Unpack `T_g` input types
287    let actuals = super_sig
288        .inputs()
289        .iter()
290        .map(|ty| infcx.unpack(ty))
291        .collect_vec();
292
293    let mut env = TypeEnv::empty();
294    let actuals = unfold_local_ptrs(&mut infcx, &mut env, sub_sig.as_ref(), &actuals)?;
295    let actuals = infer_under_mut_ref_hack(&mut infcx, &actuals[..], sub_sig.as_ref());
296
297    let output = infcx.ensure_resolved_evars(|infcx| {
298        // 2. Fresh names for `T_f` refine-params / Instantiate fn_def_sig and normalize it
299        // in subtyping_mono, skip next two steps...
300        let sub_sig = match sub_sig {
301            SubFn::Poly(def_id, early_sig, sub_args) => {
302                let refine_args = infcx.instantiate_refine_args(def_id, &sub_args)?;
303                early_sig.instantiate(tcx, &sub_args, &refine_args)
304            }
305            SubFn::Mono(sig) => sig,
306        };
307        // ... jump right here.
308        let sub_sig = sub_sig
309            .replace_bound_vars(
310                |_| rty::ReErased,
311                |sort, mode, _| infcx.fresh_infer_var(sort, mode),
312            )
313            .deeply_normalize(infcx)?;
314
315        // 3. INPUT subtyping (g-input <: f-input)
316        for requires in super_sig.requires() {
317            infcx.assume_pred(requires);
318        }
319        infcx.check_pred(
320            Expr::implies(super_sig.no_panic(), sub_sig.no_panic()),
321            ConstrReason::Subtype(SubtypeReason::Input),
322        );
323        for (actual, formal) in iter::zip(actuals, sub_sig.inputs()) {
324            let reason = ConstrReason::Subtype(SubtypeReason::Input);
325            infcx.subtyping_with_env(&mut env, &actual, formal, reason)?;
326        }
327        // we check the requires AFTER the actual-formal subtyping as the above may unfold stuff in
328        // the actuals
329        for requires in sub_sig.requires() {
330            let reason = ConstrReason::Subtype(SubtypeReason::Requires);
331            infcx.check_pred(requires, reason);
332        }
333
334        Ok(sub_sig.output())
335    })?;
336
337    let output = infcx
338        .fully_resolve_evars(&output)
339        .replace_bound_refts_with(|sort, _, kind| {
340            Expr::fvar(infcx.define_bound_reft_var(sort, kind))
341        });
342
343    // 4. OUTPUT subtyping (f_out <: g_out)
344    infcx.ensure_resolved_evars(|infcx| {
345        let super_output = super_sig
346            .output()
347            .replace_bound_refts_with(|sort, mode, _| infcx.fresh_infer_var(sort, mode));
348        let reason = ConstrReason::Subtype(SubtypeReason::Output);
349        infcx.subtyping(&output.ret, &super_output.ret, reason)?;
350
351        // 6. Update state with Output "ensures" and check super ensures
352        env.assume_ensures(infcx, &output.ensures, span);
353        fold_local_ptrs(infcx, &mut env, span)?;
354        env.check_ensures(
355            infcx,
356            &super_output.ensures,
357            ConstrReason::Subtype(SubtypeReason::Ensures),
358        )
359    })
360}
361
362/// Trait subtyping check, which makes sure that the type for an impl method (def_id)
363/// is a subtype of the corresponding trait method.
364pub(crate) fn trait_impl_subtyping<'genv, 'tcx>(
365    genv: GlobalEnv<'genv, 'tcx>,
366    def_id: LocalDefId,
367    opts: InferOpts,
368    span: Span,
369) -> InferResult<Option<InferCtxtRoot<'genv, 'tcx>>> {
370    let tcx = genv.tcx();
371
372    // Skip the check if this is not an impl method
373    let Some((impl_trait_ref, trait_method_id)) = find_trait_item(genv, def_id)? else {
374        return Ok(None);
375    };
376    let impl_method_id = def_id.to_def_id();
377    // Skip the check if either the trait-method or the impl-method are marked as `trusted_impl`
378    if genv.has_trusted_impl(trait_method_id) || genv.has_trusted_impl(impl_method_id) {
379        return Ok(None);
380    }
381
382    let impl_id = tcx.impl_of_assoc(impl_method_id).unwrap();
383    let impl_method_args = GenericArg::identity_for_item(genv, impl_method_id)?;
384    let trait_method_args = impl_method_args.rebase_onto(&tcx, impl_id, &impl_trait_ref.args);
385    let trait_refine_args = RefineArgs::identity_for_item(genv, trait_method_id)?;
386
387    let rustc_infcx = genv
388        .tcx()
389        .infer_ctxt()
390        .with_next_trait_solver(true)
391        .build(TypingMode::non_body_analysis());
392
393    let mut root_ctxt = genv
394        .infcx_root(&rustc_infcx, opts)
395        .with_const_generics(impl_id)?
396        .with_refinement_generics(trait_method_id, &trait_method_args)?
397        .build()?;
398
399    let mut infcx = root_ctxt.infcx(impl_method_id, &rustc_infcx);
400
401    let trait_fn_sig =
402        genv.fn_sig(trait_method_id)?
403            .instantiate(tcx, &trait_method_args, &trait_refine_args);
404    let impl_sig = genv.fn_sig(impl_method_id)?;
405    let sub_sig = SubFn::Poly(impl_method_id, impl_sig, impl_method_args);
406
407    check_fn_subtyping(&mut infcx, sub_sig, &trait_fn_sig, span)?;
408    Ok(Some(root_ctxt))
409}
410
411fn find_trait_item(
412    genv: GlobalEnv<'_, '_>,
413    def_id: LocalDefId,
414) -> QueryResult<Option<(rty::TraitRef, DefId)>> {
415    let tcx = genv.tcx();
416    let def_id = def_id.to_def_id();
417    if let Some(impl_id) = tcx.trait_impl_of_assoc(def_id) {
418        let impl_trait_ref = genv.impl_trait_ref(impl_id)?.instantiate_identity();
419        let trait_item_id = tcx.associated_item(def_id).trait_item_def_id().unwrap();
420        return Ok(Some((impl_trait_ref, trait_item_id)));
421    }
422    Ok(None)
423}
424
425/// Temporarily (around a function call) convert an `&mut` to an `&strg` to allow for the call to be
426/// checked. This is done by unfolding the `&mut` into a local pointer at the call-site and then
427/// folding the pointer back into the `&mut` upon return.
428/// See also [`fold_local_ptrs`].
429///
430/// ```text
431///             unpack(T) = T'
432/// ---------------------------------------[local-unfold]
433/// Γ ; &mut T => Γ, l:[<: T] T' ; ptr(l)
434/// ```
435fn unfold_local_ptrs(
436    infcx: &mut InferCtxt,
437    env: &mut TypeEnv,
438    fn_sig: &PolyFnSig,
439    actuals: &[Ty],
440) -> InferResult<Vec<Ty>> {
441    // We *only* need to know whether each input is a &strg or not
442    let fn_sig = fn_sig.skip_binder_ref();
443    let mut tys = vec![];
444    for (actual, input) in izip!(actuals, fn_sig.inputs()) {
445        let actual = if let (
446            TyKind::Indexed(BaseTy::Ref(re, bound, Mutability::Mut), _),
447            TyKind::StrgRef(_, _, _),
448        ) = (actual.kind(), input.kind())
449        {
450            let loc = env.unfold_local_ptr(infcx, bound)?;
451            let path1 = Path::new(loc, rty::List::empty());
452            Ty::ptr(PtrKind::Mut(*re), path1)
453        } else {
454            actual.clone()
455        };
456        tys.push(actual);
457    }
458    Ok(tys)
459}
460
461/// Fold local pointers implements roughly a rule like the following (for all local pointers)
462/// that converts the local pointers created via [`unfold_local_ptrs`] back into `&mut`.
463///
464/// ```text
465///       T1 <: T2
466/// --------------------- [local-fold]
467/// Γ, l:[<: T2] T1 => Γ
468/// ```
469fn fold_local_ptrs(infcx: &mut InferCtxt, env: &mut TypeEnv, span: Span) -> InferResult {
470    let mut at = infcx.at(span);
471    env.fold_local_ptrs(&mut at)
472}
473
474fn promoted_fn_sig(ty: &Ty) -> PolyFnSig {
475    let safety = rustc_hir::Safety::Safe;
476    let abi = rustc_abi::ExternAbi::Rust;
477    let requires = rty::List::empty();
478    let inputs = rty::List::empty();
479    let output =
480        Binder::bind_with_vars(FnOutput::new(ty.clone(), rty::List::empty()), rty::List::empty());
481    let fn_sig = crate::rty::FnSig::new(safety, abi, requires, inputs, output, Expr::tt(), false);
482    PolyFnSig::bind_with_vars(fn_sig, crate::rty::List::empty())
483}
484
485impl<'ck, 'genv, 'tcx, M: Mode> Checker<'ck, 'genv, 'tcx, M> {
486    fn new(
487        genv: GlobalEnv<'genv, 'tcx>,
488        checker_id: CheckerId,
489        inherited: Inherited<'ck, M>,
490        body: &'ck Body<'tcx>,
491        fn_sig: FnSig,
492        promoted: &'ck IndexSlice<Promoted, Ty>,
493    ) -> QueryResult<Self> {
494        let root_id = checker_id.root_id();
495
496        let resume_ty = if let CheckerId::DefId(def_id) = checker_id
497            && genv.tcx().is_coroutine(def_id.to_def_id())
498        {
499            Some(fn_sig.inputs()[1].clone())
500        } else {
501            None
502        };
503
504        let bb_len = body.basic_blocks.len();
505        Ok(Self {
506            checker_id,
507            genv,
508            inherited,
509            body,
510            resume_ty,
511            visited: DenseBitSet::new_empty(bb_len),
512            fn_sig,
513            markers: IndexVec::from_fn_n(|_| None, bb_len),
514            queue: WorkQueue::empty(bb_len, &body.dominator_order_rank),
515            default_refiner: Refiner::default_for_item(genv, root_id.to_def_id())?,
516            promoted,
517        })
518    }
519
520    fn check_body(
521        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
522        checker_id: CheckerId,
523        inherited: Inherited<'ck, M>,
524        body: &'ck Body<'tcx>,
525        poly_sig: PolyFnSig,
526        promoted: &'ck IndexSlice<Promoted, Ty>,
527    ) -> Result {
528        let span = body.span();
529
530        let fn_sig = poly_sig
531            .replace_bound_vars(
532                |_| rty::ReErased,
533                |sort, _, kind| {
534                    let name = infcx.define_bound_reft_var(sort, kind);
535                    Expr::fvar(name)
536                },
537            )
538            .deeply_normalize(&mut infcx.at(span))
539            .with_span(span)?;
540        let mut env = TypeEnv::new(infcx, body, &fn_sig);
541
542        let mut ck = Checker::new(infcx.genv, checker_id, inherited, body, fn_sig, promoted)
543            .with_span(span)?;
544        ck.check_ghost_statements_at(infcx, &mut env, Point::FunEntry, span)?;
545
546        ck.check_goto(infcx.branch(), env, body.span(), START_BLOCK)?;
547
548        while let Some(bb) = ck.queue.pop() {
549            let visited = ck.visited.contains(bb);
550
551            if visited {
552                M::clear(&mut ck, bb);
553            }
554
555            let marker = ck.marker_at_dominator(bb);
556            let mut infcx = infcx.move_to(marker, visited);
557            let mut env = M::enter_basic_block(&mut ck, &mut infcx, bb);
558            env.unpack(&mut infcx);
559            ck.check_basic_block(infcx, env, bb)?;
560        }
561        Ok(())
562    }
563
564    /// Assign a template with fresh kvars to each promoted constant in `body_root`.
565    fn promoted_tys(
566        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
567        def_id: LocalDefId,
568        body_root: &BodyRoot<'tcx>,
569    ) -> QueryResult<IndexVec<Promoted, Ty>> {
570        let hole_refiner = Refiner::with_holes(infcx.genv, def_id.into())?;
571
572        body_root
573            .promoted
574            .iter()
575            .map(|body| {
576                Ok(body
577                    .return_ty()
578                    .refine(&hole_refiner)?
579                    .replace_holes(|binders, kind| infcx.fresh_infer_var_for_hole(binders, kind)))
580            })
581            .collect()
582    }
583
584    fn run(
585        mut infcx: InferCtxt<'_, 'genv, 'tcx>,
586        def_id: LocalDefId,
587        mut inherited: Inherited<'_, M>,
588        poly_sig: PolyFnSig,
589    ) -> Result {
590        let genv = infcx.genv;
591        let span = genv.tcx().def_span(def_id);
592        let body_root = genv.mir(def_id).with_span(span)?;
593
594        // 1. Generate templates for promoted consts
595        let promoted_tys = Self::promoted_tys(&mut infcx, def_id, &body_root).with_span(span)?;
596
597        // 2. Check the body of all promoted
598        for (promoted, ty) in promoted_tys.iter_enumerated() {
599            let body = &body_root.promoted[promoted];
600            let poly_sig = promoted_fn_sig(ty);
601            Checker::check_body(
602                &mut infcx,
603                CheckerId::Promoted(def_id, promoted),
604                inherited.reborrow(),
605                body,
606                poly_sig,
607                &promoted_tys,
608            )?;
609        }
610
611        // 3. Check the main body
612        Checker::check_body(
613            &mut infcx,
614            CheckerId::DefId(def_id),
615            inherited,
616            &body_root.body,
617            poly_sig,
618            &promoted_tys,
619        )
620    }
621
622    fn check_basic_block(
623        &mut self,
624        mut infcx: InferCtxt<'_, 'genv, 'tcx>,
625        mut env: TypeEnv,
626        bb: BasicBlock,
627    ) -> Result {
628        dbg::basic_block_start!(bb, infcx, env);
629
630        self.visited.insert(bb);
631        let data = &self.body.basic_blocks[bb];
632        let mut last_stmt_span = None;
633        let mut location = Location { block: bb, statement_index: 0 };
634        for stmt in &data.statements {
635            let span = stmt.source_info.span;
636            self.check_ghost_statements_at(
637                &mut infcx,
638                &mut env,
639                Point::BeforeLocation(location),
640                span,
641            )?;
642            bug::track_span(span, || {
643                dbg::statement!("start", stmt, &infcx, &env, span, &self);
644                self.check_statement(&mut infcx, &mut env, stmt)?;
645                dbg::statement!("end", stmt, &infcx, &env, span, &self);
646                Ok(())
647            })?;
648            if !stmt.is_nop() {
649                last_stmt_span = Some(span);
650            }
651            location = location.successor_within_block();
652        }
653
654        if let Some(terminator) = &data.terminator {
655            let span = terminator.source_info.span;
656            self.check_ghost_statements_at(
657                &mut infcx,
658                &mut env,
659                Point::BeforeLocation(location),
660                span,
661            )?;
662
663            bug::track_span(span, || {
664                dbg::terminator!("start", terminator, infcx, env);
665
666                let successors =
667                    self.check_terminator(&mut infcx, &mut env, terminator, last_stmt_span)?;
668                dbg::terminator!("end", terminator, infcx, env);
669
670                self.markers[bb] = Some(infcx.marker());
671                let term_span = last_stmt_span.unwrap_or(span);
672                self.check_successors(infcx, env, bb, term_span, successors)
673            })?;
674        }
675        Ok(())
676    }
677
678    fn check_assign_ty(
679        &mut self,
680        infcx: &mut InferCtxt,
681        env: &mut TypeEnv,
682        place: &Place,
683        ty: Ty,
684        span: Span,
685    ) -> InferResult {
686        let ty = infcx.hoister(true).hoist(&ty);
687        env.assign(&mut infcx.at(span), place, ty)
688    }
689
690    fn check_statement(
691        &mut self,
692        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
693        env: &mut TypeEnv,
694        stmt: &Statement<'tcx>,
695    ) -> Result {
696        let stmt_span = stmt.source_info.span;
697        match &stmt.kind {
698            StatementKind::Assign(place, rvalue) => {
699                let ty = self.check_rvalue(infcx, env, stmt_span, rvalue)?;
700                self.check_assign_ty(infcx, env, place, ty, stmt_span)
701                    .with_span(stmt_span)?;
702            }
703            StatementKind::SetDiscriminant { .. } => {
704                // TODO(nilehmann) double check here that the place is unfolded to
705                // the correct variant. This should be guaranteed by rustc
706            }
707            StatementKind::FakeRead(_) => {
708                // TODO(nilehmann) fake reads should be folding points
709            }
710            StatementKind::AscribeUserType(_, _) => {
711                // User ascriptions affect nll, but no refinement type checking.
712                // Maybe we can use this to associate refinement type to locals.
713            }
714            StatementKind::PlaceMention(_) => {
715                // Place mentions are a no-op used to detect uses of unsafe that would
716                // otherwise be optimized away.
717            }
718            StatementKind::Nop => {}
719            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => {
720                // Currently, we only have the `assume` intrinsic, which if we're to trust rustc should be a NOP.
721                // TODO: There may be a use-case to actually "assume" the bool index associated with the operand,
722                // i.e. to strengthen the `rcx` / `env` with the assumption that the bool-index is in fact `true`...
723                let _ = self
724                    .check_operand(infcx, env, stmt_span, op)
725                    .with_span(stmt_span)?;
726            }
727        }
728        Ok(())
729    }
730
731    fn is_exit_block(&self, bb: BasicBlock) -> bool {
732        let data = &self.body.basic_blocks[bb];
733        let is_no_op = data.statements.iter().all(Statement::is_nop);
734        let is_ret = match &data.terminator {
735            None => false,
736            Some(term) => term.is_return(),
737        };
738        is_no_op && is_ret
739    }
740
741    /// For `check_terminator`, the output `Vec<BasicBlock, Guard>` denotes,
742    /// - `BasicBlock` "successors" of the current terminator, and
743    /// - `Guard` are extra control information from, e.g. the `SwitchInt` (or `Assert`) you can assume when checking the corresponding successor.
744    fn check_terminator(
745        &mut self,
746        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
747        env: &mut TypeEnv,
748        terminator: &Terminator<'tcx>,
749        last_stmt_span: Option<Span>,
750    ) -> Result<Vec<(BasicBlock, Guard)>> {
751        let source_info = terminator.source_info;
752        let terminator_span = source_info.span;
753        match &terminator.kind {
754            TerminatorKind::Return => {
755                self.check_ret(infcx, env, last_stmt_span.unwrap_or(terminator_span))?;
756                Ok(vec![])
757            }
758            TerminatorKind::Unreachable => Ok(vec![]),
759            TerminatorKind::CoroutineDrop => Ok(vec![]),
760            TerminatorKind::Goto { target } => Ok(vec![(*target, Guard::None)]),
761            TerminatorKind::Yield { resume, resume_arg, .. } => {
762                if let Some(resume_ty) = self.resume_ty.clone() {
763                    self.check_assign_ty(infcx, env, resume_arg, resume_ty, terminator_span)
764                        .with_span(terminator_span)?;
765                } else {
766                    bug!("yield in non-generator function");
767                }
768                Ok(vec![(*resume, Guard::None)])
769            }
770            TerminatorKind::SwitchInt { discr, targets } => {
771                let discr_ty = self
772                    .check_operand(infcx, env, terminator_span, discr)
773                    .with_span(terminator_span)?;
774                if discr_ty.is_integral() || discr_ty.is_bool() || discr_ty.is_char() {
775                    Ok(Self::check_if(&discr_ty, targets))
776                } else {
777                    Ok(self.check_match(infcx, env, &discr_ty, targets, terminator_span))
778                }
779            }
780            TerminatorKind::Call { kind, args, destination, target, .. } => {
781                let actuals = self
782                    .check_operands(infcx, env, terminator_span, args)
783                    .with_span(terminator_span)?;
784                let ret = match kind {
785                    mir::CallKind::FnDef { resolved_id, resolved_args, .. } => {
786                        let fn_sig = self.genv.fn_sig(*resolved_id).with_span(terminator_span)?;
787                        let generic_args = instantiate_args_for_fun_call(
788                            self.genv,
789                            self.checker_id.root_id().to_def_id(),
790                            *resolved_id,
791                            &resolved_args.lowered,
792                        )
793                        .with_span(terminator_span)?;
794                        self.check_call(
795                            infcx,
796                            env,
797                            terminator_span,
798                            Some(*resolved_id),
799                            fn_sig,
800                            &generic_args,
801                            &actuals,
802                        )?
803                        .output
804                    }
805                    mir::CallKind::FnPtr { operand, .. } => {
806                        let ty = self
807                            .check_operand(infcx, env, terminator_span, operand)
808                            .with_span(terminator_span)?;
809                        if let TyKind::Indexed(BaseTy::FnPtr(fn_sig), _) = infcx.unpack(&ty).kind()
810                        {
811                            self.check_call(
812                                infcx,
813                                env,
814                                terminator_span,
815                                None,
816                                EarlyBinder(fn_sig.clone()),
817                                &[],
818                                &actuals,
819                            )?
820                            .output
821                        } else {
822                            bug!("TODO: fnptr call {ty:?}")
823                        }
824                    }
825                };
826
827                let name = destination.name(&self.body.local_names);
828                let ret = infcx.unpack_at_name(name, &ret);
829                infcx.assume_invariants(&ret);
830
831                env.assign(&mut infcx.at(terminator_span), destination, ret)
832                    .with_span(terminator_span)?;
833
834                if let Some(target) = target {
835                    Ok(vec![(*target, Guard::None)])
836                } else {
837                    Ok(vec![])
838                }
839            }
840            TerminatorKind::Assert { cond, expected, target, msg } => {
841                Ok(vec![(
842                    *target,
843                    self.check_assert(infcx, env, terminator_span, cond, *expected, msg)
844                        .with_span(terminator_span)?,
845                )])
846            }
847            TerminatorKind::Drop { place, target, .. } => {
848                let _ = env.move_place(&mut infcx.at(terminator_span), place);
849                Ok(vec![(*target, Guard::None)])
850            }
851            TerminatorKind::FalseEdge { real_target, .. } => Ok(vec![(*real_target, Guard::None)]),
852            TerminatorKind::FalseUnwind { real_target, .. } => {
853                Ok(vec![(*real_target, Guard::None)])
854            }
855            TerminatorKind::UnwindResume => bug!("TODO: implement checking of cleanup code"),
856        }
857    }
858
859    fn check_ret(
860        &mut self,
861        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
862        env: &mut TypeEnv,
863        span: Span,
864    ) -> Result {
865        let obligations = infcx
866            .at(span)
867            .ensure_resolved_evars(|infcx| {
868                let ret_place_ty = env.lookup_place(infcx, Place::RETURN)?;
869                let output = self
870                    .fn_sig
871                    .output
872                    .replace_bound_refts_with(|sort, mode, _| infcx.fresh_infer_var(sort, mode));
873                let obligations =
874                    infcx.subtyping_with_env(env, &ret_place_ty, &output.ret, ConstrReason::Ret)?;
875
876                env.check_ensures(infcx, &output.ensures, ConstrReason::Ret)?;
877
878                Ok(obligations)
879            })
880            .with_span(span)?;
881
882        self.check_coroutine_obligations(infcx, obligations)
883    }
884
885    #[expect(clippy::too_many_arguments)]
886    fn check_call(
887        &mut self,
888        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
889        env: &mut TypeEnv,
890        span: Span,
891        callee_def_id: Option<DefId>,
892        fn_sig: EarlyBinder<PolyFnSig>,
893        generic_args: &[GenericArg],
894        actuals: &[Ty],
895    ) -> Result<ResolvedCall> {
896        let genv = self.genv;
897        let tcx = genv.tcx();
898
899        let actuals =
900            unfold_local_ptrs(infcx, env, fn_sig.skip_binder_ref(), actuals).with_span(span)?;
901        let actuals = infer_under_mut_ref_hack(infcx, &actuals, fn_sig.skip_binder_ref());
902        infcx.push_evar_scope();
903
904        // Replace holes in generic arguments with fresh inference variables
905        let generic_args = infcx.instantiate_generic_args(generic_args);
906
907        // Generate fresh inference variables for refinement arguments
908        let early_refine_args = match callee_def_id {
909            Some(callee_def_id) => {
910                infcx
911                    .instantiate_refine_args(callee_def_id, &generic_args)
912                    .with_span(span)?
913            }
914            None => rty::List::empty(),
915        };
916
917        let clauses = match callee_def_id {
918            Some(callee_def_id) => {
919                genv.predicates_of(callee_def_id)
920                    .with_span(span)?
921                    .predicates()
922                    .instantiate(tcx, &generic_args, &early_refine_args)
923            }
924            None => crate::rty::List::empty(),
925        };
926
927        let (clauses, fn_clauses) = Clause::split_off_fn_trait_clauses(self.genv, &clauses);
928        infcx
929            .at(span)
930            .check_non_closure_clauses(&clauses, ConstrReason::Call)
931            .with_span(span)?;
932
933        for fn_trait_pred in &fn_clauses {
934            self.check_fn_trait_clause(infcx, fn_trait_pred, span)?;
935        }
936
937        // Instantiate function signature and normalize it
938        let late_refine_args = vec![];
939        let fn_sig = fn_sig
940            .instantiate(tcx, &generic_args, &early_refine_args)
941            .replace_bound_vars(
942                |_| rty::ReErased,
943                |sort, mode, _| infcx.fresh_infer_var(sort, mode),
944            );
945
946        let fn_sig = fn_sig
947            .deeply_normalize(&mut infcx.at(span))
948            .with_span(span)?;
949
950        let mut at = infcx.at(span);
951
952        if let Some(callee_def_id) = callee_def_id
953            && genv.def_kind(callee_def_id).is_fn_like()
954        {
955            let callee_no_panic = fn_sig.no_panic();
956            let callee_inferred_spec = genv.inferred_no_panic(callee_def_id);
957
958            // The call-graph and fixpoint iteration are over `Instance`s, but the output map only
959            // retains non-mono (identity) instances (that we can identify with a `DefId`). A concrete
960            // callee (e.g., `Vec::<i32>::push`) is a mono instance whose spec is not directly queryable
961            // via inferred_no_panic. However, if the caller is `WillNotPanic`, the fixpoint already
962            // accounted for all its concrete callees: any `MightPanic` callee would have propagated up
963            // and marked the caller `MightPanic(Transitive)`. So the caller's `WillNotPanic` proves all
964            // its concrete callees are no-panic, even those whose mono spec is absent from the output
965            // map. We could potentially key specs by `Instance`, but we also need to be able to recover
966            // the resolution to a mono-instance here.
967            let inferred_panic_expr = if let CheckerId::DefId(caller_id) = self.checker_id
968                && genv.inferred_no_panic(caller_id) == PanicSpec::WillNotPanic
969            {
970                Expr::tt()
971            } else if callee_inferred_spec == PanicSpec::WillNotPanic {
972                Expr::tt()
973            } else {
974                Expr::ff()
975            };
976
977            at.check_pred(
978                Expr::implies(
979                    self.fn_sig.no_panic(),
980                    Expr::or(callee_no_panic, inferred_panic_expr),
981                ),
982                ConstrReason::NoPanic(callee_def_id, callee_inferred_spec),
983            );
984        }
985
986        // Check requires predicates
987        for requires in fn_sig.requires() {
988            at.check_pred(requires, ConstrReason::Call);
989        }
990
991        // Check arguments
992        for (actual, formal) in iter::zip(actuals, fn_sig.inputs()) {
993            at.subtyping_with_env(env, &actual, formal, ConstrReason::Call)
994                .with_span(span)?;
995        }
996
997        infcx.pop_evar_scope().with_span(span)?;
998        env.fully_resolve_evars(infcx);
999
1000        let output = infcx
1001            .fully_resolve_evars(&fn_sig.output)
1002            .replace_bound_refts_with(|sort, _, kind| {
1003                Expr::fvar(infcx.define_bound_reft_var(sort, kind))
1004            });
1005
1006        env.assume_ensures(infcx, &output.ensures, span);
1007        fold_local_ptrs(infcx, env, span).with_span(span)?;
1008
1009        Ok(ResolvedCall {
1010            output: output.ret,
1011            _early_args: early_refine_args
1012                .into_iter()
1013                .map(|arg| infcx.fully_resolve_evars(arg))
1014                .collect(),
1015            _late_args: late_refine_args
1016                .into_iter()
1017                .map(|arg| infcx.fully_resolve_evars(&arg))
1018                .collect(),
1019        })
1020    }
1021
1022    fn check_coroutine_obligations(
1023        &mut self,
1024        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1025        obligs: Vec<Binder<CoroutineObligPredicate>>,
1026    ) -> Result {
1027        for oblig in obligs {
1028            // FIXME(nilehmann) we shouldn't be skipping this binder
1029            let oblig = oblig.skip_binder();
1030
1031            #[expect(clippy::disallowed_methods, reason = "coroutines cannot be extern speced")]
1032            let def_id = oblig.def_id.expect_local();
1033            let span = self.genv.tcx().def_span(def_id);
1034            let body = self.genv.mir(def_id).with_span(span)?;
1035            Checker::run(
1036                infcx.change_item(def_id, &body.infcx),
1037                def_id,
1038                self.inherited.reborrow(),
1039                oblig.to_poly_fn_sig(),
1040            )?;
1041        }
1042        Ok(())
1043    }
1044
1045    fn find_self_ty_fn_sig(
1046        &self,
1047        self_ty: rustc_middle::ty::Ty<'tcx>,
1048        span: Span,
1049    ) -> Result<PolyFnSig> {
1050        let tcx = self.genv.tcx();
1051        let mut def_id = Some(self.checker_id.root_id().to_def_id());
1052        while let Some(did) = def_id {
1053            let generic_predicates = self
1054                .genv
1055                .predicates_of(did)
1056                .with_span(span)?
1057                .instantiate_identity();
1058            let predicates = generic_predicates.predicates;
1059
1060            for poly_fn_trait_pred in Clause::split_off_fn_trait_clauses(self.genv, &predicates).1 {
1061                if poly_fn_trait_pred.skip_binder_ref().self_ty.to_rustc(tcx) == self_ty {
1062                    return Ok(poly_fn_trait_pred.map(|fn_trait_pred| fn_trait_pred.fndef_sig()));
1063                }
1064            }
1065            // Continue to the parent if we didn't find a match
1066            def_id = generic_predicates.parent;
1067        }
1068
1069        span_bug!(
1070            span,
1071            "cannot find self_ty_fn_sig for {:?} with self_ty = {self_ty:?}",
1072            self.checker_id
1073        );
1074    }
1075
1076    fn check_fn_trait_clause(
1077        &mut self,
1078        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1079        poly_fn_trait_pred: &Binder<FnTraitPredicate>,
1080        span: Span,
1081    ) -> Result {
1082        let self_ty = poly_fn_trait_pred
1083            .skip_binder_ref()
1084            .self_ty
1085            .as_bty_skipping_existentials();
1086        let oblig_sig = poly_fn_trait_pred.map_ref(|fn_trait_pred| fn_trait_pred.fndef_sig());
1087        match self_ty {
1088            Some(BaseTy::Closure(def_id, _, _, _)) => {
1089                let Some(poly_sig) = self.inherited.closures.get(def_id).cloned() else {
1090                    span_bug!(span, "missing template for closure {def_id:?}");
1091                };
1092                check_fn_subtyping(infcx, SubFn::Mono(poly_sig.clone()), &oblig_sig, span)
1093                    .with_span(span)?;
1094            }
1095            Some(BaseTy::FnDef(def_id, args)) => {
1096                // Generates "function subtyping" obligations between the (super-type) `oblig_sig` in the `fn_trait_pred`
1097                // and the (sub-type) corresponding to the signature of `def_id + args`.
1098                // See `tests/neg/surface/fndef00.rs`
1099                let sub_sig = self.genv.fn_sig(def_id).with_span(span)?;
1100                check_fn_subtyping(
1101                    infcx,
1102                    SubFn::Poly(*def_id, sub_sig, args.clone()),
1103                    &oblig_sig,
1104                    span,
1105                )
1106                .with_span(span)?;
1107            }
1108            Some(BaseTy::FnPtr(sub_sig)) => {
1109                check_fn_subtyping(infcx, SubFn::Mono(sub_sig.clone()), &oblig_sig, span)
1110                    .with_span(span)?;
1111            }
1112
1113            // Some(self_ty) => {
1114            Some(self_ty @ BaseTy::Param(_)) => {
1115                // Step 1. Find matching clause and turn it into a FnSig
1116                let tcx = self.genv.tcx();
1117                let self_ty = self_ty.to_rustc(tcx);
1118                let sub_sig = self.find_self_ty_fn_sig(self_ty, span)?;
1119                // Step 2. Issue the subtyping
1120                check_fn_subtyping(infcx, SubFn::Mono(sub_sig), &oblig_sig, span)
1121                    .with_span(span)?;
1122            }
1123            _ => {}
1124        }
1125        Ok(())
1126    }
1127
1128    fn check_assert(
1129        &mut self,
1130        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1131        env: &mut TypeEnv,
1132        terminator_span: Span,
1133        cond: &Operand<'tcx>,
1134        expected: bool,
1135        msg: &AssertKind,
1136    ) -> InferResult<Guard> {
1137        let ty = self.check_operand(infcx, env, terminator_span, cond)?;
1138        let TyKind::Indexed(BaseTy::Bool, idx) = ty.kind() else {
1139            tracked_span_bug!("unexpected ty `{ty:?}`");
1140        };
1141        let pred = if expected { idx.clone() } else { idx.not() };
1142
1143        let msg = match msg {
1144            AssertKind::DivisionByZero => "possible division by zero",
1145            AssertKind::BoundsCheck => "possible out-of-bounds access",
1146            AssertKind::RemainderByZero => "possible remainder with a divisor of zero",
1147            AssertKind::Overflow(mir::BinOp::Div) => "possible division with overflow",
1148            AssertKind::Overflow(mir::BinOp::Rem) => "possible reminder with overflow",
1149            AssertKind::Overflow(_) => return Ok(Guard::Pred(pred)),
1150        };
1151        infcx
1152            .at(terminator_span)
1153            .check_pred(&pred, ConstrReason::Assert(msg));
1154        Ok(Guard::Pred(pred))
1155    }
1156
1157    /// Checks conditional branching as in a `match` statement. [`SwitchTargets`](https://doc.rust-lang.org/nightly/nightly-rustc/stable_mir/mir/struct.SwitchTargets.html) contains a list of branches - the exact bit value which is being compared and the block to jump to. Using the conditionals, each branch can be checked using the new control flow information.
1158    /// See <https://github.com/flux-rs/flux/pull/840#discussion_r1786543174>
1159    fn check_if(discr_ty: &Ty, targets: &SwitchTargets) -> Vec<(BasicBlock, Guard)> {
1160        let mk = |bits| {
1161            match discr_ty.kind() {
1162                TyKind::Indexed(BaseTy::Bool, idx) => {
1163                    if bits == 0 {
1164                        idx.not()
1165                    } else {
1166                        idx.clone()
1167                    }
1168                }
1169                TyKind::Indexed(bty @ (BaseTy::Int(_) | BaseTy::Uint(_) | BaseTy::Char), idx) => {
1170                    Expr::eq(idx.clone(), Expr::from_bits(bty, bits))
1171                }
1172                _ => tracked_span_bug!("unexpected discr_ty {:?}", discr_ty),
1173            }
1174        };
1175
1176        let mut successors = vec![];
1177
1178        for (bits, bb) in targets.iter() {
1179            successors.push((bb, Guard::Pred(mk(bits))));
1180        }
1181        let otherwise = Expr::and_from_iter(targets.iter().map(|(bits, _)| mk(bits).not()));
1182        successors.push((targets.otherwise(), Guard::Pred(otherwise)));
1183
1184        successors
1185    }
1186
1187    fn check_match(
1188        &mut self,
1189        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1190        env: &mut TypeEnv,
1191        discr_ty: &Ty,
1192        targets: &SwitchTargets,
1193        span: Span,
1194    ) -> Vec<(BasicBlock, Guard)> {
1195        let (adt_def, place) = discr_ty.expect_discr();
1196        let idx = if let Ok(ty) = env.lookup_place(&mut infcx.at(span), place)
1197            && let TyKind::Indexed(_, idx) = ty.kind()
1198        {
1199            Some(idx.clone())
1200        } else {
1201            None
1202        };
1203
1204        let mut successors = vec![];
1205        let mut remaining: FxHashMap<u128, VariantIdx> = adt_def
1206            .discriminants()
1207            .map(|(idx, discr)| (discr, idx))
1208            .collect();
1209        for (bits, bb) in targets.iter() {
1210            let variant_idx = remaining
1211                .remove(&bits)
1212                .expect("value doesn't correspond to any variant");
1213            successors.push((bb, Guard::Match(place.clone(), variant_idx)));
1214        }
1215        let guard = if remaining.len() == 1 {
1216            // If there's only one variant left, we know for sure that this is the one, so can force an unfold
1217            let (_, variant_idx) = remaining
1218                .into_iter()
1219                .next()
1220                .unwrap_or_else(|| tracked_span_bug!());
1221            Guard::Match(place.clone(), variant_idx)
1222        } else if adt_def.sort_def().is_reflected()
1223            && let Some(idx) = idx
1224        {
1225            // If there's more than one variant left, we can only assume the `is_ctor` holds for one of them
1226            let mut cases = vec![];
1227            for (_, variant_idx) in remaining {
1228                let did = adt_def.did();
1229                cases.push(rty::Expr::is_ctor(did, variant_idx, idx.clone()));
1230            }
1231            Guard::Pred(Expr::or_from_iter(cases))
1232        } else {
1233            Guard::None
1234        };
1235        successors.push((targets.otherwise(), guard));
1236
1237        successors
1238    }
1239
1240    fn check_successors(
1241        &mut self,
1242        mut infcx: InferCtxt<'_, 'genv, 'tcx>,
1243        env: TypeEnv,
1244        from: BasicBlock,
1245        terminator_span: Span,
1246        successors: Vec<(BasicBlock, Guard)>,
1247    ) -> Result {
1248        for (target, guard) in successors {
1249            let mut infcx = infcx.branch();
1250            let mut env = env.clone();
1251            match guard {
1252                Guard::None => {}
1253                Guard::Pred(expr) => {
1254                    infcx.assume_pred(&expr);
1255                }
1256                Guard::Match(place, variant_idx) => {
1257                    env.downcast(&mut infcx.at(terminator_span), &place, variant_idx)
1258                        .with_span(terminator_span)?;
1259                }
1260            }
1261            self.check_ghost_statements_at(
1262                &mut infcx,
1263                &mut env,
1264                Point::Edge(from, target),
1265                terminator_span,
1266            )?;
1267            self.check_goto(infcx, env, terminator_span, target)?;
1268        }
1269        Ok(())
1270    }
1271
1272    fn check_goto(
1273        &mut self,
1274        mut infcx: InferCtxt<'_, 'genv, 'tcx>,
1275        mut env: TypeEnv,
1276        span: Span,
1277        target: BasicBlock,
1278    ) -> Result {
1279        if self.is_exit_block(target) {
1280            // We inline *exit basic blocks* (i.e., that just return) because this typically
1281            // gives us better a better error span.
1282            let mut location = Location { block: target, statement_index: 0 };
1283            for _ in &self.body.basic_blocks[target].statements {
1284                self.check_ghost_statements_at(
1285                    &mut infcx,
1286                    &mut env,
1287                    Point::BeforeLocation(location),
1288                    span,
1289                )?;
1290                location = location.successor_within_block();
1291            }
1292            self.check_ghost_statements_at(
1293                &mut infcx,
1294                &mut env,
1295                Point::BeforeLocation(location),
1296                span,
1297            )?;
1298            self.check_ret(&mut infcx, &mut env, span)
1299        } else if self.body.is_join_point(target) {
1300            if M::check_goto_join_point(self, infcx, env, span, target)? {
1301                self.queue.insert(target);
1302            }
1303            Ok(())
1304        } else {
1305            self.check_basic_block(infcx, env, target)
1306        }
1307    }
1308
1309    fn closure_template(
1310        &mut self,
1311        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1312        env: &mut TypeEnv,
1313        stmt_span: Span,
1314        args: &flux_rustc_bridge::ty::GenericArgs,
1315        operands: &[Operand<'tcx>],
1316    ) -> InferResult<(Vec<Ty>, PolyFnSig)> {
1317        let upvar_tys = self
1318            .check_operands(infcx, env, stmt_span, operands)?
1319            .into_iter()
1320            .map(|ty| {
1321                if let TyKind::Ptr(PtrKind::Mut(re), path) = ty.kind() {
1322                    env.ptr_to_ref(
1323                        &mut infcx.at(stmt_span),
1324                        ConstrReason::Other,
1325                        *re,
1326                        path,
1327                        PtrToRefBound::Infer,
1328                    )
1329                } else {
1330                    Ok(ty.clone())
1331                }
1332            })
1333            .try_collect_vec()?;
1334
1335        let closure_args = args.as_closure();
1336        let ty = closure_args.sig_as_fn_ptr_ty();
1337
1338        if let flux_rustc_bridge::ty::TyKind::FnPtr(poly_sig) = ty.kind() {
1339            let poly_sig = poly_sig.unpack_closure_sig();
1340            let poly_sig = self.refine_with_holes(&poly_sig)?;
1341            let poly_sig = poly_sig.hoist_input_binders();
1342            let poly_sig = poly_sig
1343                .replace_holes(|binders, kind| infcx.fresh_infer_var_for_hole(binders, kind));
1344
1345            Ok((upvar_tys, poly_sig))
1346        } else {
1347            bug!("check_rvalue: closure: expected fn_ptr ty, found {ty:?} in {args:?}");
1348        }
1349    }
1350
1351    fn check_closure_body(
1352        &mut self,
1353        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1354        did: &DefId,
1355        upvar_tys: &[Ty],
1356        args: &flux_rustc_bridge::ty::GenericArgs,
1357        poly_sig: &PolyFnSig,
1358    ) -> Result {
1359        let genv = self.genv;
1360        let tcx = genv.tcx();
1361        #[expect(clippy::disallowed_methods, reason = "closures cannot be extern speced")]
1362        let closure_id = did.expect_local();
1363        let span = tcx.def_span(closure_id);
1364        let body = genv.mir(closure_id).with_span(span)?;
1365        let no_panic = self.genv.no_panic(*did);
1366        let closure_sig = rty::to_closure_sig(tcx, closure_id, upvar_tys, args, poly_sig, no_panic);
1367        Checker::run(
1368            infcx.change_item(closure_id, &body.infcx),
1369            closure_id,
1370            self.inherited.reborrow(),
1371            closure_sig,
1372        )
1373    }
1374
1375    fn check_rvalue_closure(
1376        &mut self,
1377        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1378        env: &mut TypeEnv,
1379        stmt_span: Span,
1380        did: &DefId,
1381        args: &flux_rustc_bridge::ty::GenericArgs,
1382        operands: &[Operand<'tcx>],
1383    ) -> Result<Ty> {
1384        // (1) Create the closure template
1385        let (upvar_tys, poly_sig) = self
1386            .closure_template(infcx, env, stmt_span, args, operands)
1387            .with_span(stmt_span)?;
1388        // (2) Check the closure body against the template
1389        self.check_closure_body(infcx, did, &upvar_tys, args, &poly_sig)?;
1390        // (3) "Save" the closure type in the `closures` map
1391        self.inherited.closures.insert(*did, poly_sig);
1392        // (4) Return the closure type
1393        let no_panic = self.genv.no_panic(*did);
1394        Ok(Ty::closure(*did, upvar_tys, args, no_panic))
1395    }
1396
1397    fn check_rvalue(
1398        &mut self,
1399        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1400        env: &mut TypeEnv,
1401        stmt_span: Span,
1402        rvalue: &Rvalue<'tcx>,
1403    ) -> Result<Ty> {
1404        let genv = self.genv;
1405        match rvalue {
1406            Rvalue::Use(operand) => {
1407                self.check_operand(infcx, env, stmt_span, operand)
1408                    .with_span(stmt_span)
1409            }
1410            Rvalue::Repeat(operand, c) => {
1411                let ty = self
1412                    .check_operand(infcx, env, stmt_span, operand)
1413                    .with_span(stmt_span)?;
1414                let arr_ty = ty
1415                    .with_holes()
1416                    .replace_holes(|binders, kind| infcx.fresh_infer_var_for_hole(binders, kind));
1417                infcx
1418                    .at(stmt_span)
1419                    .subtyping_with_env(env, &ty, &arr_ty, ConstrReason::Other)
1420                    .with_span(stmt_span)?;
1421                Ok(Ty::array(arr_ty, c.clone()))
1422            }
1423            Rvalue::Ref(r, BorrowKind::Mut { .. }, place) => {
1424                env.borrow(&mut infcx.at(stmt_span), *r, Mutability::Mut, place)
1425                    .with_span(stmt_span)
1426            }
1427            Rvalue::Ref(r, BorrowKind::Shared | BorrowKind::Fake(..), place) => {
1428                env.borrow(&mut infcx.at(stmt_span), *r, Mutability::Not, place)
1429                    .with_span(stmt_span)
1430            }
1431
1432            Rvalue::RawPtr(mir::RawPtrKind::FakeForPtrMetadata, place) => {
1433                // see tests/tests/neg/surface/slice02.rs for what happens without unfolding here.
1434                env.unfold(infcx, place, stmt_span).with_span(stmt_span)?;
1435                let ty = env
1436                    .lookup_place(&mut infcx.at(stmt_span), place)
1437                    .with_span(stmt_span)?;
1438                let ty = BaseTy::RawPtrMetadata(ty).to_ty();
1439                Ok(ty)
1440            }
1441            Rvalue::RawPtr(kind, place) => {
1442                // ignore any refinements on the type stored at place
1443                let ty = &env.lookup_rust_ty(genv, place).with_span(stmt_span)?;
1444                let ty = self.refine_default(ty).with_span(stmt_span)?;
1445                let ty = BaseTy::RawPtr(ty, kind.to_mutbl_lossy()).to_ty();
1446                Ok(ty)
1447            }
1448            Rvalue::Cast(kind, op, to) => {
1449                let from = self
1450                    .check_operand(infcx, env, stmt_span, op)
1451                    .with_span(stmt_span)?;
1452                self.check_cast(infcx, env, stmt_span, *kind, &from, to)
1453                    .with_span(stmt_span)
1454            }
1455            Rvalue::BinaryOp(bin_op, op1, op2) => {
1456                self.check_binary_op(infcx, env, stmt_span, *bin_op, op1, op2)
1457                    .with_span(stmt_span)
1458            }
1459
1460            Rvalue::UnaryOp(UnOp::PtrMetadata, Operand::Copy(place))
1461            | Rvalue::UnaryOp(UnOp::PtrMetadata, Operand::Move(place)) => {
1462                self.check_raw_ptr_metadata(infcx, env, stmt_span, place)
1463            }
1464            Rvalue::UnaryOp(un_op, op) => {
1465                self.check_unary_op(infcx, env, stmt_span, *un_op, op)
1466                    .with_span(stmt_span)
1467            }
1468            Rvalue::Discriminant(place) => {
1469                let ty = env
1470                    .lookup_place(&mut infcx.at(stmt_span), place)
1471                    .with_span(stmt_span)?;
1472                // HACK(nilehmann, mut-ref-unfolding) place should be unfolded here.
1473                let (adt_def, ..) = ty
1474                    .as_bty_skipping_existentials()
1475                    .unwrap_or_else(|| tracked_span_bug!())
1476                    .expect_adt();
1477                Ok(Ty::discr(adt_def.clone(), place.clone()))
1478            }
1479            Rvalue::Aggregate(
1480                AggregateKind::Adt(def_id, variant_idx, args, _, field_idx),
1481                operands,
1482            ) => {
1483                let actuals = self
1484                    .check_operands(infcx, env, stmt_span, operands)
1485                    .with_span(stmt_span)?;
1486                let sig = genv
1487                    .variant_sig(*def_id, *variant_idx)
1488                    .with_span(stmt_span)?
1489                    .ok_or_query_err(*def_id)
1490                    .with_span(stmt_span)?
1491                    .to_poly_fn_sig(*field_idx);
1492
1493                let args = instantiate_args_for_constructor(
1494                    genv,
1495                    self.checker_id.root_id().to_def_id(),
1496                    *def_id,
1497                    args,
1498                )
1499                .with_span(stmt_span)?;
1500                self.check_call(infcx, env, stmt_span, Some(*def_id), sig, &args, &actuals)
1501                    .map(|resolved_call| resolved_call.output)
1502            }
1503            Rvalue::Aggregate(AggregateKind::Array(arr_ty), operands) => {
1504                let args = self
1505                    .check_operands(infcx, env, stmt_span, operands)
1506                    .with_span(stmt_span)?;
1507                let arr_ty = self.refine_with_holes(arr_ty).with_span(stmt_span)?;
1508                self.check_mk_array(infcx, env, stmt_span, &args, arr_ty)
1509                    .with_span(stmt_span)
1510            }
1511            Rvalue::Aggregate(AggregateKind::Tuple, args) => {
1512                let tys = self
1513                    .check_operands(infcx, env, stmt_span, args)
1514                    .with_span(stmt_span)?;
1515                Ok(Ty::tuple(tys))
1516            }
1517            Rvalue::Aggregate(AggregateKind::Closure(did, args), operands) => {
1518                self.check_rvalue_closure(infcx, env, stmt_span, did, args, operands)
1519            }
1520            Rvalue::Aggregate(AggregateKind::Coroutine(did, args), ops) => {
1521                let coroutine_args = args.as_coroutine();
1522                let resume_ty = self
1523                    .refine_default(coroutine_args.resume_ty())
1524                    .with_span(stmt_span)?;
1525                let upvar_tys = self
1526                    .check_operands(infcx, env, stmt_span, ops)
1527                    .with_span(stmt_span)?;
1528                Ok(Ty::coroutine(*did, resume_ty, upvar_tys.into(), args.clone()))
1529            }
1530            Rvalue::ShallowInitBox(operand, _) => {
1531                self.check_operand(infcx, env, stmt_span, operand)
1532                    .with_span(stmt_span)?;
1533                Ty::mk_box_with_default_alloc(self.genv, Ty::uninit()).with_span(stmt_span)
1534            }
1535        }
1536    }
1537
1538    fn check_raw_ptr_metadata(
1539        &mut self,
1540        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1541        env: &mut TypeEnv,
1542        stmt_span: Span,
1543        place: &Place,
1544    ) -> Result<Ty> {
1545        let ty = env
1546            .lookup_place(&mut infcx.at(stmt_span), place)
1547            .with_span(stmt_span)?;
1548        let ty = match ty.kind() {
1549            TyKind::Indexed(BaseTy::RawPtrMetadata(ty), _)
1550            | TyKind::Indexed(BaseTy::Ref(_, ty, _), _) => ty,
1551            _ => tracked_span_bug!("check_metadata: bug! unexpected type `{ty:?}`"),
1552        };
1553        match ty.kind() {
1554            TyKind::Indexed(BaseTy::Array(_, len), _) => {
1555                let idx = Expr::from_const(self.genv.tcx(), len);
1556                Ok(Ty::indexed(BaseTy::Uint(UintTy::Usize), idx))
1557            }
1558            TyKind::Indexed(BaseTy::Slice(_), len) => {
1559                Ok(Ty::indexed(BaseTy::Uint(UintTy::Usize), len.clone()))
1560            }
1561            _ => Ok(Ty::unit()),
1562        }
1563    }
1564
1565    fn check_binary_op(
1566        &mut self,
1567        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1568        env: &mut TypeEnv,
1569        stmt_span: Span,
1570        bin_op: mir::BinOp,
1571        op1: &Operand<'tcx>,
1572        op2: &Operand<'tcx>,
1573    ) -> InferResult<Ty> {
1574        let ty1 = self.check_operand(infcx, env, stmt_span, op1)?;
1575        let ty2 = self.check_operand(infcx, env, stmt_span, op2)?;
1576
1577        match (ty1.kind(), ty2.kind()) {
1578            (TyKind::Indexed(bty1, idx1), TyKind::Indexed(bty2, idx2)) => {
1579                let rule =
1580                    primops::match_bin_op(bin_op, bty1, idx1, bty2, idx2, infcx.check_overflow);
1581                if let Some(pre) = rule.precondition {
1582                    infcx.at(stmt_span).check_pred(pre.pred, pre.reason);
1583                }
1584
1585                Ok(rule.output_type)
1586            }
1587            _ => tracked_span_bug!("incompatible types: `{ty1:?}` `{ty2:?}`"),
1588        }
1589    }
1590
1591    fn check_unary_op(
1592        &mut self,
1593        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1594        env: &mut TypeEnv,
1595        stmt_span: Span,
1596        un_op: mir::UnOp,
1597        op: &Operand<'tcx>,
1598    ) -> InferResult<Ty> {
1599        let ty = self.check_operand(infcx, env, stmt_span, op)?;
1600        match ty.kind() {
1601            TyKind::Indexed(bty, idx) => {
1602                let rule = primops::match_un_op(un_op, bty, idx, infcx.check_overflow);
1603                if let Some(pre) = rule.precondition {
1604                    infcx.at(stmt_span).check_pred(pre.pred, pre.reason);
1605                }
1606                Ok(rule.output_type)
1607            }
1608            _ => tracked_span_bug!("invalid type for unary operator `{un_op:?}` `{ty:?}`"),
1609        }
1610    }
1611
1612    fn check_mk_array(
1613        &mut self,
1614        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1615        env: &mut TypeEnv,
1616        stmt_span: Span,
1617        args: &[Ty],
1618        arr_ty: Ty,
1619    ) -> InferResult<Ty> {
1620        let arr_ty = infcx.ensure_resolved_evars(|infcx| {
1621            let arr_ty =
1622                arr_ty.replace_holes(|binders, kind| infcx.fresh_infer_var_for_hole(binders, kind));
1623
1624            let (arr_ty, pred) = arr_ty.unconstr();
1625            let mut at = infcx.at(stmt_span);
1626            at.check_pred(&pred, ConstrReason::Other);
1627            for ty in args {
1628                at.subtyping_with_env(env, ty, &arr_ty, ConstrReason::Other)?;
1629            }
1630            Ok(arr_ty)
1631        })?;
1632        let arr_ty = infcx.fully_resolve_evars(&arr_ty);
1633
1634        Ok(Ty::array(arr_ty, rty::Const::from_usize(self.genv.tcx(), args.len())))
1635    }
1636
1637    fn check_cast(
1638        &self,
1639        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1640        env: &mut TypeEnv,
1641        stmt_span: Span,
1642        kind: CastKind,
1643        from: &Ty,
1644        to: &ty::Ty,
1645    ) -> InferResult<Ty> {
1646        use ty::TyKind as RustTy;
1647        let ty = match kind {
1648            CastKind::PointerExposeProvenance => {
1649                match to.kind() {
1650                    RustTy::Int(int_ty) => Ty::int(*int_ty),
1651                    RustTy::Uint(uint_ty) => Ty::uint(*uint_ty),
1652                    _ => tracked_span_bug!("unsupported PointerExposeProvenance cast"),
1653                }
1654            }
1655            CastKind::IntToInt => {
1656                match (from.kind(), to.kind()) {
1657                    (Bool!(idx), RustTy::Int(int_ty)) => bool_int_cast(idx, *int_ty),
1658                    (Bool!(idx), RustTy::Uint(uint_ty)) => bool_uint_cast(idx, *uint_ty),
1659                    (Int!(int_ty1, idx), RustTy::Int(int_ty2)) => {
1660                        int_int_cast(idx, *int_ty1, *int_ty2)
1661                    }
1662                    (Uint!(uint_ty1, idx), RustTy::Uint(uint_ty2)) => {
1663                        uint_uint_cast(idx, *uint_ty1, *uint_ty2)
1664                    }
1665                    (Uint!(uint_ty, idx), RustTy::Int(int_ty)) => {
1666                        uint_int_cast(idx, *uint_ty, *int_ty)
1667                    }
1668                    (Int!(int_ty, idx), RustTy::Uint(uint_ty)) => {
1669                        int_uint_cast(idx, *int_ty, *uint_ty)
1670                    }
1671                    (TyKind::Discr(adt_def, _), RustTy::Int(int_ty)) => {
1672                        Self::discr_to_int_cast(adt_def, BaseTy::Int(*int_ty))
1673                    }
1674                    (TyKind::Discr(adt_def, _place), RustTy::Uint(uint_ty)) => {
1675                        Self::discr_to_int_cast(adt_def, BaseTy::Uint(*uint_ty))
1676                    }
1677                    (Char!(idx), RustTy::Uint(uint_ty)) => char_uint_cast(idx, *uint_ty),
1678                    (Uint!(_, idx), RustTy::Char) => uint_char_cast(idx),
1679                    _ => {
1680                        tracked_span_bug!("invalid int to int cast {from:?} --> {to:?}")
1681                    }
1682                }
1683            }
1684            CastKind::PointerCoercion(mir::PointerCast::Unsize) => {
1685                self.check_unsize_cast(infcx, env, stmt_span, from, to)?
1686            }
1687            CastKind::FloatToInt
1688            | CastKind::IntToFloat
1689            | CastKind::PtrToPtr
1690            | CastKind::PointerCoercion(mir::PointerCast::MutToConstPointer)
1691            | CastKind::PointerCoercion(mir::PointerCast::ClosureFnPointer)
1692            | CastKind::PointerWithExposedProvenance => self.refine_default(to)?,
1693            CastKind::PointerCoercion(mir::PointerCast::ReifyFnPointer) => {
1694                let to = self.refine_default(to)?;
1695                if let TyKind::Indexed(BaseTy::FnDef(def_id, args), _) = from.kind()
1696                    && let TyKind::Indexed(BaseTy::FnPtr(super_sig), _) = to.kind()
1697                {
1698                    let current_did = infcx.def_id;
1699                    let sub_sig =
1700                        SubFn::Poly(current_did, infcx.genv.fn_sig(*def_id)?, args.clone());
1701                    // TODO:CLOSURE:2 TODO(RJ) dicey maneuver? assumes that sig_b is unrefined?
1702                    check_fn_subtyping(infcx, sub_sig, super_sig, stmt_span)?;
1703                    to
1704                } else {
1705                    tracked_span_bug!("invalid cast from `{from:?}` to `{to:?}`")
1706                }
1707            }
1708        };
1709        Ok(ty)
1710    }
1711
1712    fn discr_to_int_cast(adt_def: &AdtDef, bty: BaseTy) -> Ty {
1713        // TODO: This could be a giant disjunction, maybe better (if less precise) to use the interval?
1714        let vals = adt_def
1715            .discriminants()
1716            .map(|(_, idx)| Expr::eq(Expr::nu(), Expr::from_bits(&bty, idx)))
1717            .collect_vec();
1718        Ty::exists_with_constr(bty, Expr::or_from_iter(vals))
1719    }
1720
1721    fn check_unsize_cast(
1722        &self,
1723        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1724        env: &mut TypeEnv,
1725        span: Span,
1726        src: &Ty,
1727        dst: &ty::Ty,
1728    ) -> InferResult<Ty> {
1729        // Convert `ptr` to `&mut`
1730        let src = if let TyKind::Ptr(PtrKind::Mut(re), path) = src.kind() {
1731            env.ptr_to_ref(
1732                &mut infcx.at(span),
1733                ConstrReason::Other,
1734                *re,
1735                path,
1736                PtrToRefBound::Identity,
1737            )?
1738        } else {
1739            src.clone()
1740        };
1741
1742        if let ty::TyKind::Ref(_, deref_ty, _) = dst.kind()
1743            && let ty::TyKind::Dynamic(..) = deref_ty.kind()
1744        {
1745            return Ok(self.refine_default(dst)?);
1746        }
1747
1748        // `&mut [T; n] -> &mut [T]` or `&[T; n] -> &[T]`
1749        if let TyKind::Indexed(BaseTy::Ref(_, deref_ty, _), _) = src.kind()
1750            && let TyKind::Indexed(BaseTy::Array(arr_ty, arr_len), _) = deref_ty.kind()
1751            && let ty::TyKind::Ref(re, _, mutbl) = dst.kind()
1752        {
1753            let idx = Expr::from_const(self.genv.tcx(), arr_len);
1754            Ok(Ty::mk_ref(*re, Ty::indexed(BaseTy::Slice(arr_ty.clone()), idx), *mutbl))
1755
1756        // `Box<[T; n]> -> Box<[T]>`
1757        } else if let TyKind::Indexed(BaseTy::Adt(adt_def, args), _) = src.kind()
1758            && adt_def.is_box()
1759            && let (deref_ty, alloc_ty) = args.box_args()
1760            && let TyKind::Indexed(BaseTy::Array(arr_ty, arr_len), _) = deref_ty.kind()
1761        {
1762            let idx = Expr::from_const(self.genv.tcx(), arr_len);
1763            Ok(Ty::mk_box(
1764                self.genv,
1765                Ty::indexed(BaseTy::Slice(arr_ty.clone()), idx),
1766                alloc_ty.clone(),
1767            )?)
1768        } else {
1769            Err(query_bug!("unsupported unsize cast from `{src:?}` to `{dst:?}`"))?
1770        }
1771    }
1772
1773    fn check_operands(
1774        &mut self,
1775        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1776        env: &mut TypeEnv,
1777        span: Span,
1778        operands: &[Operand<'tcx>],
1779    ) -> InferResult<Vec<Ty>> {
1780        operands
1781            .iter()
1782            .map(|op| self.check_operand(infcx, env, span, op))
1783            .try_collect()
1784    }
1785
1786    fn check_operand(
1787        &mut self,
1788        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1789        env: &mut TypeEnv,
1790        span: Span,
1791        operand: &Operand<'tcx>,
1792    ) -> InferResult<Ty> {
1793        let ty = match operand {
1794            Operand::Copy(p) => env.lookup_place(&mut infcx.at(span), p)?,
1795            Operand::Move(p) => env.move_place(&mut infcx.at(span), p)?,
1796            Operand::Constant(c) => self.check_constant(infcx, c)?,
1797        };
1798        Ok(infcx.hoister(true).hoist(&ty))
1799    }
1800
1801    fn check_constant(
1802        &mut self,
1803        infcx: &InferCtxt<'_, 'genv, 'tcx>,
1804        constant: &ConstOperand<'tcx>,
1805    ) -> QueryResult<Ty> {
1806        use rustc_middle::mir::Const;
1807        match constant.const_ {
1808            Const::Ty(ty, cst) => self.check_ty_const(constant, cst, ty)?,
1809            Const::Val(val, ty) => self.check_const_val(val, ty)?,
1810            Const::Unevaluated(uneval, ty) => {
1811                self.check_uneval_const(infcx, constant, uneval, ty)?
1812            }
1813        }
1814        .map_or_else(|| self.refine_default(&constant.ty), Ok)
1815    }
1816
1817    fn check_ty_const(
1818        &mut self,
1819        constant: &ConstOperand<'tcx>,
1820        cst: rustc_middle::ty::Const<'tcx>,
1821        ty: rustc_middle::ty::Ty<'tcx>,
1822    ) -> QueryResult<Option<Ty>> {
1823        use rustc_middle::ty::ConstKind;
1824        match cst.kind() {
1825            ConstKind::Param(param) => {
1826                let idx = Expr::const_generic(param);
1827                let ctor = self
1828                    .default_refiner
1829                    .refine_ty_or_base(&constant.ty)?
1830                    .expect_base();
1831                Ok(Some(ctor.replace_bound_reft(&idx).to_ty()))
1832            }
1833            ConstKind::Value(val_tree) => {
1834                let val = self.genv.tcx().valtree_to_const_val(val_tree);
1835                Ok(self.check_const_val(val, ty)?)
1836            }
1837            _ => Ok(None),
1838        }
1839    }
1840
1841    fn check_const_val(
1842        &mut self,
1843        val: rustc_middle::mir::ConstValue,
1844        ty: rustc_middle::ty::Ty<'tcx>,
1845    ) -> QueryResult<Option<Ty>> {
1846        use rustc_middle::{mir::ConstValue, ty};
1847        match val {
1848            ConstValue::Scalar(scalar) => self.check_scalar(scalar, ty),
1849            ConstValue::ZeroSized if ty.is_unit() => Ok(Some(Ty::unit())),
1850            ConstValue::Slice { .. } => {
1851                if let ty::Ref(_, ref_ty, Mutability::Not) = ty.kind()
1852                    && ref_ty.is_str()
1853                    && let Some(data) = val.try_get_slice_bytes_for_diagnostics(self.genv.tcx())
1854                {
1855                    let str = String::from_utf8_lossy(data);
1856                    let idx = Expr::constant(Constant::Str(Symbol::intern(&str)));
1857                    Ok(Some(Ty::mk_ref(ReErased, Ty::indexed(BaseTy::Str, idx), Mutability::Not)))
1858                } else {
1859                    Ok(None)
1860                }
1861            }
1862            _ => Ok(None),
1863        }
1864    }
1865
1866    fn check_uneval_const(
1867        &mut self,
1868        infcx: &InferCtxt<'_, 'genv, 'tcx>,
1869        constant: &ConstOperand<'tcx>,
1870        uneval: rustc_middle::mir::UnevaluatedConst<'tcx>,
1871        ty: rustc_middle::ty::Ty<'tcx>,
1872    ) -> QueryResult<Option<Ty>> {
1873        // 1. Use template for promoted constants, if applicable
1874        if let Some(promoted) = uneval.promoted
1875            && let Some(ty) = self.promoted.get(promoted)
1876        {
1877            return Ok(Some(ty.clone()));
1878        }
1879
1880        // 2. `Genv::constant_info` cannot handle constants with generics, so, we evaluate
1881        //    them here. These mostly come from inline consts, e.g., `const { 1 + 1 }`, because
1882        //    the generic_const_items feature is unstable.
1883        if !uneval.args.is_empty() {
1884            let tcx = self.genv.tcx();
1885            let param_env = tcx.param_env(self.checker_id.root_id());
1886            let typing_env = infcx.region_infcx.typing_env(param_env);
1887            if let Ok(val) = tcx.const_eval_resolve(typing_env, uneval, constant.span) {
1888                return self.check_const_val(val, ty);
1889            } else {
1890                return Ok(None);
1891            }
1892        }
1893
1894        // 3. Try to see if we have `consant_info` for it.
1895        if let rty::TyOrBase::Base(ctor) = self.default_refiner.refine_ty_or_base(&constant.ty)?
1896            && let rty::ConstantInfo::Interpreted(idx, _) = self.genv.constant_info(uneval.def)?
1897        {
1898            return Ok(Some(ctor.replace_bound_reft(&idx).to_ty()));
1899        }
1900
1901        Ok(None)
1902    }
1903
1904    fn check_scalar(
1905        &mut self,
1906        scalar: rustc_middle::mir::interpret::Scalar,
1907        ty: rustc_middle::ty::Ty<'tcx>,
1908    ) -> QueryResult<Option<Ty>> {
1909        use rustc_middle::mir::interpret::{GlobalAlloc, Scalar};
1910        match scalar {
1911            Scalar::Int(scalar_int) => Ok(self.check_scalar_int(scalar_int, ty)),
1912            Scalar::Ptr(ptr, _) => {
1913                let alloc_id = ptr.provenance.alloc_id();
1914                if let GlobalAlloc::Static(def_id) = self.genv.tcx().global_alloc(alloc_id)
1915                    && let rty::StaticInfo::Known(ty) = self.genv.static_info(def_id)?
1916                    && !self.genv.tcx().is_mutable_static(def_id)
1917                // TODO: mutable statics!
1918                {
1919                    Ok(Some(Ty::mk_ref(ReErased, ty, Mutability::Not)))
1920                } else {
1921                    Ok(None)
1922                }
1923            }
1924        }
1925    }
1926
1927    fn check_scalar_int(
1928        &mut self,
1929        scalar: rustc_middle::ty::ScalarInt,
1930        ty: rustc_middle::ty::Ty<'tcx>,
1931    ) -> Option<Ty> {
1932        use flux_rustc_bridge::const_eval::{scalar_to_int, scalar_to_uint};
1933        use rustc_middle::ty;
1934
1935        let tcx = self.genv.tcx();
1936
1937        match ty.kind() {
1938            ty::Int(int_ty) => {
1939                let idx = Expr::constant(Constant::from(scalar_to_int(tcx, scalar, *int_ty)));
1940                Some(Ty::indexed(BaseTy::Int(*int_ty), idx))
1941            }
1942            ty::Uint(uint_ty) => {
1943                let idx = Expr::constant(Constant::from(scalar_to_uint(tcx, scalar, *uint_ty)));
1944                Some(Ty::indexed(BaseTy::Uint(*uint_ty), idx))
1945            }
1946            ty::Float(float_ty) => Some(Ty::float(*float_ty)),
1947            ty::Char => {
1948                let idx = Expr::constant(Constant::Char(scalar.try_into().unwrap()));
1949                Some(Ty::indexed(BaseTy::Char, idx))
1950            }
1951            ty::Bool => {
1952                let idx = Expr::constant(Constant::Bool(scalar.try_to_bool().unwrap()));
1953                Some(Ty::indexed(BaseTy::Bool, idx))
1954            }
1955            // ty::Tuple(tys) if tys.is_empty() => Constant::Unit,
1956            _ => None,
1957        }
1958    }
1959
1960    fn check_ghost_statements_at(
1961        &mut self,
1962        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1963        env: &mut TypeEnv,
1964        point: Point,
1965        span: Span,
1966    ) -> Result {
1967        bug::track_span(span, || {
1968            for stmt in self.ghost_stmts().statements_at(point) {
1969                self.check_ghost_statement(infcx, env, stmt, span)
1970                    .with_span(span)?;
1971            }
1972            Ok(())
1973        })
1974    }
1975
1976    fn check_ghost_statement(
1977        &mut self,
1978        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
1979        env: &mut TypeEnv,
1980        stmt: &GhostStatement,
1981        span: Span,
1982    ) -> InferResult {
1983        dbg::statement!("start", stmt, infcx, env, span, &self);
1984        match stmt {
1985            GhostStatement::Fold(place) => {
1986                env.fold(&mut infcx.at(span), place)?;
1987            }
1988            GhostStatement::Unfold(place) => {
1989                env.unfold(infcx, place, span)?;
1990            }
1991            GhostStatement::Unblock(place) => env.unblock(infcx, place),
1992            GhostStatement::PtrToRef(place) => {
1993                env.ptr_to_ref_at_place(&mut infcx.at(span), place)?;
1994            }
1995        }
1996        dbg::statement!("end", stmt, infcx, env, span, &self);
1997        Ok(())
1998    }
1999
2000    #[track_caller]
2001    fn marker_at_dominator(&self, bb: BasicBlock) -> &Marker {
2002        marker_at_dominator(self.body, &self.markers, bb)
2003    }
2004
2005    fn dominators(&self) -> &'ck Dominators<BasicBlock> {
2006        self.body.dominators()
2007    }
2008
2009    fn ghost_stmts(&self) -> &'ck GhostStatements {
2010        &self.inherited.ghost_stmts[&self.checker_id]
2011    }
2012
2013    fn refine_default<T: Refine>(&self, ty: &T) -> QueryResult<T::Output> {
2014        ty.refine(&self.default_refiner)
2015    }
2016
2017    fn refine_with_holes<T: Refine>(&self, ty: &T) -> QueryResult<<T as Refine>::Output> {
2018        ty.refine(&Refiner::with_holes(self.genv, self.checker_id.root_id().to_def_id())?)
2019    }
2020}
2021
2022fn instantiate_args_for_fun_call(
2023    genv: GlobalEnv,
2024    caller_id: DefId,
2025    callee_id: DefId,
2026    args: &ty::GenericArgs,
2027) -> QueryResult<Vec<rty::GenericArg>> {
2028    let params_in_clauses = collect_params_in_clauses(genv, callee_id);
2029    let assumed_parametric_params = genv.assume_parametric_params(callee_id);
2030
2031    let hole_refiner = Refiner::new_for_item(genv, caller_id, |bty| {
2032        let sort = bty.sort();
2033        let bty = bty.shift_in_escaping(1);
2034        let constr = if !sort.is_unit() {
2035            rty::SubsetTy::new(bty, Expr::nu(), Expr::hole(rty::HoleKind::Pred))
2036        } else {
2037            rty::SubsetTy::trivial(bty, Expr::nu())
2038        };
2039        Binder::bind_with_sort(constr, sort)
2040    })?;
2041    let default_refiner = Refiner::default_for_item(genv, caller_id)?;
2042
2043    let callee_generics = genv.generics_of(callee_id)?;
2044    args.iter()
2045        .enumerate()
2046        .map(|(idx, arg)| {
2047            let param = callee_generics.param_at(idx, genv)?;
2048            let is_parametric = !params_in_clauses.contains(&idx)
2049                || assumed_parametric_params.contains(&(idx as u32));
2050            let refiner = if is_parametric { &hole_refiner } else { &default_refiner };
2051            refiner.refine_generic_arg(&param, arg)
2052        })
2053        .collect()
2054}
2055
2056fn instantiate_args_for_constructor(
2057    genv: GlobalEnv,
2058    caller_id: DefId,
2059    adt_id: DefId,
2060    args: &ty::GenericArgs,
2061) -> QueryResult<Vec<rty::GenericArg>> {
2062    let params_in_clauses = collect_params_in_clauses(genv, adt_id);
2063
2064    let adt_generics = genv.generics_of(adt_id)?;
2065    let hole_refiner = Refiner::with_holes(genv, caller_id)?;
2066    let default_refiner = Refiner::default_for_item(genv, caller_id)?;
2067    args.iter()
2068        .enumerate()
2069        .map(|(idx, arg)| {
2070            let param = adt_generics.param_at(idx, genv)?;
2071            let refiner =
2072                if params_in_clauses.contains(&idx) { &default_refiner } else { &hole_refiner };
2073            refiner.refine_generic_arg(&param, arg)
2074        })
2075        .collect()
2076}
2077
2078fn collect_params_in_clauses(genv: GlobalEnv, def_id: DefId) -> UnordSet<usize> {
2079    let tcx = genv.tcx();
2080    struct Collector {
2081        params: UnordSet<usize>,
2082    }
2083
2084    impl rustc_middle::ty::TypeVisitor<TyCtxt<'_>> for Collector {
2085        fn visit_ty(&mut self, t: rustc_middle::ty::Ty) {
2086            if let rustc_middle::ty::Param(param_ty) = t.kind() {
2087                self.params.insert(param_ty.index as usize);
2088            }
2089            t.super_visit_with(self);
2090        }
2091    }
2092    let mut vis = Collector { params: UnordSet::new() };
2093
2094    let span = genv.tcx().def_span(def_id);
2095    for (clause, _) in all_predicates_of(tcx, def_id) {
2096        if let Some(trait_pred) = clause.as_trait_clause() {
2097            let trait_id = trait_pred.def_id();
2098            let ignore = [
2099                LangItem::MetaSized,
2100                LangItem::Sized,
2101                LangItem::Tuple,
2102                LangItem::Copy,
2103                LangItem::Destruct,
2104            ];
2105            if ignore
2106                .iter()
2107                .any(|lang_item| tcx.require_lang_item(*lang_item, span) == trait_id)
2108            {
2109                continue;
2110            }
2111
2112            if tcx.fn_trait_kind_from_def_id(trait_id).is_some() {
2113                continue;
2114            }
2115            if tcx.get_diagnostic_item(sym::Hash) == Some(trait_id) {
2116                continue;
2117            }
2118            if tcx.get_diagnostic_item(sym::Eq) == Some(trait_id) {
2119                continue;
2120            }
2121        }
2122        if let Some(proj_pred) = clause.as_projection_clause() {
2123            let assoc_id = proj_pred.item_def_id();
2124            if genv.is_fn_output(assoc_id) {
2125                continue;
2126            }
2127        }
2128        if let Some(outlives_pred) = clause.as_type_outlives_clause() {
2129            // We skip outlives bounds if they are not 'static. A 'static bound means the type
2130            // implements `Any` which makes it unsound to instantiate the argument with refinements.
2131            if outlives_pred.skip_binder().1 != tcx.lifetimes.re_static {
2132                continue;
2133            }
2134        }
2135        clause.visit_with(&mut vis);
2136    }
2137    vis.params
2138}
2139
2140fn all_predicates_of(
2141    tcx: TyCtxt<'_>,
2142    id: DefId,
2143) -> impl Iterator<Item = &(rustc_middle::ty::Clause<'_>, Span)> {
2144    let mut next_id = Some(id);
2145    iter::from_fn(move || {
2146        next_id.take().map(|id| {
2147            let preds = tcx.predicates_of(id);
2148            next_id = preds.parent;
2149            preds.predicates.iter()
2150        })
2151    })
2152    .flatten()
2153}
2154
2155struct SkipConstr;
2156
2157impl TypeFolder for SkipConstr {
2158    fn fold_ty(&mut self, ty: &rty::Ty) -> rty::Ty {
2159        if let rty::TyKind::Constr(_, inner_ty) = ty.kind() {
2160            inner_ty.fold_with(self)
2161        } else {
2162            ty.super_fold_with(self)
2163        }
2164    }
2165}
2166
2167fn is_indexed_mut_skipping_constr(ty: &Ty) -> bool {
2168    let ty = SkipConstr.fold_ty(ty);
2169    if let rty::Ref!(_, inner_ty, Mutability::Mut) = ty.kind()
2170        && let TyKind::Indexed(..) = inner_ty.kind()
2171    {
2172        true
2173    } else {
2174        false
2175    }
2176}
2177
2178/// HACK(nilehmann) This let us infer parameters under mutable references for the simple case
2179/// where the formal argument is of the form `&mut B[@n]`, e.g., the type of the first argument
2180/// to `RVec::get_mut` is `&mut RVec<T>[@n]`. We should remove this after we implement opening of
2181/// mutable references.
2182fn infer_under_mut_ref_hack(rcx: &mut InferCtxt, actuals: &[Ty], fn_sig: &PolyFnSig) -> Vec<Ty> {
2183    iter::zip(actuals, fn_sig.skip_binder_ref().inputs())
2184        .map(|(actual, formal)| {
2185            if let rty::Ref!(re, deref_ty, Mutability::Mut) = actual.kind()
2186                && is_indexed_mut_skipping_constr(formal)
2187            {
2188                rty::Ty::mk_ref(*re, rcx.unpack(deref_ty), Mutability::Mut)
2189            } else {
2190                actual.clone()
2191            }
2192        })
2193        .collect()
2194}
2195
2196impl Mode for ShapeMode {
2197    const NAME: &str = "shape";
2198
2199    fn enter_basic_block<'ck, 'genv, 'tcx>(
2200        ck: &mut Checker<'ck, 'genv, 'tcx, ShapeMode>,
2201        _infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
2202        bb: BasicBlock,
2203    ) -> TypeEnv<'ck> {
2204        ck.inherited.mode.bb_envs[&ck.checker_id][&bb].enter(&ck.body.local_decls)
2205    }
2206
2207    fn check_goto_join_point<'genv, 'tcx>(
2208        ck: &mut Checker<'_, 'genv, 'tcx, ShapeMode>,
2209        _: InferCtxt<'_, 'genv, 'tcx>,
2210        env: TypeEnv,
2211        span: Span,
2212        target: BasicBlock,
2213    ) -> Result<bool> {
2214        let bb_envs = &mut ck.inherited.mode.bb_envs;
2215        let target_bb_env = bb_envs.entry(ck.checker_id).or_default().get(&target);
2216        dbg::shape_goto_enter!(target, env, target_bb_env);
2217
2218        let modified = match bb_envs.entry(ck.checker_id).or_default().entry(target) {
2219            Entry::Occupied(mut entry) => entry.get_mut().join(env, span),
2220            Entry::Vacant(entry) => {
2221                let scope = marker_at_dominator(ck.body, &ck.markers, target)
2222                    .scope()
2223                    .unwrap_or_else(|| tracked_span_bug!());
2224                entry.insert(env.into_infer(scope));
2225                true
2226            }
2227        };
2228
2229        dbg::shape_goto_exit!(target, bb_envs[&ck.checker_id].get(&target));
2230        Ok(modified)
2231    }
2232
2233    fn clear(ck: &mut Checker<ShapeMode>, root: BasicBlock) {
2234        ck.visited.remove(root);
2235        for bb in ck.body.basic_blocks.indices() {
2236            if bb != root && ck.dominators().dominates(root, bb) {
2237                ck.inherited
2238                    .mode
2239                    .bb_envs
2240                    .entry(ck.checker_id)
2241                    .or_default()
2242                    .remove(&bb);
2243                ck.visited.remove(bb);
2244            }
2245        }
2246    }
2247}
2248
2249impl Mode for RefineMode {
2250    const NAME: &str = "refine";
2251
2252    fn enter_basic_block<'ck, 'genv, 'tcx>(
2253        ck: &mut Checker<'ck, 'genv, 'tcx, RefineMode>,
2254        infcx: &mut InferCtxt<'_, 'genv, 'tcx>,
2255        bb: BasicBlock,
2256    ) -> TypeEnv<'ck> {
2257        ck.inherited.mode.bb_envs[&ck.checker_id][&bb].enter(infcx, &ck.body.local_decls)
2258    }
2259
2260    fn check_goto_join_point(
2261        ck: &mut Checker<RefineMode>,
2262        mut infcx: InferCtxt,
2263        env: TypeEnv,
2264        terminator_span: Span,
2265        target: BasicBlock,
2266    ) -> Result<bool> {
2267        let bb_env = &ck.inherited.mode.bb_envs[&ck.checker_id][&target];
2268        tracked_span_dbg_assert_eq!(
2269            &ck.marker_at_dominator(target)
2270                .scope()
2271                .unwrap_or_else(|| tracked_span_bug!()),
2272            bb_env.scope()
2273        );
2274
2275        dbg::refine_goto!(target, infcx, env, bb_env);
2276
2277        env.check_goto(&mut infcx.at(terminator_span), bb_env, target)
2278            .with_span(terminator_span)?;
2279
2280        Ok(!ck.visited.contains(target))
2281    }
2282
2283    fn clear(_ck: &mut Checker<RefineMode>, _bb: BasicBlock) {
2284        bug!();
2285    }
2286}
2287
2288fn bool_int_cast(b: &Expr, int_ty: IntTy) -> Ty {
2289    let idx = Expr::ite(b, 1, 0);
2290    Ty::indexed(BaseTy::Int(int_ty), idx)
2291}
2292
2293/// Unlike [`char_uint_cast`] rust only allows `u8` to `char` casts, which are
2294/// non-lossy, so we can use indexed type directly.
2295fn uint_char_cast(idx: &Expr) -> Ty {
2296    let idx = Expr::cast(rty::Sort::Int, rty::Sort::Char, idx.clone());
2297    Ty::indexed(BaseTy::Char, idx)
2298}
2299
2300fn char_uint_cast(idx: &Expr, uint_ty: UintTy) -> Ty {
2301    let idx = Expr::cast(rty::Sort::Char, rty::Sort::Int, idx.clone());
2302    if uint_bit_width(uint_ty) >= 32 {
2303        // non-lossy cast: uint[cast(idx)]
2304        Ty::indexed(BaseTy::Uint(uint_ty), idx)
2305    } else {
2306        // lossy-cast: uint{v: cast(idx) <= max_value => v == cast(idx) }
2307        guarded_uint_ty(&idx, uint_ty)
2308    }
2309}
2310
2311fn bool_uint_cast(b: &Expr, uint_ty: UintTy) -> Ty {
2312    let idx = Expr::ite(b, 1, 0);
2313    Ty::indexed(BaseTy::Uint(uint_ty), idx)
2314}
2315
2316fn int_int_cast(idx: &Expr, int_ty1: IntTy, int_ty2: IntTy) -> Ty {
2317    if int_bit_width(int_ty1) <= int_bit_width(int_ty2) {
2318        Ty::indexed(BaseTy::Int(int_ty2), idx.clone())
2319    } else {
2320        Ty::int(int_ty2)
2321    }
2322}
2323
2324fn uint_int_cast(idx: &Expr, uint_ty: UintTy, int_ty: IntTy) -> Ty {
2325    if uint_bit_width(uint_ty) < int_bit_width(int_ty) {
2326        Ty::indexed(BaseTy::Int(int_ty), idx.clone())
2327    } else {
2328        Ty::int(int_ty)
2329    }
2330}
2331
2332fn int_uint_cast(idx: &Expr, int_ty: IntTy, uint_ty: UintTy) -> Ty {
2333    let non_neg = Expr::ge(idx.clone(), Expr::zero());
2334
2335    let guard: Expr = if int_bit_width(int_ty) <= uint_bit_width(uint_ty) {
2336        non_neg
2337    } else {
2338        // Cast is still possible if the value is known to fit.
2339        let fits = Expr::le(idx.clone(), Expr::uint_max(uint_ty));
2340        Expr::and(non_neg, fits)
2341    };
2342
2343    let eq = Expr::eq(Expr::nu(), idx.clone());
2344    Ty::exists_with_constr(BaseTy::Uint(uint_ty), Expr::implies(guard, eq))
2345}
2346
2347fn guarded_uint_ty(idx: &Expr, uint_ty: UintTy) -> Ty {
2348    // uint_ty2{v: idx <= max_value => v == idx }
2349    let max_value = Expr::uint_max(uint_ty);
2350    let guard = Expr::le(idx.clone(), max_value);
2351    let eq = Expr::eq(Expr::nu(), idx.clone());
2352    Ty::exists_with_constr(BaseTy::Uint(uint_ty), Expr::implies(guard, eq))
2353}
2354
2355fn uint_uint_cast(idx: &Expr, uint_ty1: UintTy, uint_ty2: UintTy) -> Ty {
2356    if uint_bit_width(uint_ty1) <= uint_bit_width(uint_ty2) {
2357        Ty::indexed(BaseTy::Uint(uint_ty2), idx.clone())
2358    } else {
2359        guarded_uint_ty(idx, uint_ty2)
2360    }
2361}
2362
2363fn uint_bit_width(uint_ty: UintTy) -> u64 {
2364    uint_ty
2365        .bit_width()
2366        .unwrap_or(config::pointer_width().bits())
2367}
2368
2369fn int_bit_width(int_ty: IntTy) -> u64 {
2370    int_ty.bit_width().unwrap_or(config::pointer_width().bits())
2371}
2372
2373impl ShapeResult {
2374    fn into_bb_envs(
2375        self,
2376        infcx: &mut InferCtxtRoot,
2377        body: &Body,
2378    ) -> FxHashMap<CheckerId, FxHashMap<BasicBlock, BasicBlockEnv>> {
2379        self.0
2380            .into_iter()
2381            .map(|(checker_id, shapes)| {
2382                let bb_envs = shapes
2383                    .into_iter()
2384                    .map(|(bb, shape)| (bb, shape.into_bb_env(infcx, body)))
2385                    .collect();
2386                (checker_id, bb_envs)
2387            })
2388            .collect()
2389    }
2390}
2391
2392fn marker_at_dominator<'a>(
2393    body: &Body,
2394    markers: &'a IndexVec<BasicBlock, Option<Marker>>,
2395    bb: BasicBlock,
2396) -> &'a Marker {
2397    let dominator = body
2398        .dominators()
2399        .immediate_dominator(bb)
2400        .unwrap_or_else(|| tracked_span_bug!());
2401    markers[dominator]
2402        .as_ref()
2403        .unwrap_or_else(|| tracked_span_bug!())
2404}
2405
2406pub(crate) mod errors {
2407    use flux_errors::{E0999, ErrorGuaranteed};
2408    use flux_infer::infer::InferErr;
2409    use flux_middle::{global_env::GlobalEnv, queries::ErrCtxt};
2410    use rustc_errors::Diagnostic;
2411    use rustc_hir::def_id::LocalDefId;
2412    use rustc_span::Span;
2413
2414    use crate::fluent_generated as fluent;
2415
2416    #[derive(Debug)]
2417    pub struct CheckerError {
2418        kind: InferErr,
2419        span: Span,
2420    }
2421
2422    impl CheckerError {
2423        pub fn emit(self, genv: GlobalEnv, fn_def_id: LocalDefId) -> ErrorGuaranteed {
2424            let dcx = genv.sess().dcx().handle();
2425            match self.kind {
2426                InferErr::UnsolvedEvar(_) => {
2427                    let mut diag =
2428                        dcx.struct_span_err(self.span, fluent::refineck_param_inference_error);
2429                    diag.code(E0999);
2430                    diag.emit()
2431                }
2432                InferErr::Query(err) => {
2433                    let level = rustc_errors::Level::Error;
2434                    err.at(ErrCtxt::FnCheck(self.span, fn_def_id))
2435                        .into_diag(dcx, level)
2436                        .emit()
2437                }
2438            }
2439        }
2440    }
2441
2442    pub trait ResultExt<T> {
2443        fn with_span(self, span: Span) -> Result<T, CheckerError>;
2444    }
2445
2446    impl<T, E> ResultExt<T> for Result<T, E>
2447    where
2448        E: Into<InferErr>,
2449    {
2450        fn with_span(self, span: Span) -> Result<T, CheckerError> {
2451            self.map_err(|err| CheckerError { kind: err.into(), span })
2452        }
2453    }
2454}