1use std::collections::HashMap;
11
12use anyhow::{bail, Result};
13
14use crate::base::FfnId;
15use crate::foreign::ForeignLang;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum UnaryOp {
20 Not,
22 Neg,
24}
25
26#[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum BinOp {
30 Add,
31 Sub,
32 Mul,
33 Div,
34 Mod,
35 Eq,
36 Ne,
37 Lt,
38 Le,
39 Gt,
40 Ge,
41 And,
42 Or,
43}
44
45impl BinOp {
46 pub fn symbol(self) -> &'static str {
48 match self {
49 BinOp::Add => "+",
50 BinOp::Sub => "-",
51 BinOp::Mul => "*",
52 BinOp::Div => "/",
53 BinOp::Mod => "%",
54 BinOp::Eq => "==",
55 BinOp::Ne => "!=",
56 BinOp::Lt => "<",
57 BinOp::Le => "<=",
58 BinOp::Gt => ">",
59 BinOp::Ge => ">=",
60 BinOp::And => "&&",
61 BinOp::Or => "||",
62 }
63 }
64
65 pub fn from_symbol(s: &str) -> Self {
72 match s {
73 "+" => BinOp::Add,
74 "-" => BinOp::Sub,
75 "*" => BinOp::Mul,
76 "/" => BinOp::Div,
77 "%" => BinOp::Mod,
78 "==" => BinOp::Eq,
79 "!=" => BinOp::Ne,
80 "<" => BinOp::Lt,
81 "<=" => BinOp::Le,
82 ">" => BinOp::Gt,
83 ">=" => BinOp::Ge,
84 "&&" => BinOp::And,
85 "||" => BinOp::Or,
86 _ => unreachable!("operator alternatives are exhaustive"),
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum Term {
94 Int(i128),
96 Bool(bool),
98 Param(String),
100 RetVal,
102 Field {
104 base: Box<Term>,
106 name: String,
108 },
109 Old(Box<Term>),
112 Unary {
114 op: UnaryOp,
116 operand: Box<Term>,
118 },
119 Binary {
121 op: BinOp,
123 lhs: Box<Term>,
125 rhs: Box<Term>,
127 },
128 Ternary {
130 cond: Box<Term>,
132 then: Box<Term>,
134 els: Box<Term>,
136 },
137}
138
139impl Term {
140 pub fn binary(op: &str, lhs: Term, rhs: Term) -> Term {
142 Term::Binary {
143 op: BinOp::from_symbol(op),
144 lhs: Box::new(lhs),
145 rhs: Box::new(rhs),
146 }
147 }
148
149 fn children(&self) -> impl Iterator<Item = &Term> {
151 let (a, b, c) = match self {
152 Term::Int(_) | Term::Bool(_) | Term::Param(_) | Term::RetVal => (None, None, None),
153 Term::Old(t) | Term::Unary { operand: t, .. } | Term::Field { base: t, .. } => {
154 (Some(&**t), None, None)
155 }
156 Term::Binary { lhs, rhs, .. } => (Some(&**lhs), Some(&**rhs), None),
157 Term::Ternary { cond, then, els } => (Some(&**cond), Some(&**then), Some(&**els)),
158 };
159 [a, b, c].into_iter().flatten()
160 }
161
162 pub fn mentions_retval(&self) -> bool {
164 matches!(self, Term::RetVal) || self.children().any(Term::mentions_retval)
165 }
166
167 pub fn identifiers(&self) -> Vec<&str> {
169 let mut out = Vec::new();
170 self.collect_identifiers(&mut out);
171 out
172 }
173
174 fn collect_identifiers<'a>(&'a self, out: &mut Vec<&'a str>) {
175 if let Term::Param(name) = self {
176 if !out.contains(&name.as_str()) {
177 out.push(name);
178 }
179 }
180 for child in self.children() {
181 child.collect_identifiers(out);
182 }
183 }
184}
185
186#[derive(Debug, Clone)]
188pub struct FnContract {
189 pub lang: ForeignLang,
191 pub name: String,
193 pub params: Vec<String>,
195 pub requires: Vec<Term>,
197 pub ensures: Vec<Term>,
199 pub retval: Option<Term>,
203 pub impurity: Option<String>,
206 pub fields: Vec<(String, Term)>,
209}
210
211impl FnContract {
212 pub fn from_clauses(
221 lang: ForeignLang,
222 name: String,
223 params: Vec<String>,
224 requires: Vec<Term>,
225 ensures: Vec<Term>,
226 impurity: Option<String>,
227 ) -> Result<Self> {
228 if requires.iter().any(Term::mentions_retval) {
229 bail!(
230 "function `{name}`: a `requires` clause mentions the return value, which only \
231 exists after the call"
232 );
233 }
234
235 let fields = ensures.iter().filter_map(field_value).collect();
236 let mut retval = None;
237 for clause in &ensures {
238 let Some(rhs) = deterministic_rhs(clause) else {
239 continue;
240 };
241 if retval.is_some() {
242 bail!(
243 "function `{name}`: two `ensures retval == …` clauses; fic needs exactly one \
244 deterministic value for the return"
245 );
246 }
247 retval = Some(rhs.clone());
248 }
249
250 Ok(FnContract {
251 lang,
252 name,
253 params,
254 requires,
255 ensures,
256 retval,
257 impurity,
258 fields,
259 })
260 }
261}
262
263fn field_value(clause: &Term) -> Option<(String, Term)> {
265 let Term::Binary {
266 op: BinOp::Eq,
267 lhs,
268 rhs,
269 } = clause
270 else {
271 return None;
272 };
273 let ((Term::Field { base, name }, e) | (e, Term::Field { base, name })) =
274 (lhs.as_ref(), rhs.as_ref())
275 else {
276 return None;
277 };
278 (**base == Term::RetVal && !e.mentions_retval()).then(|| (name.clone(), e.clone()))
279}
280
281impl FnContract {
282 #[must_use]
287 pub fn result_range(&self) -> Option<(i128, i128)> {
288 if self.retval.is_some() {
289 return None;
290 }
291 let mut range = (None, None);
292 let mut bounded = false;
293 for clause in self.ensures.iter().filter(|c| c.mentions_retval()) {
294 range = meet(range, interval(clause)?);
295 bounded = true;
296 }
297 match range {
298 (Some(lo), Some(hi)) if bounded && lo <= hi => Some((lo, hi)),
299 _ => None,
300 }
301 }
302}
303
304type Interval = (Option<i128>, Option<i128>);
306
307fn meet(a: Interval, b: Interval) -> Interval {
308 let lo = match (a.0, b.0) {
309 (Some(x), Some(y)) => Some(x.max(y)),
310 (x, y) => x.or(y),
311 };
312 let hi = match (a.1, b.1) {
313 (Some(x), Some(y)) => Some(x.min(y)),
314 (x, y) => x.or(y),
315 };
316 (lo, hi)
317}
318
319fn hull(a: Interval, b: Interval) -> Interval {
321 let lo = a.0.zip(b.0).map(|(x, y)| x.min(y));
322 let hi = a.1.zip(b.1).map(|(x, y)| x.max(y));
323 (lo, hi)
324}
325
326fn interval(clause: &Term) -> Option<Interval> {
329 let Term::Binary { op, lhs, rhs } = clause else {
330 return None;
331 };
332 match op {
333 BinOp::And => Some(meet(interval(lhs)?, interval(rhs)?)),
334 BinOp::Or => Some(hull(interval(lhs)?, interval(rhs)?)),
335 BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
336 let (op, c) = match (lhs.as_ref(), rhs.as_ref()) {
338 (Term::RetVal, c) => (*op, constant(c)?),
339 (c, Term::RetVal) => (flipped(*op), constant(c)?),
340 _ => return None,
341 };
342 Some(match op {
343 BinOp::Eq => (Some(c), Some(c)),
344 BinOp::Lt => (None, Some(c - 1)),
345 BinOp::Le => (None, Some(c)),
346 BinOp::Gt => (Some(c + 1), None),
347 _ => (Some(c), None),
348 })
349 }
350 _ => None,
351 }
352}
353
354fn flipped(op: BinOp) -> BinOp {
356 match op {
357 BinOp::Lt => BinOp::Gt,
358 BinOp::Le => BinOp::Ge,
359 BinOp::Gt => BinOp::Lt,
360 BinOp::Ge => BinOp::Le,
361 op => op,
362 }
363}
364
365fn constant(t: &Term) -> Option<i128> {
367 match t {
368 Term::Int(n) => Some(*n),
369 Term::Unary {
370 op: UnaryOp::Neg,
371 operand,
372 } => constant(operand).map(|n| -n),
373 _ => None,
374 }
375}
376
377fn deterministic_rhs(clause: &Term) -> Option<&Term> {
379 let Term::Binary {
380 op: BinOp::Eq,
381 lhs,
382 rhs,
383 } = clause
384 else {
385 return None;
386 };
387 match (lhs.as_ref(), rhs.as_ref()) {
388 (Term::RetVal, e) | (e, Term::RetVal) if !e.mentions_retval() => Some(e),
389 _ => None,
390 }
391}
392
393#[derive(Debug, Default)]
396pub struct ContractTable {
397 fns: HashMap<FfnId, FnContract>,
398}
399
400impl ContractTable {
401 pub fn insert(&mut self, f: FfnId, contract: FnContract) {
403 self.fns.insert(f, contract);
404 }
405
406 pub fn contract(&self, f: FfnId) -> Option<&FnContract> {
408 self.fns.get(&f)
409 }
410
411 pub fn is_empty(&self) -> bool {
413 self.fns.is_empty()
414 }
415
416 pub fn function_count(&self) -> usize {
418 self.fns.len()
419 }
420
421 pub fn function_counts(&self) -> Vec<(ForeignLang, usize)> {
423 let mut counts: Vec<(ForeignLang, usize)> = Vec::new();
424 for c in self.fns.values() {
425 match counts.iter_mut().find(|(l, _)| *l == c.lang) {
426 Some((_, n)) => *n += 1,
427 None => counts.push((c.lang, 1)),
428 }
429 }
430 counts.sort_by_key(|(l, _)| l.to_string());
431 counts
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 fn retval_eq(e: Term) -> Term {
440 Term::binary("==", Term::RetVal, e)
441 }
442
443 #[test]
444 fn a_unique_retval_equality_is_the_deterministic_value() {
445 let c = FnContract::from_clauses(
446 ForeignLang::Pancake,
447 "tally".into(),
448 vec!["r".into()],
449 vec![Term::binary("<=", Term::Int(0), Term::Param("r".into()))],
450 vec![retval_eq(Term::binary(
451 "+",
452 Term::Param("r".into()),
453 Term::Int(1),
454 ))],
455 None,
456 )
457 .expect("contract builds");
458 assert_eq!(
459 c.retval,
460 Some(Term::binary("+", Term::Param("r".into()), Term::Int(1)))
461 );
462 }
463
464 #[test]
465 fn a_non_equality_ensures_leaves_the_return_free() {
466 let c = FnContract::from_clauses(
467 ForeignLang::Pancake,
468 "pick".into(),
469 Vec::new(),
470 Vec::new(),
471 vec![Term::binary("<", Term::RetVal, Term::Int(8))],
472 None,
473 )
474 .expect("contract builds");
475 assert!(c.retval.is_none());
476 }
477
478 fn ranged(ensures: Vec<Term>) -> Option<(i128, i128)> {
479 FnContract::from_clauses(
480 ForeignLang::C,
481 "f".into(),
482 Vec::new(),
483 Vec::new(),
484 ensures,
485 None,
486 )
487 .expect("contract builds")
488 .result_range()
489 }
490
491 #[test]
492 fn a_bounded_return_has_its_interval() {
493 let r = || Term::RetVal;
494 let either = Term::binary(
495 "||",
496 Term::binary("==", r(), Term::Int(0)),
497 Term::binary("==", r(), Term::Int(1)),
498 );
499 assert_eq!(ranged(vec![either]), Some((0, 1)));
500 let within = Term::binary(
502 "&&",
503 Term::binary("<=", Term::Int(0), r()),
504 Term::binary("<=", r(), Term::Int(3)),
505 );
506 assert_eq!(ranged(vec![within]), Some((0, 3)));
507 let two = vec![
509 Term::binary(">", r(), Term::Int(-1)),
510 Term::binary("<", r(), Term::Int(4)),
511 ];
512 assert_eq!(ranged(two), Some((0, 3)));
513 }
514
515 #[test]
516 fn an_unbounded_or_dependent_return_has_none() {
517 assert_eq!(
518 ranged(vec![Term::binary("<", Term::RetVal, Term::Int(8))]),
519 None
520 );
521 let on_param = Term::binary("==", Term::RetVal, Term::Param("x".into()));
522 assert_eq!(
523 ranged(vec![
524 Term::binary("<=", Term::Int(0), Term::RetVal),
525 on_param
526 ]),
527 None
528 );
529 assert_eq!(ranged(vec![retval_eq(Term::Int(2))]), None, "deterministic");
530 }
531
532 #[test]
533 fn a_result_field_fixed_by_ensures_is_collected() {
534 let origin = || Term::Field {
535 base: Box::new(Term::RetVal),
536 name: "origin".into(),
537 };
538 let c = FnContract::from_clauses(
539 ForeignLang::C,
540 "eth_frame".into(),
541 vec!["nth".into()],
542 Vec::new(),
543 vec![Term::binary("==", origin(), Term::Param("nth".into()))],
544 None,
545 )
546 .expect("contract builds");
547 assert_eq!(c.fields, [("origin".to_owned(), Term::Param("nth".into()))]);
548 assert!(c.retval.is_none() && c.result_range().is_none());
549 }
550
551 #[test]
552 fn two_retval_equalities_are_rejected() {
553 let err = FnContract::from_clauses(
554 ForeignLang::Pancake,
555 "f".into(),
556 Vec::new(),
557 Vec::new(),
558 vec![retval_eq(Term::Int(0)), retval_eq(Term::Int(1))],
559 None,
560 )
561 .expect_err("two deterministic values");
562 assert!(err.to_string().contains("two `ensures retval"), "{err}");
563 }
564
565 #[test]
566 fn retval_in_a_precondition_is_rejected() {
567 let err = FnContract::from_clauses(
568 ForeignLang::Pancake,
569 "f".into(),
570 Vec::new(),
571 vec![Term::binary("<", Term::RetVal, Term::Int(1))],
572 Vec::new(),
573 None,
574 )
575 .expect_err("retval before the call");
576 assert!(
577 err.to_string().contains("only exists after the call"),
578 "{err}"
579 );
580 }
581
582 #[test]
583 fn a_contract_is_found_by_its_function() {
584 use crate::base::Idx;
585
586 let contract = |lang, name: &str| FnContract {
587 lang,
588 name: name.into(),
589 params: Vec::new(),
590 requires: Vec::new(),
591 ensures: Vec::new(),
592 retval: None,
593 impurity: None,
594 fields: Vec::new(),
595 };
596 let f = FfnId::new;
597 let mut table = ContractTable::default();
598 table.insert(f(1), contract(ForeignLang::Pancake, "b"));
599 table.insert(f(2), contract(ForeignLang::C, "a"));
600 assert_eq!(table.contract(f(1)).map(|c| c.name.as_str()), Some("b"));
601 assert!(table.contract(f(0)).is_none());
602 assert_eq!(table.function_count(), 2);
603 assert_eq!(
604 table.function_counts(),
605 vec![(ForeignLang::C, 1), (ForeignLang::Pancake, 1)]
606 );
607 }
608}