patronus 0.37.0

Hardware bug-finding toolkit.
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright 2024 Cornell University
// released under BSD 3-Clause License
// author: Kevin Laeufer <laeufer@cornell.edu>

use crate::expr::{Context, ExprRef, TypeCheck, WidthInt};
use baa::BitVecValue;
use regex::{Captures, Match, Regex, RegexSet};
use rustc_hash::FxHashMap;

pub fn parse_expr(ctx: &mut Context, inp: &str) -> ExprRef {
    let mut parser = Parser::new(ctx, inp);
    let expr = parser.parse_expr_all();
    expr.type_check(ctx)
        .unwrap_or_else(|_| panic!("{inp} failed to type-check"));
    expr
}

struct Parser<'a> {
    ctx: &'a mut Context,
    inp: &'a str,
    symbols: FxHashMap<String, ExprRef>,
}

#[derive(Debug, Copy, Clone)]
enum Arg {
    E(ExprRef),
    C(WidthInt),
}

#[derive(Debug, Copy, Clone)]
enum ArgTpe {
    E,
    C,
}

impl<'a> Parser<'a> {
    fn new(ctx: &'a mut Context, inp: &'a str) -> Self {
        let inp = inp.trim();
        let symbols = FxHashMap::default();
        Self { ctx, inp, symbols }
    }

    fn parse_expr_all(&mut self) -> ExprRef {
        let e = self.parse_expr();
        assert!(self.inp.is_empty(), "could not pars: {}", self.inp);
        e
    }

    fn parse_expr(&mut self) -> ExprRef {
        let mut e = self
            .try_parse_fun()
            .or_else(|| self.try_pars_bv_lit())
            .or_else(|| self.try_parse_symbol())
            .unwrap_or_else(|| panic!("failed to parse: {}", self.inp));

        while let Some(c) = SLICE_REGEX.captures(self.inp) {
            if let Some(bit) = c.get(2) {
                let bit = Self::width_int(bit);
                self.consume_c(&c);
                e = self.ctx.slice(e, bit, bit);
            } else if let (Some(msb), Some(lsb)) = (c.get(4), c.get(5)) {
                let msb = Self::width_int(msb);
                let lsb = Self::width_int(lsb);
                self.consume_c(&c);
                e = self.ctx.slice(e, msb, lsb);
            } else {
                unreachable!("unexpected slice! @ {}", self.inp)
            }
        }
        e
    }

    fn width_int(m: Match) -> WidthInt {
        m.as_str().parse().unwrap()
    }

    fn try_parse_fun(&mut self) -> Option<ExprRef> {
        let fun = ANY_FUNCTION_REGEX.matches(self.inp);
        if let Some(fun_id) = fun.into_iter().next() {
            self.consume_r(&FUNCTION_REGEX[fun_id]);
            let args = self.parse_args(fun_id);
            Some(self.make_fun(fun_id, args))
        } else {
            None
        }
    }

    fn try_pars_bv_lit(&mut self) -> Option<ExprRef> {
        if let Some(m) = BIN_LIT_REGEX.captures(self.inp) {
            let width: WidthInt = m.get(1).unwrap().as_str().parse().unwrap();
            let value_str = m.get(2).unwrap().as_str();
            let value = BitVecValue::from_str_radix(value_str, 2, width).unwrap();
            self.consume_c(&m);
            Some(self.ctx.bv_lit(&value))
        } else if let Some(m) = DEC_LIT_REGEX.captures(self.inp) {
            let width: WidthInt = m.get(1).unwrap().as_str().parse().unwrap();
            let value_str = m.get(2).unwrap().as_str();
            let value = BitVecValue::from_str_radix(value_str, 10, width).unwrap();
            self.consume_c(&m);
            Some(self.ctx.bv_lit(&value))
        } else if let Some(m) = HEX_LIT_REGEX.captures(self.inp) {
            let width: WidthInt = m.get(1).unwrap().as_str().parse().unwrap();
            let value_str = m.get(2).unwrap().as_str();
            let value = BitVecValue::from_str_radix(value_str, 16, width).unwrap();
            self.consume_c(&m);
            Some(self.ctx.bv_lit(&value))
        } else if let Some(c) = TRUE_FALSE_REGEX.captures(self.inp) {
            self.consume_c(&c);
            if c.get(2).is_some() {
                Some(self.ctx.get_true())
            } else {
                debug_assert!(c.get(3).is_some());
                Some(self.ctx.get_false())
            }
        } else {
            None
        }
    }

