1use crate::ir::{VerifyExpr, VerifyOp, VerifyType};
8use std::collections::HashMap;
9
10#[derive(Debug, Clone)]
11pub enum TypeError {
12 Conflict {
13 var: String,
14 expected: VerifyType,
15 found: VerifyType,
16 },
17}
18
19impl std::fmt::Display for TypeError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 TypeError::Conflict {
23 var,
24 expected,
25 found,
26 } => {
27 write!(
28 f,
29 "Type conflict for '{}': expected {:?}, found {:?}",
30 var, expected, found
31 )
32 }
33 }
34 }
35}
36
37impl std::error::Error for TypeError {}
38
39pub fn infer_types(expr: &VerifyExpr) -> Result<HashMap<String, VerifyType>, TypeError> {
44 let mut constraints: HashMap<String, VerifyType> = HashMap::new();
45 collect_constraints(expr, &mut constraints)?;
46 Ok(constraints)
47}
48
49fn collect_constraints(
50 expr: &VerifyExpr,
51 constraints: &mut HashMap<String, VerifyType>,
52) -> Result<(), TypeError> {
53 match expr {
54 VerifyExpr::Bool(_) | VerifyExpr::Int(_) => Ok(()),
55
56 VerifyExpr::Var(_) => Ok(()),
57
58 VerifyExpr::Binary { op, left, right } => {
59 match op {
60 VerifyOp::And | VerifyOp::Or | VerifyOp::Implies => {
62 constrain_as_bool(left, constraints)?;
63 constrain_as_bool(right, constraints)?;
64 }
65 VerifyOp::Add
67 | VerifyOp::Sub
68 | VerifyOp::Mul
69 | VerifyOp::Div
70 | VerifyOp::FloorDiv => {
71 constrain_as_int(left, constraints)?;
72 constrain_as_int(right, constraints)?;
73 }
74 VerifyOp::Gt | VerifyOp::Lt | VerifyOp::Gte | VerifyOp::Lte => {
76 constrain_as_int(left, constraints)?;
77 constrain_as_int(right, constraints)?;
78 }
79 VerifyOp::Eq | VerifyOp::Neq => {
81 if expr_suggests_int(left) || expr_suggests_int(right) {
83 constrain_as_int(left, constraints)?;
84 constrain_as_int(right, constraints)?;
85 }
86 }
87 }
88 collect_constraints(left, constraints)?;
89 collect_constraints(right, constraints)?;
90 Ok(())
91 }
92
93 VerifyExpr::Not(inner) => {
94 constrain_as_bool(inner, constraints)?;
95 collect_constraints(inner, constraints)
96 }
97
98 VerifyExpr::Iff(l, r) => {
99 collect_constraints(l, constraints)?;
100 collect_constraints(r, constraints)
101 }
102
103 VerifyExpr::ForAll { body, vars } | VerifyExpr::Exists { body, vars } => {
104 for (name, ty) in vars {
105 add_constraint(name, ty.clone(), constraints)?;
106 }
107 collect_constraints(body, constraints)
108 }
109
110 VerifyExpr::Apply { args, .. } | VerifyExpr::ApplyInt { args, .. } => {
111 for arg in args {
112 collect_constraints(arg, constraints)?;
113 }
114 Ok(())
115 }
116
117 VerifyExpr::BitVecConst { .. } => Ok(()),
119
120 VerifyExpr::BitVecBinary { op: _, left, right } => {
121 let width = bv_width_hint(left).or_else(|| bv_width_hint(right));
122 if let Some(w) = width {
123 constrain_as_bv(left, w, constraints)?;
124 constrain_as_bv(right, w, constraints)?;
125 }
126 collect_constraints(left, constraints)?;
127 collect_constraints(right, constraints)
128 }
129
130 VerifyExpr::BitVecExtract {
131 high,
132 low: _,
133 operand,
134 } => {
135 let min_width = high + 1;
137 constrain_as_bv(operand, min_width, constraints)?;
138 collect_constraints(operand, constraints)
139 }
140
141 VerifyExpr::BitVecConcat(l, r) => {
142 collect_constraints(l, constraints)?;
143 collect_constraints(r, constraints)
144 }
145
146 VerifyExpr::Select { array, index } => {
148 if let VerifyExpr::Var(name) = array.as_ref() {
149 let idx_ty = infer_sort_of(index);
150 let elem_ty = VerifyType::Int; add_constraint(
152 name,
153 VerifyType::Array(Box::new(idx_ty), Box::new(elem_ty)),
154 constraints,
155 )?;
156 }
157 collect_constraints(array, constraints)?;
158 collect_constraints(index, constraints)
159 }
160
161 VerifyExpr::Store {
162 array,
163 index,
164 value,
165 } => {
166 if let VerifyExpr::Var(name) = array.as_ref() {
167 let idx_ty = infer_sort_of(index);
168 let val_ty = infer_sort_of(value);
169 add_constraint(
170 name,
171 VerifyType::Array(Box::new(idx_ty), Box::new(val_ty)),
172 constraints,
173 )?;
174 }
175 collect_constraints(array, constraints)?;
176 collect_constraints(index, constraints)?;
177 collect_constraints(value, constraints)
178 }
179
180 VerifyExpr::AtState { state, expr } => {
181 collect_constraints(state, constraints)?;
182 collect_constraints(expr, constraints)
183 }
184
185 VerifyExpr::Transition { from, to } => {
186 collect_constraints(from, constraints)?;
187 collect_constraints(to, constraints)
188 }
189 }
190}
191
192fn constrain_as_bool(
193 expr: &VerifyExpr,
194 constraints: &mut HashMap<String, VerifyType>,
195) -> Result<(), TypeError> {
196 if let VerifyExpr::Var(name) = expr {
197 add_constraint(name, VerifyType::Bool, constraints)?;
198 }
199 Ok(())
200}
201
202fn constrain_as_int(
203 expr: &VerifyExpr,
204 constraints: &mut HashMap<String, VerifyType>,
205) -> Result<(), TypeError> {
206 if let VerifyExpr::Var(name) = expr {
207 add_constraint(name, VerifyType::Int, constraints)?;
208 }
209 if let VerifyExpr::Binary { left, right, .. } = expr {
211 constrain_as_int(left, constraints)?;
212 constrain_as_int(right, constraints)?;
213 }
214 Ok(())
215}
216
217fn constrain_as_bv(
218 expr: &VerifyExpr,
219 width: u32,
220 constraints: &mut HashMap<String, VerifyType>,
221) -> Result<(), TypeError> {
222 if let VerifyExpr::Var(name) = expr {
223 add_constraint(name, VerifyType::BitVector(width), constraints)?;
224 }
225 Ok(())
226}
227
228fn add_constraint(
229 name: &str,
230 ty: VerifyType,
231 constraints: &mut HashMap<String, VerifyType>,
232) -> Result<(), TypeError> {
233 if let Some(existing) = constraints.get(name) {
234 if !types_compatible(existing, &ty) {
235 return Err(TypeError::Conflict {
236 var: name.to_string(),
237 expected: existing.clone(),
238 found: ty,
239 });
240 }
241 if type_specificity(&ty) > type_specificity(existing) {
243 constraints.insert(name.to_string(), ty);
244 }
245 } else {
246 constraints.insert(name.to_string(), ty);
247 }
248 Ok(())
249}
250
251fn types_compatible(a: &VerifyType, b: &VerifyType) -> bool {
252 match (a, b) {
253 (VerifyType::Int, VerifyType::Int) => true,
254 (VerifyType::Bool, VerifyType::Bool) => true,
255 (VerifyType::Real, VerifyType::Real) => true,
256 (VerifyType::Object, _) | (_, VerifyType::Object) => true,
257 (VerifyType::BitVector(w1), VerifyType::BitVector(w2)) => w1 == w2,
258 (VerifyType::Array(i1, e1), VerifyType::Array(i2, e2)) => {
259 types_compatible(i1, i2) && types_compatible(e1, e2)
260 }
261 _ => false,
262 }
263}
264
265fn type_specificity(ty: &VerifyType) -> u8 {
266 match ty {
267 VerifyType::Object => 0,
268 VerifyType::Bool => 1,
269 VerifyType::Int => 1,
270 VerifyType::Real => 1,
271 VerifyType::BitVector(_) => 2,
272 VerifyType::Array(_, _) => 2,
273 }
274}
275
276fn bv_width_hint(expr: &VerifyExpr) -> Option<u32> {
277 match expr {
278 VerifyExpr::BitVecConst { width, .. } => Some(*width),
279 VerifyExpr::BitVecBinary { left, right, .. } => {
280 bv_width_hint(left).or_else(|| bv_width_hint(right))
281 }
282 VerifyExpr::BitVecExtract { high, low, .. } => Some(high - low + 1),
283 _ => None,
284 }
285}
286
287fn expr_suggests_int(expr: &VerifyExpr) -> bool {
288 matches!(
289 expr,
290 VerifyExpr::Int(_)
291 | VerifyExpr::Binary {
292 op: VerifyOp::Add
293 | VerifyOp::Sub
294 | VerifyOp::Mul
295 | VerifyOp::Div
296 | VerifyOp::FloorDiv,
297 ..
298 }
299 )
300}
301
302fn infer_sort_of(expr: &VerifyExpr) -> VerifyType {
303 match expr {
304 VerifyExpr::Int(_) => VerifyType::Int,
305 VerifyExpr::Bool(_) => VerifyType::Bool,
306 VerifyExpr::BitVecConst { width, .. } => VerifyType::BitVector(*width),
307 VerifyExpr::Binary {
308 op: VerifyOp::Add | VerifyOp::Sub | VerifyOp::Mul | VerifyOp::Div | VerifyOp::FloorDiv,
309 ..
310 } => VerifyType::Int,
311 _ => VerifyType::Int, }
313}