1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use std::collections::HashMap;
use std::ops::{Add, Div, Mul, Sub};
use syn::{BinOp, Expr, ExprBinary, ExprLit, ExprMacro, ExprParen, ExprPath, ExprUnary};
use z3::ast::Ast;
use z3::{ast, Context};
// Enum to represent different Z3 variable types
// (just using Int and bool for now)
#[derive(Clone, Debug)]
pub enum Z3Var<'ctx> {
Int(ast::Int<'ctx>),
Bool(ast::Bool<'ctx>),
Real(ast::Real<'ctx>),
BV(ast::BV<'ctx>),
Float(ast::Float<'ctx>),
Array(ast::Array<'ctx>),
String(ast::String<'ctx>),
Set(ast::Set<'ctx>),
Datatype(ast::Datatype<'ctx>),
Dynamic(ast::Dynamic<'ctx>),
}
#[derive(Debug, Clone)]
struct ImplicationPlaceholder<'a> {
chain: Vec<ast::Bool<'a>>, // Store translated Z3 Bool expressions
}
impl<'a> ImplicationPlaceholder<'a> {
fn new() -> Self {
Self { chain: Vec::new() }
}
fn add_argument(&mut self, arg: ast::Bool<'a>) {
self.chain.push(arg);
}
/// Converts the chain into nested Z3 implications
fn to_z3_implies(self, _ctx: &'a Context) -> ast::Bool<'a> {
self.chain
.into_iter()
.rev()
.reduce(|acc, expr| ast::Bool::implies(&expr, &acc))
.expect("ImplicationPlaceholder must have at least one argument")
}
}
// Main function to generate Z3 condition and variables HashMap
pub fn generate_condition_and_vars<'a>(
ctx: &'a Context,
expr: &Expr,
) -> (ast::Bool<'a>, HashMap<String, Z3Var<'a>>) {
let mut vars = HashMap::new();
//println!("Whole SYN AST: {:?}", expr);
let z3_condition_var = generate_z3_ast(ctx, expr, &mut vars);
// Ensure the condition is returned as a Bool, converting if necessary
let z3_condition = match z3_condition_var {
Z3Var::Bool(b) => b,
_ => panic!("Expected Bool condition, found different type"),
};
// Post-process the AST to handle implication placeholders
let z3_condition = post_process_implications(&z3_condition, ctx);
/*println!("Variables in the condition:");
for (name, var) in &vars {
match var {
Z3Var::Int(int_var) => println!("{} = Int({})", name, int_var.to_string()),
Z3Var::Bool(bool_var) => println!("{} = Bool({})", name, bool_var.to_string()),
Z3Var::Real(real_var) => println!("{} = Real({})", name, real_var.to_string()),
Z3Var::BV(bv_var) => println!("{} = BV({})", name, bv_var.to_string()),
Z3Var::Float(float_var) => println!("{} = Float({})", name, float_var.to_string()),
Z3Var::Array(array_var) => println!("{} = Array({})", name, array_var.to_string()),
Z3Var::String(string_var) => println!("{} = String({})", name, string_var.to_string()),
Z3Var::Set(set_var) => println!("{} = Set({})", name, set_var.to_string()),
Z3Var::Datatype(datatype_var) => println!("{} = Datatype({})", name, datatype_var.to_string()),
Z3Var::Dynamic(dynamic_var) => println!("{} = Dynamic({})", name, dynamic_var.to_string()),
}
}*/
println!();
println!("Generated Z3 Condition:\n{}\n", z3_condition.to_string());
(z3_condition, vars)
}
fn generate_z3_ast<'a>(
ctx: &'a Context,
expr: &Expr,
vars: &mut HashMap<String, Z3Var<'a>>,
) -> Z3Var<'a> {
match expr {
Expr::Macro(ExprMacro { mac, .. }) => {
let macro_name = mac
.path
.segments
.last()
.expect("Expected macro name")
.ident
.to_string();
if ["invariant", "pre", "post"].contains(¯o_name.as_str()) {
if let Ok(arg_expr) = syn::parse2::<Expr>(mac.tokens.clone()) {
return generate_z3_ast(ctx, &arg_expr, vars);
} else {
panic!("Failed to parse macro argument expression");
}
} else {
panic!("Unsupported macro: {}", macro_name);
}
}
Expr::Lit(ExprLit { lit, .. }) => match lit {
syn::Lit::Int(lit_int) => {
let int_value = lit_int
.base10_parse::<i64>()
.expect("Expected integer literal");
Z3Var::Int(ast::Int::from_i64(ctx, int_value))
}
syn::Lit::Bool(lit_bool) => Z3Var::Bool(ast::Bool::from_bool(ctx, lit_bool.value)),
_ => panic!("Unsupported literal type"),
},
Expr::Paren(ExprParen { expr, .. }) => generate_z3_ast(ctx, expr, vars),
Expr::Path(ExprPath { path, .. }) => {
if let Some(ident) = path.get_ident() {
let var_name = ident.to_string();
get_or_create_var(ctx, &var_name, vars)
} else {
panic!("Unsupported path expression");
}
}
Expr::Unary(ExprUnary { op, expr, .. }) => match op {
syn::UnOp::Not(_) => {
let inner_ast = generate_z3_ast(ctx, expr, vars);
match inner_ast {
Z3Var::Bool(inner_bool) => Z3Var::Bool(inner_bool.not()),
_ => panic!("Expected Bool type for Not operation"),
}
}
_ => panic!("Unsupported unary operator: {:?}", op),
},
Expr::Binary(ExprBinary {
left, op, right, ..
}) => {
let left_ast = generate_z3_ast(ctx, left, vars);
let right_ast = generate_z3_ast(ctx, right, vars);
match op {
BinOp::And(_) => {
if let (Z3Var::Bool(left_bool), Z3Var::Bool(right_bool)) = (left_ast, right_ast)
{
Z3Var::Bool(ast::Bool::and(ctx, &[&left_bool, &right_bool]))
} else {
panic!("Expected Bool types for And operation");
}
}
BinOp::Or(_) => {
if let (Z3Var::Bool(left_bool), Z3Var::Bool(right_bool)) = (left_ast, right_ast)
{
Z3Var::Bool(ast::Bool::or(ctx, &[&left_bool, &right_bool]))
} else {
panic!("Expected Bool types for Or operation");
}
}
BinOp::Eq(_) => match (left_ast, right_ast) {
(Z3Var::Int(left_int), Z3Var::Int(right_int)) => {
Z3Var::Bool(left_int._eq(&right_int))
}
(Z3Var::Bool(left_bool), Z3Var::Bool(right_bool)) => {
Z3Var::Bool(left_bool._eq(&right_bool))
}
_ => panic!("Unsupported types for Eq operation"),
},
BinOp::Le(_) => {
match (left_ast, right_ast) {
(Z3Var::Int(left_int), Z3Var::Int(right_int)) => {
// println!("Attempting Le operation: left = {:?}, right = {:?}", left_int, right_int);
Z3Var::Bool(left_int.le(&right_int))
}
(left, right) => {
println!(
"Expected Int types for Le operation, found incompatible types: left = {:?}, right = {:?}",
left, right
);
panic!("Comparison operations require Int types only.");
}
}
}
BinOp::Ge(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Bool(left_int.ge(&right_int))
} else {
panic!("Expected Int types for Ge operation");
}
}
BinOp::Lt(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Bool(left_int.lt(&right_int))
} else {
panic!("Expected Int types for Lt operation");
}
}
BinOp::Gt(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Bool(left_int.gt(&right_int))
} else {
panic!("Expected Int types for Gt operation");
}
}
BinOp::Add(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Int(left_int.add(&right_int))
} else {
panic!("Expected Int types for Add operation");
}
}
BinOp::Sub(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Int(left_int.sub(&right_int))
} else {
panic!("Expected Int types for Sub operation");
}
}
BinOp::Mul(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Int(left_int.mul(&right_int))
} else {
panic!("Expected Int types for Mul operation");
}
}
BinOp::Div(_) => {
if let (Z3Var::Int(left_int), Z3Var::Int(right_int)) = (left_ast, right_ast) {
Z3Var::Int(left_int.div(&right_int))
} else {
panic!("Expected Int types for Div operation");
}
}
BinOp::Shr(_) => {
// println!("Detected '>>' operation in Syn AST:");
// println!("Left: {:?}", left);
// println!("Right: {:?}", right);
let mut placeholder = ImplicationPlaceholder::new();
// Helper function to traverse and extract chained implications
fn extract_chain<'a>(
ctx: &'a Context,
expr: &Expr,
vars: &mut HashMap<String, Z3Var<'a>>,
placeholder: &mut ImplicationPlaceholder<'a>,
) {
if let Expr::Binary(ExprBinary {
left, op, right, ..
}) = expr
{
if matches!(op, BinOp::Shr(_)) {
// If the left side is also a '>>', traverse it recursively
extract_chain(ctx, left, vars, placeholder);
// Process the right side and add it to the placeholder
if let Z3Var::Bool(right_bool) = generate_z3_ast(ctx, right, vars) {
placeholder.add_argument(right_bool);
} else {
panic!("Expected Bool type for right operand of '>>'");
}
return;
}
}
// If it's not a chain, process it as a standalone expression
if let Z3Var::Bool(expr_bool) = generate_z3_ast(ctx, expr, vars) {
placeholder.add_argument(expr_bool);
} else {
panic!("Expected Bool type for chain element");
}
}
// Extract the left side chain
extract_chain(ctx, left, vars, &mut placeholder);
// Process the right side of the current '>>' operation
if let Z3Var::Bool(right_bool) = generate_z3_ast(ctx, right, vars) {
placeholder.add_argument(right_bool);
} else {
println!("Left operand: {:?}", left);
panic!(
"Expected Bool type for right operand of top-level '>>': {:?}",
right
);
}
// Return the placeholder as a 'Z3Var::Bool'
Z3Var::Bool(placeholder.to_z3_implies(ctx))
}
_ => panic!("Unsupported binary operator: {:?}", op),
}
}
other => {
println!(
"Encountered unsupported logical expression type: {:?}",
other
);
panic!("Unsupported logical expression");
}
}
}
fn post_process_implications<'a>(expr: &ast::Bool<'a>, ctx: &'a Context) -> ast::Bool<'a> {
if let Some(placeholder) = extract_implication_placeholder(expr) {
// Print the chain for debugging
/*println!("Implication chain detected:");
for (i, implication) in placeholder.chain.iter().enumerate() {
println!(" [{}]: {}", i, implication.to_string());
}*/
// Convert the placeholder to nested implications
return placeholder.to_z3_implies(ctx);
}
// Recursively process left and right if this is an implication
if expr.decl().kind() == z3::DeclKind::IMPLIES {
let args = expr.children();
if args.len() == 2 {
let left = post_process_implications(
&args[0].clone().try_into().expect("Expected Bool type"),
ctx,
);
let right = post_process_implications(
&args[1].clone().try_into().expect("Expected Bool type"),
ctx,
);
println!(
"Processing implication: {} => {}",
left.to_string(),
right.to_string()
);
return ast::Bool::implies(&left, &right);
}
}
println!("Non-implication or terminal node: {}", expr.to_string());
expr.clone() // Return the original expression if no placeholder or processing needed
}
fn extract_implication_placeholder<'a>(expr: &ast::Bool<'a>) -> Option<ImplicationPlaceholder<'a>> {
if expr.decl().kind() == z3::DeclKind::IMPLIES {
let args = expr.children();
let mut placeholder = ImplicationPlaceholder::new();
if let Some(left_dynamic) = args.get(0) {
let left = left_dynamic.clone().try_into().ok()?;
placeholder.add_argument(left);
}
if let Some(right_dynamic) = args.get(1) {
let right = right_dynamic.clone().try_into().ok()?;
placeholder.add_argument(right);
}
return Some(placeholder);
}
None
}
// Helper function to create or retrieve Z3 variables
fn get_or_create_var<'a>(
ctx: &'a Context,
name: &str,
vars: &mut HashMap<String, Z3Var<'a>>,
) -> Z3Var<'a> {
vars.entry(name.to_string())
.or_insert_with(|| Z3Var::Int(ast::Int::new_const(ctx, name)))
.clone()
}