    fn try_parse_symbol(&mut self) -> Option<ExprRef> {
        if let Some(c) = SYMBOL_REGEX.captures(self.inp) {
            let escaped_name = c.get(3).map(|m| {
                let len = m.as_str().len();
                &m.as_str()[1..len - 2]
            });
            let name = escaped_name.unwrap_or_else(|| c.get(1).map(|m| m.as_str()).unwrap());

            // do we have an explicit bv type?
            if let Some(width) = c.get(5) {
                let width: WidthInt = width.as_str().parse().unwrap();
                let new_sym = self.ctx.bv_symbol(name, width);
                // compare width
                if let Some(other) = self.symbols.get(name) {
                    let other_width = self.ctx[*other].get_bv_type(self.ctx).unwrap();
                    assert_eq!(
                        width, other_width,
                        "Two symbols with same name {name} have different widths!"
                    );
                } else {
                    // remember width
                    self.symbols.insert(name.to_string(), new_sym);
                }
                self.consume_c(&c);
                Some(new_sym)
            } else {
                let other = *self
                    .symbols
                    .get(name)
                    .unwrap_or_else(|| panic!("symbol of unknown type: `{name}` @ {}", self.inp));
                let width = self.ctx[other].get_bv_type(self.ctx).unwrap();
                self.consume_c(&c);
                Some(self.ctx.bv_symbol(name, width))
            }
        } else {
            None
        }
    }

    fn make_fun(&mut self, fun_id: usize, args: Vec<Arg>) -> ExprRef {
        match (fun_id, args.as_slice()) {
            (0, [Arg::E(e), Arg::C(by)]) => self.ctx.zero_extend(*e, *by),
            (1, [Arg::E(e), Arg::C(by)]) => self.ctx.sign_extend(*e, *by),
            (2, [Arg::E(e)]) => self.ctx.not(*e),
            (3, [Arg::E(e)]) => self.ctx.negate(*e),
            (4, [Arg::E(a), Arg::E(b)]) => self.ctx.equal(*a, *b),
            (5, [Arg::E(a), Arg::E(b)]) => self.ctx.implies(*a, *b),
            (6, [Arg::E(a), Arg::E(b)]) => self.ctx.greater(*a, *b),
            (7, [Arg::E(a), Arg::E(b)]) => self.ctx.greater_signed(*a, *b),
            (8, [Arg::E(a), Arg::E(b)]) => self.ctx.greater_or_equal(*a, *b),
            (9, [Arg::E(a), Arg::E(b)]) => self.ctx.greater_or_equal_signed(*a, *b),
            (10, [Arg::E(a), Arg::E(b)]) => self.ctx.concat(*a, *b),
            (11, [Arg::E(a), Arg::E(b)]) => self.ctx.and(*a, *b),
            (12, [Arg::E(a), Arg::E(b)]) => self.ctx.or(*a, *b),
            (13, [Arg::E(a), Arg::E(b)]) => self.ctx.xor(*a, *b),
            (14, [Arg::E(a), Arg::E(b)]) => self.ctx.shift_left(*a, *b),
            (15, [Arg::E(a), Arg::E(b)]) => self.ctx.arithmetic_shift_right(*a, *b),
            (16, [Arg::E(a), Arg::E(b)]) => self.ctx.shift_right(*a, *b),
            (17, [Arg::E(a), Arg::E(b)]) => self.ctx.add(*a, *b),
            (18, [Arg::E(a), Arg::E(b)]) => self.ctx.mul(*a, *b),
            (19, [Arg::E(a), Arg::E(b)]) => self.ctx.signed_div(*a, *b),
            (20, [Arg::E(a), Arg::E(b)]) => self.ctx.div(*a, *b),
            (21, [Arg::E(a), Arg::E(b)]) => self.ctx.signed_mod(*a, *b),
            (22, [Arg::E(a), Arg::E(b)]) => self.ctx.signed_remainder(*a, *b),
            (23, [Arg::E(a), Arg::E(b)]) => self.ctx.remainder(*a, *b),
            (24, [Arg::E(a), Arg::E(b)]) => self.ctx.sub(*a, *b),
            (25, [Arg::E(a), Arg::E(b), Arg::E(c)]) => self.ctx.ite(*a, *b, *c),
            _ => todo!("implement: {}({:?})", FUNCTIONS[fun_id], args),
        }
    }

