1use rustc_middle::{mir::Local, ty::Ty};
2use z3::ast::{Ast, Bool, Int};
3
4use crate::def_ids::type_ids;
5use crate::{
6 compat::FxHashSet,
7 util::mir_utils,
8 contract::{
9 ContractExpr, ContractKind, ContractPlace, ContractProjection, BinOp, PlaceBase,
10 Property, PropertyArg, PropertyKind,
11 },
12};
13
14use crate::contract::place::{index_access_locals, rebind_property_place, slice_offset_locals};
15use super::state::{
16 AllocId, ElementTy, Provenance, ValueFacts, ValueSource, VmExecutor, VmValue,
17};
18
19impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
20 pub(crate) fn assert_contract_fact(&mut self, property: &Property<'tcx>) {
21 if property.contract_kind() == ContractKind::Postcond {
22 return;
23 }
24 let mut allocs = FxHashSet::default();
28 self.collect_alias_hazard_allocs(property, &mut allocs);
29 self.path_state.alias_hazard_allocs.extend(allocs);
30 match property {
31 Property::Atom(atom) => {
32 if atom.contract_kind == ContractKind::Hazard {
33 return;
34 }
35 self.assert_atom_direct(property);
36 for sub in crate::contract::compound::subsumption_closure(atom) {
37 self.assert_atom_direct(&Property::Atom(sub));
38 }
39 }
40 Property::And(and) => {
41 for conj in &and.conjuncts {
42 self.assert_contract_fact(conj);
43 }
44 }
45 Property::Or(or) => {
46 let is_guard = |d: &Property<'tcx>| matches!(d, Property::Atom(a) if a.kind == PropertyKind::Null || a.kind == PropertyKind::Size);
55 if !or.disjuncts.iter().any(is_guard) {
56 return;
57 }
58 for disj in &or.disjuncts {
59 if is_guard(disj) {
60 continue;
61 }
62 self.assert_contract_fact(disj);
63 }
64 }
65 }
66 }
67
68 fn collect_alias_hazard_allocs(&self, property: &Property<'tcx>, out: &mut FxHashSet<AllocId>) {
69 match property {
70 Property::Atom(atom) => {
71 if atom.kind != PropertyKind::Alias {
72 return;
73 }
74 let Some(ContractExpr::Place(cp)) = atom.args.first().and_then(PropertyArg::expr) else {
75 return;
76 };
77 if let Some(alloc_id) = self.place_root_alloc(cp) {
78 out.insert(alloc_id);
79 }
80 }
81 Property::And(and) => {
82 for conj in &and.conjuncts {
83 self.collect_alias_hazard_allocs(conj, out);
84 }
85 }
86 Property::Or(or) => {
87 for disj in &or.disjuncts {
88 self.collect_alias_hazard_allocs(disj, out);
89 }
90 }
91 }
92 }
93
94 fn place_root_alloc(&self, cp: &ContractPlace) -> Option<AllocId> {
95 let local = cp.base.to_local();
96 let mut field_path: Vec<usize> = Vec::new();
97 for proj in &cp.projections {
98 match proj {
99 ContractProjection::Field { index } => field_path.push(*index),
100 _ => return None,
101 }
102 }
103 let val = if field_path.is_empty() {
104 self.local_value(local).cloned()
105 } else {
106 self.field_value(local, &field_path).cloned()
107 };
108 val.and_then(|v| v.provenance_alloc_id())
109 .map(|id| self.root_alloc(id))
110 }
111
112 fn assert_atom_direct(&mut self, property: &Property<'tcx>) {
115 let Property::Atom(atom) = property else {
116 return;
117 };
118 let kind = atom.kind;
119 match kind {
120 PropertyKind::SliceOffset => {
121 if let Some((dest, base_local, index_local)) = slice_offset_locals(property)
122 && let (Some(base), Some(index)) = (
123 self.local_value(base_local).cloned(),
124 self.local_value(index_local).cloned(),
125 )
126 {
127 let previous = self.local_value(dest).cloned();
128 if self.apply_slice_offset(dest, &base, &index, index_local) {
129 if let (Some(previous), Some(expected)) = (previous, self.local_value(dest))
130 {
131 self.path_state.constraints
132 .assertions
133 .push(previous.z3_term._eq(&expected.z3_term));
134 }
135 let indexed_in_bounds = self.path_state.index_access_facts.iter().any(
136 |(slice, index_term, slice_local, indexed_local)| {
137 *slice_local == base_local
138 && *indexed_local == index_local
139 && *slice == base.z3_term
140 && *index_term == index.z3_term
141 },
142 );
143 if indexed_in_bounds {
144 self.record_bounded_result_span(dest);
145 }
146 } else {
147 self.record_unsupported("SliceOffset index");
148 }
149 }
150 }
151 PropertyKind::NonNull => {
152 if let Some(val) = self.contract_target_value(property) {
153 self.set_non_null_for_value(property, val);
154 }
155 }
156 PropertyKind::Align => {
157 if property.for_each().is_none()
158 && let Some(val) = self.contract_target_value(property)
159 {
160 self.set_align_for_value(property, val);
161 }
162 self.record_for_each_align(property);
163 }
164 PropertyKind::Init => {
165 if let Some(val) = self.contract_target_value(property) {
166 self.set_init_for_value(property, val);
167 }
168 }
169 PropertyKind::Owning => {
170 if property.for_each().is_none()
171 && let Some(val) = self.contract_target_value(property)
172 {
173 self.set_owning_for_value(val);
174 }
175 self.record_for_each_owning(property);
176 }
177 PropertyKind::Alive => {
178 if let Some(id) = self.contract_alloc_id_field_aware(property) {
179 if let Some(PropertyArg::Region(region)) = property.args().get(1) {
183 self.alloc_mut(id).facts.liveness = Some(*region);
184 }
185 }
186 }
187 PropertyKind::InBound => {
188 self.record_index_access_fact(property);
189 if property.for_each().is_none()
190 && let Some(val) = self.contract_target_value(property)
191 {
192 if let (Some(alloc_id), Some(ty)) =
193 (val.provenance_alloc_id(), property.try_type_arg_at(1))
194 && let Some(span) = self.bounded_span(&val, ty)
195 {
196 self.alloc_mut(alloc_id).facts.bounded_spans.push(span);
197 }
198 self.set_in_bounds_for_value(property, val);
199 }
200 if let Some(fe_base) = property.for_each() {
201 self.assert_in_bound_for_each(property, fe_base);
202 } else {
203 self.assert_in_bound_single(property);
204 }
205 if property.try_type_arg_at(1).is_some() && property.for_each().is_none() {
211 self.assert_allocated_fact(property);
212 }
213 }
214 PropertyKind::Allocated => {
215 if property.for_each().is_none() {
216 self.assert_allocated_fact(property);
217 }
218 self.record_for_each_allocated(property);
219 }
220 PropertyKind::Typed => {
221 if let Some(val) = self.contract_target_value(property)
222 && let Some(expected_ty) =
223 property.try_type_arg_at(1).or_else(|| mir_utils::pointee_ty(val.ty))
224 {
225 if let Some(alloc_id) = val.provenance_alloc_id() {
226 if property.for_each().is_none()
227 && property.args().len() <= 2
228 && let Some(prov) = &val.provenance
229 {
230 self.content_mut(alloc_id)
231 .typed_facts
232 .insert((prov.offset.clone(), expected_ty));
233 }
234 if property.for_each().is_some() {
235 self.alloc_mut(alloc_id).facts.for_each.target_ty = Some(expected_ty);
236 }
237 if property.for_each().is_none()
238 && self.alloc(alloc_id).element_ty.is_generic()
239 {
240 self.alloc_mut(alloc_id).element_ty = ElementTy::Typed(expected_ty);
241 }
242 }
243 }
244 }
245 PropertyKind::SplitTransmute => {
246 let src = property.try_type_arg_at(0);
251 let dst = property.try_type_arg_at(1);
252 if let (Some(src), Some(dst)) = (src, dst) {
253 let dst_elem = match dst.kind() {
256 rustc_middle::ty::TyKind::Slice(e) => *e,
257 _ => dst,
258 };
259 let arg_count = self.body().arg_count;
263 for local_idx in 1..=arg_count {
264 let local = Local::from_usize(local_idx);
265 if let Some(val) = self.local_value(local).cloned() {
266 let is_match = match val.ty.kind() {
267 rustc_middle::ty::TyKind::Ref(_, inner, _) => *inner == src,
268 _ => false,
269 };
270 if is_match && let Some(prov) = &val.provenance {
271 self.content_mut(prov.alloc_id).facts.split_transmute_to =
272 Some(dst_elem);
273 }
274 }
275 }
276 }
277 }
278 PropertyKind::ValidCStr => {
279 self.assert_valid_cstr_fact(property);
280 }
281 PropertyKind::ValidString => {
282 let id = self.contract_alloc_id_field_aware(property).or_else(|| {
283 let local = self.contract_target_local(property)?;
286 let val = self.local_value(local)?.clone();
287 let iter_local = self.find_local_by_address(&val.z3_term)?;
288 self.iter_utf8_buffer(iter_local).map(|(id, _)| id)
289 });
290 if let Some(id) = id {
291 self.content_mut(id).facts.initialized = true;
292 self.content_mut(id).facts.utf8_trusted = true;
293 }
294 }
295 PropertyKind::ValidNum => {
296 if let Some(PropertyArg::Predicates(predicates)) = property.args().first() {
297 for pred in predicates {
298 if let Some(condition) = self.eval_predicate_as_bool(pred) {
299 self.path_state.constraints.assertions.push(condition);
300 }
301 }
302 }
303 }
304 _ => {}
305 }
306 }
307
308 pub(crate) fn record_bounded_result_span(&mut self, destination: Local) {
309 if let Some(result) = self.local_value(destination)
310 && let Some(alloc_id) = result.provenance_alloc_id()
311 && let Some(pointee) = mir_utils::pointee_ty(result.ty)
312 && let Some(span) = self.bounded_span(result, pointee)
313 {
314 self.alloc_mut(alloc_id).facts.bounded_spans.push(span);
315 }
316 }
317
318 fn contract_target_local(&self, property: &Property<'tcx>) -> Option<Local> {
320 let cp = property.target_place()?;
321 Some(cp.base.to_local())
322 }
323
324 fn assert_valid_cstr_fact(&mut self, property: &Property<'tcx>) {
325 let id = self.contract_alloc_id_field_aware(property).or_else(|| {
326 let local = self.contract_target_local(property)?;
327 self.local_value(local)?.provenance_alloc_id()
328 });
329 let Some(id) = id else { return };
330 self.alloc_mut(id).facts.dead = false;
331 let region = self.contract_target_local(property).and_then(|local| {
332 let ty = if local.as_usize() > 0 && local.as_usize() <= self.body().arg_count {
333 super::region::fn_arg_ty(
334 self.tcx,
335 self.path_state.current_frame.current_def_id,
336 local.as_usize() - 1,
337 )
338 } else {
339 self.local_value(local).map(|value| value.ty)
340 }?;
341 match ty.kind() {
342 rustc_middle::ty::TyKind::Ref(region, ..) => Some(*region),
343 _ => None,
344 }
345 });
346 if let Some(region) = region
347 && !matches!(region.kind(), rustc_middle::ty::RegionKind::ReErased)
348 {
349 self.alloc_mut(id).facts.liveness = Some(region);
350 }
351 self.content_mut(id).facts.initialized = true;
352 self.content_mut(id).facts.cstr_trusted = true;
353 let one = Int::from_u64(self.z3_ctx, 1);
356 self.path_state.constraints.assertions.push(self.alloc(id).size.ge(&one));
357 if let Some(n) = property.args().get(1).and_then(|a| match a {
358 PropertyArg::Expr(ContractExpr::Const(_)) | PropertyArg::ForEach(ContractExpr::Const(_)) => None,
359 a => self.resolve_contract_count(a),
360 }) {
361 let one = Int::from_u64(self.z3_ctx, 1);
362 self.path_state.constraints.assertions.push(n.ge(&one));
363 self.path_state.constraints.assertions.push(self.alloc(id).size.ge(&n));
364 let zero = Int::from_u64(self.z3_ctx, 0);
365 let terminal = Int::sub(self.z3_ctx, &[&n, &one]);
366 self.byte_write(id, &terminal, &zero);
367 }
368 }
369
370 fn mark_alloc_live_keep(&mut self, val: &VmValue<'z3, 'tcx>, elem_ty: Ty<'tcx>) -> bool {
377 let Some(alloc_id) = val.provenance_alloc_id() else {
378 return false;
379 };
380 self.alloc_mut(alloc_id).facts.dead = false;
381 if self.alloc(alloc_id).is_external() {
382 self.alloc_mut(alloc_id).facts.liveness = Some(self.tcx.lifetimes.re_static);
383 }
384 if self.alloc(alloc_id).element_ty.is_generic() {
385 self.alloc_mut(alloc_id).element_ty = ElementTy::Typed(elem_ty);
386 }
387 true
388 }
389
390 fn materialize_external_alloc(
391 &mut self,
392 elem_ty: Ty<'tcx>,
393 count_term: Option<Int<'z3>>,
394 val_ty: Ty<'tcx>,
395 huge: bool,
396 ) -> VmValue<'z3, 'tcx> {
397 let elem_sz_raw = self.size_of_ty(elem_ty);
398 let heap_align = self.align_sym(elem_ty);
399 let heap_align_n = Self::non_trivial_align(heap_align.clone());
400 let (heap_id, heap_base) = if huge || elem_sz_raw == 0 {
401 let max_size = Int::from_u64(self.z3_ctx, i64::MAX as u64);
405 self.allocate_external(max_size, heap_align.clone(), Some(elem_ty))
406 } else {
407 let elem_sz = Int::from_u64(self.z3_ctx, elem_sz_raw);
408 let count = count_term.unwrap_or_else(|| Int::from_u64(self.z3_ctx, 1));
409 let total = Int::mul(self.z3_ctx, &[&count, &elem_sz]);
410 self.allocate_external(total, heap_align, Some(elem_ty))
411 };
412 self.content_mut(heap_id).facts.initialized = true;
413 VmValue {
414 z3_term: heap_base,
415 ty: val_ty,
416 provenance: Some(Provenance {
417 alloc_id: heap_id,
418 offset: Int::from_u64(self.z3_ctx, 0),
419 offset_kind: None,
420 }),
421 facts: ValueFacts {
422 non_null: true,
423 dangling: false,
424 init: true,
425 in_bounds: true,
426 align_n: heap_align_n,
427 ownership_transfer: None,
428 },
429 source: ValueSource::None,
430 }
431 }
432
433 fn assert_allocated_fact(&mut self, property: &Property<'tcx>) {
443 self.materialize_allocated_fact(property);
444 let Some(value) = self.contract_target_value(property) else {
445 return;
446 };
447 let (Some(alloc_id), Some(elem_ty)) = (value.provenance_alloc_id(), property.try_type_arg_at(1))
448 else {
449 return;
450 };
451 let count = match property.args().get(2) {
452 Some(arg) => match self.resolve_contract_count(arg) {
453 Some(count) => count,
454 None => return,
455 },
456 None => Int::from_u64(self.z3_ctx, 1),
457 };
458 let bytes = Int::mul(self.z3_ctx, &[&count, &self.size_sym(elem_ty)]);
461 let range = (value.z3_term, bytes);
462 let ranges = &mut self.alloc_mut(alloc_id).facts.bounded_ranges;
463 if !ranges.contains(&range) {
464 ranges.push(range);
465 }
466 }
467
468 fn materialize_allocated_fact(&mut self, property: &Property<'tcx>) {
469 let elem_ty = property.try_type_arg_at(1);
470 let count_term = property
471 .args()
472 .get(2)
473 .and_then(|a| self.resolve_contract_count(a));
474 let Some(elem_ty) = elem_ty else { return };
475
476 let has_nonfield = property
477 .target_place()
478 .map(|cp| {
479 cp.projections.iter().any(|p| {
480 !matches!(p, crate::contract::ContractProjection::Field { .. })
481 })
482 })
483 .unwrap_or(false);
484
485 if has_nonfield {
486 let Some(local) = self.contract_target_local(property) else {
487 return;
488 };
489 let Some(val) = self.local_value(local).cloned() else {
490 return;
491 };
492 if let Some(alloc_id) = val.provenance_alloc_id() {
493 self.alloc_mut(alloc_id).facts.dead = false;
494 }
495 let v = self.materialize_external_alloc(elem_ty, count_term, val.ty, false);
496 self.set_local(local, v);
497 } else {
498 let Some((local, field_path)) = self.contract_field_path(property) else {
499 return;
500 };
501 if field_path.is_empty() {
502 let Some(val) = self.local_value(local).cloned() else {
503 return;
504 };
505 if self.mark_alloc_live_keep(&val, elem_ty) {
506 return;
507 }
508 let v = self.materialize_external_alloc(elem_ty, count_term, val.ty, false);
509 self.set_local(local, v);
510 } else {
511 let is_direct_simple_ptr = self
519 .field_value(local, &field_path)
520 .map(|val| {
521 (matches!(val.ty.kind(), rustc_middle::ty::TyKind::RawPtr(..))
522 || matches!(val.ty.kind(), rustc_middle::ty::TyKind::Adt(adt, _)
523 if type_ids::is_std_nonnull(adt.did())
524 || mir_utils::is_raw_ptr_wrapper(self.tcx, adt.did())))
525 && (elem_ty.is_primitive()
526 || matches!(elem_ty.kind(), rustc_middle::ty::TyKind::Param(_)))
527 })
528 .unwrap_or(false);
529 let Some(val) = self.field_value(local, &field_path).cloned() else {
530 return;
531 };
532 if let rustc_middle::ty::TyKind::Adt(adt, _) =
533 self.body().local_decls[local].ty.kind()
534 && (type_ids::is_std_vec(adt.did())
535 || type_ids::is_std_string(adt.did()))
536 && val.provenance_alloc_id().is_some_and(|id| {
537 self.alloc(id).slice_len().is_some()
538 && self.alloc(id).element_ty.as_ty() == Some(elem_ty)
539 })
540 {
541 return;
542 }
543 if let Some(alloc_id) = val.provenance_alloc_id() {
544 self.alloc_mut(alloc_id).facts.dead = false;
545 if self.alloc(alloc_id).size.as_u64().is_some() {
546 return;
547 }
548 }
549 let mut v = self.materialize_external_alloc(
554 elem_ty,
555 count_term,
556 val.ty,
557 is_direct_simple_ptr,
558 );
559 if v.facts.align_n.is_none() {
564 v.facts.align_n = val.facts.align_n.clone();
565 }
566 self.set_field_value(local, field_path, v);
567 }
568 }
569 }
570
571 fn contract_field_path(&self, property: &Property<'tcx>) -> Option<(Local, Vec<usize>)> {
575 let cp = property.target_place()?;
576 let local = cp.base.to_local();
577 let mut path = Vec::new();
578 for proj in &cp.projections {
579 match proj {
580 crate::contract::ContractProjection::Field { index } => {
581 path.push(*index);
582 }
583 _ => break,
584 }
585 }
586 Some((local, path))
587 }
588
589 fn contract_target_value(&self, property: &Property<'tcx>) -> Option<VmValue<'z3, 'tcx>> {
593 let place = property.target_place()?;
594 self.bound_contract_place_value(place)
595 }
596
597 fn set_contract_target_value(&mut self, property: &Property<'tcx>, val: VmValue<'z3, 'tcx>) {
599 if let Some((local, path)) = self.contract_field_path(property) {
600 if path.is_empty() {
601 self.set_local(local, val);
602 } else {
603 self.set_field_value(local, path, val);
604 }
605 }
606 }
607
608 fn contract_alloc_id_field_aware(&self, property: &Property<'tcx>) -> Option<AllocId> {
611 let cp = match property.args().first()?.expr()? {
612 ContractExpr::Place(cp) => cp,
613 _ => return None,
614 };
615 cp.plain_field_path()?;
616 self.bound_contract_place_value(cp)?
617 .provenance_alloc_id()
618 }
619
620 fn resolve_contract_count(&self, arg: &PropertyArg<'tcx>) -> Option<Int<'z3>> {
623 match arg {
624 PropertyArg::Expr(expr) | PropertyArg::ForEach(expr) => self.eval_contract_expr_simple(expr),
625 _ => None,
626 }
627 }
628
629 fn eval_predicate_as_bool(
631 &self,
632 pred: &crate::contract::NumericPredicate<'tcx>,
633 ) -> Option<Bool<'z3>> {
634 let lhs = self.eval_contract_expr_simple(&pred.lhs)?;
635 let rhs = self.eval_contract_expr_simple(&pred.rhs)?;
636 Some(self.contract_relop_bool(pred.op, &lhs, &rhs))
637 }
638
639 fn eval_numeric_binary(
640 &self,
641 left: &Int<'z3>,
642 right: &Int<'z3>,
643 op: crate::contract::BinOp,
644 ) -> Option<Int<'z3>> {
645 match op {
646 BinOp::Div => Some(left.div(right)),
647 BinOp::Rem => Some(left.rem(right)),
648 _ => self.contract_binary_term(op, left, right),
649 }
650 }
651
652 fn set_non_null_for_value(&mut self, property: &Property<'tcx>, mut val: VmValue<'z3, 'tcx>) {
654 val.facts.non_null = true;
655 self.set_contract_target_value(property, val);
656 }
657
658 fn set_in_bounds_for_value(&mut self, property: &Property<'tcx>, mut val: VmValue<'z3, 'tcx>) {
659 val.facts.in_bounds = true;
660 self.set_contract_target_value(property, val);
661 }
662
663 fn assert_in_bound_for_each(
664 &mut self,
665 property: &Property<'tcx>,
666 fe_base: &PlaceBase,
667 ) {
668 if matches!(fe_base, PlaceBase::Return) {
669 return;
670 }
671 let fe_local = fe_base.to_local();
672 let fe_val = match self.local_value(fe_local).cloned() {
673 Some(v) => v,
674 None => return,
675 };
676 let fe_alloc_id = match fe_val.provenance_alloc_id() {
677 Some(id) => id,
678 None => return,
679 };
680 let byte_vals: Vec<(usize, Int<'z3>)> = self.alloc_byte_values(fe_alloc_id);
681 if byte_vals.is_empty() {
682 return;
683 }
684 let slice_local = match property.args().first().and_then(PropertyArg::expr) {
685 Some(ContractExpr::IndexAccess { slice, .. }) => {
686 match slice.as_ref() {
687 ContractExpr::Place(cp) if !matches!(cp.base, PlaceBase::Return) => Some(cp.base.to_local()),
688 _ => None,
689 }
690 }
691 Some(ContractExpr::Place(cp)) if !matches!(cp.base, PlaceBase::Return) => Some(cp.base.to_local()),
692 _ => None,
693 };
694 let slice_val = slice_local.and_then(|loc| self.local_value(loc));
695 let slice_alloc_id = slice_val.and_then(|sl_val| sl_val.provenance_alloc_id());
696 let data_size = slice_alloc_id.map(|da_id| self.alloc(da_id).size.clone());
697 let elem_sz = slice_alloc_id
698 .and_then(|da_id| self.alloc(da_id).element_ty.as_ty())
699 .map(|ty| self.size_of_ty(ty))
700 .unwrap_or(1)
701 .max(1);
702 let Some(data_size) = data_size else { return };
703 let elem_sz_term = Int::from_u64(self.z3_ctx, elem_sz);
704 let len = slice_val
705 .and_then(|sl_val| self.slice_len_from_value(sl_val))
706 .unwrap_or_else(|| data_size.div(&elem_sz_term));
707 let zero = Int::from_u64(self.z3_ctx, 0);
708 for (_, term) in &byte_vals {
709 self.path_state.constraints.assertions.push(term.ge(&zero));
710 self.path_state.constraints.assertions.push(term.lt(&len));
711 }
712 }
713
714 fn assert_in_bound_single(&mut self, property: &Property<'tcx>) {
720 let Some(ContractExpr::IndexAccess { slice, index }) = property.args().first().and_then(PropertyArg::expr)
721 else {
722 return;
723 };
724 let ContractExpr::Place(index_place) = index.as_ref() else {
725 return;
726 };
727 let index_local = index_place.base.to_local();
728 if !matches!(
729 self.body().local_decls[index_local].ty.kind(),
730 rustc_middle::ty::TyKind::Uint(rustc_middle::ty::UintTy::Usize)
731 ) {
732 return;
733 }
734 let slice_local = match slice.as_ref() {
735 ContractExpr::Place(cp) if !matches!(cp.base, PlaceBase::Return) => Some(cp.base.to_local()),
736 _ => None,
737 };
738 let Some(slice_local) = slice_local else {
739 return;
740 };
741 let Some(da_id) = self
742 .local_value(slice_local)
743 .and_then(|v| v.provenance_alloc_id())
744 else {
745 return;
746 };
747 let len = self
748 .slice_len_of_alloc(da_id)
749 .unwrap_or_else(|| self.alloc(da_id).size.clone());
750 let Some(index_term) = self.eval_contract_expr_simple(index) else {
751 return;
752 };
753 self.path_state.constraints.assertions.push(index_term.lt(&len));
754 }
755
756 fn record_index_access_fact(&mut self, property: &Property<'tcx>) {
757 let Some((slice_local, index_local)) = index_access_locals(property) else {
758 return;
759 };
760 if let (Some(slice), Some(index)) =
761 (self.local_value(slice_local), self.local_value(index_local))
762 {
763 self.path_state.index_access_facts.push((
764 slice.z3_term.clone(),
765 index.z3_term.clone(),
766 slice_local,
767 index_local,
768 ));
769 }
770 }
771
772 pub(crate) fn assert_pointee_struct_invariants(
777 &mut self,
778 dest_ty: Ty<'tcx>,
779 dest_local: Local,
780 ) {
781 let pointee = match dest_ty.kind() {
782 rustc_middle::ty::TyKind::Ref(_, inner, _) => *inner,
783 _ => return,
784 };
785 let adt_def = match pointee.kind() {
786 rustc_middle::ty::TyKind::Adt(adt_def, _) => *adt_def,
787 _ => return,
788 };
789 let invariants = crate::contract::annotation::get_struct_invariants_from_annotation(
790 self.tcx,
791 adt_def.did(),
792 adt_def.did(),
793 );
794 for inv in &invariants {
795 let mut rebound = inv.clone();
796 rebind_property_place(&mut rebound, dest_local);
797 self.assert_contract_fact(&rebound);
798 }
799 }
800
801 pub(crate) fn assert_alloc_pointee_invariants(
809 &mut self,
810 alloc_id: AllocId,
811 pointee_ty: Ty<'tcx>,
812 ) {
813 let rustc_middle::ty::TyKind::Adt(adt_def, _) = pointee_ty.kind() else {
814 return;
815 };
816 let invariants = crate::contract::annotation::get_struct_invariants_from_annotation(
817 self.tcx,
818 adt_def.did(),
819 adt_def.did(),
820 );
821 for inv in &invariants {
822 let Property::Atom(atom) = inv else {
823 continue;
824 };
825 if atom.kind != PropertyKind::ValidNum {
826 continue;
827 }
828 let Some(PropertyArg::Predicates(preds)) = atom.args.first() else {
829 continue;
830 };
831 for pred in preds {
832 if let Some(cond) = self.eval_pointee_predicate_as_bool(alloc_id, pointee_ty, pred)
833 {
834 self.path_state.constraints.assertions.push(cond);
835 }
836 }
837 }
838 }
839
840 fn eval_pointee_predicate_as_bool(
844 &self,
845 alloc_id: AllocId,
846 view_ty: Ty<'tcx>,
847 pred: &crate::contract::NumericPredicate<'tcx>,
848 ) -> Option<Bool<'z3>> {
849 let lhs = self.eval_pointee_expr(alloc_id, view_ty, &pred.lhs)?;
850 let rhs = self.eval_pointee_expr(alloc_id, view_ty, &pred.rhs)?;
851 Some(self.contract_relop_bool(pred.op, &lhs, &rhs))
852 }
853
854 fn eval_pointee_expr(
856 &self,
857 alloc_id: AllocId,
858 view_ty: Ty<'tcx>,
859 expr: &ContractExpr<'tcx>,
860 ) -> Option<Int<'z3>> {
861 match expr {
862 ContractExpr::Const(v) => Some(Int::from_u64(self.z3_ctx, *v as u64)),
863 ContractExpr::SizeOf(ty) => Some(self.size_sym_read(*ty)),
864 ContractExpr::AlignOf(ty) => Some(self.align_sym_read(*ty)),
865 ContractExpr::Place(cp) => {
866 let path = cp.plain_field_path()?;
867 self.path_state.mem_units[alloc_id.0]
868 .content
869 .values
870 .get(&(view_ty, path))
871 .map(|v| v.z3_term.clone())
872 }
873 ContractExpr::Binary { op, lhs, rhs } => {
874 let l = self.eval_pointee_expr(alloc_id, view_ty, lhs)?;
875 let r = self.eval_pointee_expr(alloc_id, view_ty, rhs)?;
876 self.eval_numeric_binary(&l, &r, *op)
877 }
878 ContractExpr::Len(inner, _) => {
879 let val = self.eval_pointee_expr_value(alloc_id, view_ty, inner)?;
880 self.slice_len_from_value(&val)
881 }
882 _ => None,
883 }
884 }
885
886 fn eval_pointee_expr_value(
889 &self,
890 alloc_id: AllocId,
891 view_ty: Ty<'tcx>,
892 expr: &ContractExpr<'tcx>,
893 ) -> Option<VmValue<'z3, 'tcx>> {
894 let ContractExpr::Place(cp) = expr else {
895 return None;
896 };
897 let path = cp.plain_field_path()?;
898 self.path_state.mem_units[alloc_id.0]
899 .content
900 .values
901 .get(&(view_ty, path))
902 .cloned()
903 }
904
905 fn set_align_for_value(&mut self, property: &Property<'tcx>, mut val: VmValue<'z3, 'tcx>) {
907 if let Some(PropertyArg::Ty(ty)) = property.args().get(1) {
908 let align = self.align_sym(*ty);
909 let align_u64 = align.simplify().as_u64();
910 if align_u64 != Some(1) {
911 val.facts.align_n = Some(align.clone());
912 if align_u64.is_some() {
921 self.path_state.constraints
922 .assertions
923 .push(val.z3_term.rem(&align)._eq(&Int::from_u64(self.z3_ctx, 0)));
924 }
925 }
926 }
927 self.set_contract_target_value(property, val);
928 }
929
930 fn set_init_for_value(&mut self, property: &Property<'tcx>, val: VmValue<'z3, 'tcx>) {
932 let is_maybe_uninit = property
936 .try_type_arg_at(1)
937 .map(crate::def_ids::strips_to_maybe_uninit)
938 .unwrap_or(false);
939 if is_maybe_uninit {
940 return;
941 }
942 if let Some(prov) = &val.provenance {
943 self.content_mut(prov.alloc_id).facts.initialized = true;
944 }
945 if let Some((local, path)) = self.contract_field_path(property) {
946 let existing = if path.is_empty() {
947 self.local_value(local).cloned()
948 } else {
949 self.field_value(local, &path).cloned()
950 };
951 if let Some(mut existing) = existing {
952 self.mark_initialized(&mut existing);
953 if path.is_empty() {
954 self.set_local(local, existing);
955 } else {
956 self.set_field_value(local, path, existing);
957 }
958 }
959 }
960 }
961
962 fn set_owning_for_value(&mut self, val: VmValue<'z3, 'tcx>) {
964 if let Some(prov) = &val.provenance {
965 self.alloc_mut(prov.alloc_id).facts.owning = Some(val.z3_term.clone());
966 self.content_mut(prov.alloc_id).facts.initialized = true;
967 }
968 }
969
970 fn for_each_target_alloc(&self, property: &Property<'tcx>) -> Option<AllocId> {
971 property.for_each()?;
972 self.contract_target_value(property)?.provenance_alloc_id()
973 }
974
975 fn record_for_each_align(&mut self, property: &Property<'tcx>) {
979 let Some(ty) = property.try_type_arg_at(1) else {
980 return;
981 };
982 let Some(alloc_id) = self.for_each_target_alloc(property) else {
983 return;
984 };
985 self.alloc_mut(alloc_id).facts.for_each.aligned_ty = Some(ty);
986 }
987
988 fn record_for_each_allocated(&mut self, property: &Property<'tcx>) {
991 let Some(ty) = property.try_type_arg_at(1) else {
992 return;
993 };
994 let count = property
995 .args()
996 .get(2)
997 .and_then(|a| self.resolve_contract_count(a))
998 .unwrap_or_else(|| Int::from_u64(self.z3_ctx, 1));
999 let Some(alloc_id) = self.for_each_target_alloc(property) else {
1000 return;
1001 };
1002 self.alloc_mut(alloc_id).facts.for_each.allocated = Some((ty, count));
1003 }
1004
1005 fn record_for_each_owning(&mut self, property: &Property<'tcx>) {
1009 let Some(alloc_id) = self.for_each_target_alloc(property) else {
1010 return;
1011 };
1012 self.alloc_mut(alloc_id).facts.for_each.owning = true;
1013 }
1014}