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