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