Skip to main content

flux_refineck/
checker.rs

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