    fn parse_args(&mut self, fun_id: usize) -> Vec<Arg> {
        let mut args = vec![];
        let arg_types = FUNCTION_ARGS[fun_id];
        for (ii, at) in arg_types.iter().enumerate() {
            match at {
                ArgTpe::E => {
                    args.push(Arg::E(self.parse_expr()));
                }
                ArgTpe::C => {
                    args.push(Arg::C(self.try_parse_width_int().unwrap()));
                }
            }
            let is_last = ii + 1 == arg_types.len();
            if is_last {
                if let Some(m) = CLOSE_REGEX.find(self.inp) {
                    self.consume_m(&m);
                } else {
                    panic!(
                        "failed to find end of function {} @ {}",
                        FUNCTIONS[fun_id], self.inp
                    );
                }
            } else if let Some(m) = COMMA_REGEX.find(self.inp) {
                self.consume_m(&m);
            } else if !is_last && CLOSE_REGEX.is_match(self.inp) {
                panic!(
                    "Expected another argument for {}({:?},..) @ `{}`",
                    FUNCTIONS[fun_id], args, self.inp
                );
            } else {
                panic!(
                    "failed to find end of argument in function {}, expected `,` or `)` @ `{}`",
                    FUNCTIONS[fun_id], self.inp
                );
            }
        }
        args
    }

    fn try_parse_width_int(&mut self) -> Option<WidthInt> {
        if let Some(m) = DEC_NUM_REGEX.find(self.inp)
            && let Ok(num) = m.as_str().parse()
        {
            self.consume_m(&m);
            return Some(num);
        }
        None
    }

    fn consume_r(&mut self, reg: &Regex) {
        let m = reg.find(self.inp);
        if let Some(m) = m {
            self.consume_m(&m);
        }
    }

    fn consume_m(&mut self, m: &Match) {
        // let to_be_consumed = &self.inp[..m.end()];
        // println!("Consuming: {to_be_consumed}");
        self.inp = &self.inp[m.end()..];
    }

    fn consume_c(&mut self, c: &Captures) {
        self.consume_m(&c.get(0).unwrap());
    }
}

const FUNCTIONS: [&str; 26] = [
    "zext",
    "sext",
    "not",
    "neg",
    "eq",
    "implies",
    "ugt",
    "sgt",
    "ugte",
    "sgte",
    "concat",
    "and",
    "or",
    "xor",
    "shift_left",
    "arithmetic_shift_right",
    "shift_right",
    "add",
    "mul",
    "sdiv",
    "udiv",
    "smod",
    "srem",
    "urem",
    "sub",
    "ite",
];

const FUNCTION_ARGS: [&[ArgTpe]; 26] = [
    &[ArgTpe::E, ArgTpe::C],
    &[ArgTpe::E, ArgTpe::C],
    &[ArgTpe::E],
    &[ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E],
    &[ArgTpe::E, ArgTpe::E, ArgTpe::E],
];

