flux_refineck/
checker.rs

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