lazy_static! {
    static ref FUNCTION_REGEX: Vec<Regex> =
        FUNCTIONS.iter().map(|name| Regex::new(&format!("^{name}\\s*\\(\\s*")).unwrap()).collect();
    static ref ANY_FUNCTION_REGEX: RegexSet =
        RegexSet::new(FUNCTIONS.iter().map(|name| format!("^{name}\\s*\\(\\s*"))).unwrap();
    static ref COMMA_REGEX: Regex = Regex::new(r"^,\s*").unwrap();
    static ref CLOSE_REGEX: Regex = Regex::new(r"^\)\s*").unwrap();
    static ref DEC_NUM_REGEX: Regex = Regex::new(r"^[[:digit:]]+\s*").unwrap();
    static ref BIN_LIT_REGEX: Regex = Regex::new(r"^([[:digit:]]+)'b([01]+)\s*").unwrap();
    static ref DEC_LIT_REGEX: Regex = Regex::new(r"^([[:digit:]]+)'d([[:digit:]]+)\s*").unwrap();
    static ref HEX_LIT_REGEX: Regex = Regex::new(r"^([[:digit:]]+)'x([0-9a-fA-F]+)\s*").unwrap();
    static ref TRUE_FALSE_REGEX: Regex = Regex::new(r"^((true)|(false))\s*").unwrap();
    // escaped or not + optional type info
    static ref SYMBOL_REGEX: Regex = Regex::new(r"^(([[:alpha:]][[:alnum:]]*)|(\|[^\|]*\|))\s*(:\s*bv<\s*([[:digit:]]+)\s*>\s*)?").unwrap();
    static ref SLICE_REGEX: Regex = Regex::new(r"^\[\s*(([[:digit:]]+)|(([[:digit:]]+)\s*:\s*([[:digit:]]+)))\s*\]\s*").unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_regexes() {
        assert!(TRUE_FALSE_REGEX.is_match("true"));
        assert!(TRUE_FALSE_REGEX.is_match("false"));
        assert!(TRUE_FALSE_REGEX.is_match("true  "));
        assert!(TRUE_FALSE_REGEX.is_match("false  "));
        assert!(!TRUE_FALSE_REGEX.is_match(" false"));
        assert!(TRUE_FALSE_REGEX.is_match("false  123"));

        assert!(SYMBOL_REGEX.is_match("a"));
        assert!(SYMBOL_REGEX.is_match("|a|"));
        assert!(SYMBOL_REGEX.is_match("a : bv<10>"));
        assert!(SYMBOL_REGEX.is_match("a : bv< 10>"));
        assert!(SYMBOL_REGEX.is_match("a : bv<10 >"));
        assert!(SYMBOL_REGEX.is_match("a: bv<10>"));
        assert!(SYMBOL_REGEX.is_match("a :bv<10>"));

        assert!(CLOSE_REGEX.is_match("))"));

        assert!(SLICE_REGEX.captures(", c:bv<5>[4:3]").is_none())
    }

    #[test]
    fn simple_parse() {
        let mut ctx = Context::default();
        assert_eq!(
            parse_expr(&mut ctx, "and(a : bv<1>, b : bv<1>)"),
            ctx.build(|c| c.and(c.bv_symbol("a", 1), c.bv_symbol("b", 1)))
        );

        assert_eq!(
            parse_expr(&mut ctx, "and(a : bv<2>, b : bv<2>)[1]"),
            ctx.build(|c| c.slice(c.and(c.bv_symbol("a", 2), c.bv_symbol("b", 2)), 1, 1))
        );

        assert_eq!(
            parse_expr(&mut ctx, "a : bv<10>[7:3]"),
            ctx.build(|c| c.slice(c.bv_symbol("a", 10), 7, 3))
        );

        assert_eq!(
            parse_expr(&mut ctx, "and(true, false)"),
            ctx.build(|c| c.and(c.get_true(), c.get_false()))
        );

        assert_eq!(
            parse_expr(&mut ctx, "ite(c : bv<1>, a: bv<10>, a)"),
            ctx.build(|c| c.ite(
                c.bv_symbol("c", 1),
                c.bv_symbol("a", 10),
                c.bv_symbol("a", 10)
            )),
        );

        assert_eq!(
            parse_expr(&mut ctx, "and(a : bv<3>, 3'b111)"),
            ctx.build(|c| c.and(c.bv_symbol("a", 3), c.bit_vec_val(0b111, 3)))
        );

        // nested functions
        assert_eq!(
            parse_expr(&mut ctx, "or(and(true, true), false)"),
            ctx.build(|c| c.or(c.and(c.get_true(), c.get_true()), c.get_false()))
        );
        assert_eq!(
            parse_expr(&mut ctx, "or(false, and(true, true))"),
            ctx.build(|c| c.or(c.get_false(), c.and(c.get_true(), c.get_true())))
        );
    }
}