Skip to main content

liquid_fixpoint/
suggestion_solver.rs

1//! Validity check + Quantifier Elimination. Used to make suggestions.
2
3use std::{
4    collections::{HashMap, HashSet},
5    fmt::Write as _,
6    io,
7    path::Path,
8};
9
10use crate::{
11    BinOp, BinRel, ConstDecl, Constant, DataDecl, Expr, FlatConstraint, FunDef, Identifier, Pred,
12    Sort, Types,
13    sexp::{Atom, Sexp},
14    smt_fmt::{SmtEncoder, SmtOptions},
15    z3_subprocess::{SatStatus, Z3Error, Z3Subprocess},
16};
17
18#[derive(Debug)]
19pub enum SuggestionSolverError {
20    Z3Process(io::Error),
21    QETimeout,
22    ContainsQuantifier,
23    NoResults,
24    FailedSanityCheck,
25}
26
27impl From<io::Error> for SuggestionSolverError {
28    fn from(err: io::Error) -> Self {
29        Self::Z3Process(err)
30    }
31}
32
33impl From<Z3Error> for SuggestionSolverError {
34    fn from(err: Z3Error) -> Self {
35        match err {
36            Z3Error::Io(err) => Self::Z3Process(err),
37            Z3Error::Timeout => Self::QETimeout,
38        }
39    }
40}
41
42pub struct SuggestionSolver<T: Types> {
43    session: Z3Subprocess,
44    env: ConstraintGlobalEnv<T>,
45}
46
47impl<T: Types> SuggestionSolver<T> {
48    pub fn new(
49        global_consts: &[ConstDecl<T>],
50        funs: &[FunDef<T>],
51        datatype_decls: Vec<DataDecl<T>>,
52        z3: Option<&Path>,
53    ) -> Result<Self, SuggestionSolverError> {
54        let datatype_decls =
55            crate::constraint_with_env::topo_sort_data_declarations(datatype_decls);
56        let (env, declarations) = ConstraintGlobalEnv::new(&datatype_decls, global_consts, funs);
57        let mut session = Z3Subprocess::new(z3)?;
58        session.reset(&declarations)?;
59        Ok(Self { session, env })
60    }
61
62    pub(crate) fn check_validity(
63        &mut self,
64        constraint: &FlatConstraint<T>,
65    ) -> Result<bool, SuggestionSolverError> {
66        let locals = ConstraintLocalEnv::new(&self.env, &[], &constraint.binders);
67        let mut assertions = constraint
68            .preconditions()
69            .iter()
70            .map(|pred| self.env.pred(pred))
71            .collect::<Vec<_>>();
72        assertions.push(format!("(not {})", self.env.pred(&constraint.head)));
73        let mut setup = locals.declarations;
74        for assertion in &assertions {
75            writeln!(setup, "(assert {assertion})").unwrap();
76        }
77        Ok(matches!(self.session.check_sat(&setup)?, SatStatus::Unsat))
78    }
79
80    pub(crate) fn qe_and_simplify(
81        &mut self,
82        constraint: &FlatConstraint<T>,
83        binder_consts: &[ConstDecl<T>],
84    ) -> Result<Expr<T>, SuggestionSolverError> {
85        let locals = ConstraintLocalEnv::new(&self.env, binder_consts, &constraint.binders);
86        let assumptions = constraint
87            .preconditions()
88            .iter()
89            .map(|pred| self.env.pred(pred))
90            .collect::<Vec<_>>();
91        let body =
92            format!("(=> {} {})", conjunction(&assumptions), self.env.pred(&constraint.head));
93        let implication = self.env.quantified_implication(constraint, &body);
94        self.session.scoped(&locals.declarations, |session| {
95            Self::qe_and_simplify_in_context(
96                session,
97                &self.env,
98                &locals,
99                &assumptions,
100                &body,
101                &implication,
102            )
103        })
104    }
105
106    fn qe_and_simplify_in_context(
107        session: &mut Z3Subprocess,
108        env: &ConstraintGlobalEnv<T>,
109        locals: &ConstraintLocalEnv<'_, T>,
110        assumptions: &[String],
111        body: &str,
112        implication: &str,
113    ) -> Result<Expr<T>, SuggestionSolverError> {
114        let goals =
115            session.apply(&format!("(assert {implication})"), "(try-for (then qe nnf) 10000)")?;
116        let goal = goals.last().ok_or(SuggestionSolverError::NoResults)?;
117        let mut candidate = goal
118            .iter()
119            .map(|formula| locals.decode(formula))
120            .collect::<Result<Vec<_>, _>>()?
121            .into_iter()
122            .min_by_key(Expr::total_num_disjuncts)
123            .ok_or(SuggestionSolverError::NoResults)?;
124
125        let mut setup = String::new();
126        for assumption in assumptions {
127            writeln!(setup, "(assert {assumption})").unwrap();
128        }
129        if session.scoped(&setup, |session| prune_vacuous(&mut candidate, env, session))? {
130            return Ok(Expr::FALSE);
131        }
132
133        let sanity = format!("(not (=> {} {body}))", env.expr(&candidate));
134        if matches!(session.check_sat(&format!("(assert {sanity})"))?, SatStatus::Unsat) {
135            Ok(candidate)
136        } else {
137            Err(SuggestionSolverError::FailedSanityCheck)
138        }
139    }
140}
141
142struct ConstraintGlobalEnv<T: Types> {
143    symbols: HashMap<String, T::Var>,
144    declared_names: HashSet<String>,
145    encoder: SmtEncoder<T>,
146}
147
148impl<T: Types> ConstraintGlobalEnv<T> {
149    fn new(
150        datatype_decls: &[DataDecl<T>],
151        global_consts: &[ConstDecl<T>],
152        funs: &[FunDef<T>],
153    ) -> (Self, String) {
154        let mut symbols = HashMap::new();
155        for decl in datatype_decls {
156            for ctor in &decl.ctors {
157                let name = ctor.name.display().to_string();
158                symbols.insert(name, ctor.name.clone());
159                for field in &ctor.fields {
160                    symbols.insert(field.name.display().to_string(), field.name.clone());
161                }
162            }
163        }
164        for decl in global_consts {
165            symbols.insert(decl.name.display().to_string(), decl.name.clone());
166        }
167        for fun in funs {
168            symbols.insert(fun.name.display().to_string(), fun.name.clone());
169        }
170        let encoder = SmtEncoder::new(datatype_decls, SmtOptions::SUGGESTIONS);
171        let mut out = String::new();
172        for decl in datatype_decls {
173            encoder.write_datatype_decl(&mut out, decl).unwrap();
174        }
175
176        let mut declared = HashSet::new();
177        for decl in global_consts {
178            let name = decl.name.display().to_string();
179            if declared.insert(name.clone()) {
180                encoder
181                    .write_const_decl(&mut out, &name, &decl.sort)
182                    .unwrap();
183            }
184        }
185        for fun in funs {
186            let name = fun.name.display().to_string();
187            if declared.insert(name.clone()) {
188                encoder.write_fun_def(&mut out, fun).unwrap();
189            }
190        }
191        (Self { symbols, declared_names: declared, encoder }, out)
192    }
193
194    fn pred(&self, pred: &Pred<T>) -> String {
195        self.encoder.pred(pred).unwrap()
196    }
197
198    fn expr(&self, expr: &Expr<T>) -> String {
199        self.encoder.expr(expr).unwrap()
200    }
201
202    fn quantified_implication(&self, cstr: &FlatConstraint<T>, body: &str) -> String {
203        let mut quantified = body.to_string();
204        for (name, sort) in &cstr.binders {
205            let mut binder_sort = String::new();
206            self.encoder.write_sort(&mut binder_sort, sort).unwrap();
207            quantified = format!("(forall (({} {binder_sort})) {quantified})", name.display());
208        }
209        quantified
210    }
211}
212
213/// Declarations active in a single constraint's solver scope (as a string to
214/// send to Z3), and maps to decode its response back to T.
215struct ConstraintLocalEnv<'a, T: Types> {
216    declarations: String,
217    symbols: HashMap<String, T::Var>,
218    global_symbols: &'a HashMap<String, T::Var>,
219}
220
221impl<'a, T: Types> ConstraintLocalEnv<'a, T> {
222    fn new(
223        globals: &'a ConstraintGlobalEnv<T>,
224        binder_consts: &[ConstDecl<T>],
225        binders: &[(T::Var, Sort<T>)],
226    ) -> Self {
227        let mut declarations = String::new();
228        let mut declared = HashSet::new();
229        let mut symbols = HashMap::new();
230        for (var, sort) in binder_consts
231            .iter()
232            .map(|decl| (&decl.name, &decl.sort))
233            .chain(binders.iter().map(|(var, sort)| (var, sort)))
234        {
235            let name = var.display().to_string();
236            if !globals.declared_names.contains(&name) && declared.insert(name.clone()) {
237                globals
238                    .encoder
239                    .write_const_decl(&mut declarations, &name, sort)
240                    .unwrap();
241            }
242            if !globals.symbols.contains_key(&name) {
243                symbols.insert(name, var.clone());
244            }
245        }
246        for (var, _) in binders {
247            symbols.insert(var.display().to_string(), var.clone());
248        }
249        Self { declarations, symbols, global_symbols: &globals.symbols }
250    }
251
252    fn symbol(&self, name: &str) -> Option<&T::Var> {
253        self.symbols
254            .get(name)
255            .or_else(|| self.global_symbols.get(name))
256    }
257
258    fn decode(&self, sexp: &Sexp) -> Result<Expr<T>, SuggestionSolverError> {
259        match sexp {
260            Sexp::Atom(Atom::B(value)) => Ok(Expr::Constant(Constant::Boolean(*value))),
261            Sexp::Atom(Atom::I(value)) if *value >= 0 => {
262                Ok(Expr::Constant(Constant::Numeral(*value as u128)))
263            }
264            Sexp::Atom(Atom::I(value)) => {
265                Ok(Expr::Neg(Box::new(Expr::Constant(Constant::Numeral(value.unsigned_abs())))))
266            }
267            Sexp::Atom(Atom::S(name)) => self.decode_symbol(name),
268            Sexp::Atom(atom) => panic!("unsupported atom in Z3 output: `{atom:?}`"),
269            Sexp::List(items) => self.decode_application(items),
270        }
271    }
272
273    fn decode_symbol(&self, name: &str) -> Result<Expr<T>, SuggestionSolverError> {
274        match name {
275            "true" => Ok(Expr::TRUE),
276            "false" => Ok(Expr::FALSE),
277            _ => {
278                Ok(Expr::Var(
279                    self.symbol(name)
280                        .cloned()
281                        .unwrap_or_else(|| panic!("unknown symbol in Z3 output: `{name}`")),
282                ))
283            }
284        }
285    }
286
287    fn decode_application(&self, items: &[Sexp]) -> Result<Expr<T>, SuggestionSolverError> {
288        let Some((head, args)) = items.split_first() else {
289            panic!("empty application in Z3 output");
290        };
291        let head = application_head(head);
292        if matches!(head, "forall" | "exists") {
293            return Err(SuggestionSolverError::ContainsQuantifier);
294        }
295        let decoded = || {
296            args.iter()
297                .map(|arg| self.decode(arg))
298                .collect::<Result<Vec<_>, _>>()
299        };
300        match head {
301            "let" => {
302                // FIXME: substitution below is not scope-aware. For example,
303                // (let ((x 1)) (let ((x 2)) x)) should decode to 2, but replacing
304                // the outer x also rewrites the inner binding to (let ((1 2)) 1).
305                // A fix must also preserve simultaneous let bindings: in
306                // (let ((x 1)) (let ((x 2) (y x)) y)), y refers to the outer x,
307                // so the result is 1, not 2. Decode all RHSs in the outer scope
308                // before extending the environment for the body.
309                let args = exact_arg(head, args, 2);
310                let Sexp::List(bindings) = &args[0] else {
311                    panic!("malformed let bindings in Z3 output: {:?}", args[0]);
312                };
313                let mut substitutions = HashMap::new();
314                for binding in bindings {
315                    let Sexp::List(binding) = binding else {
316                        panic!("malformed let binding in Z3 output: {binding:?}");
317                    };
318                    let [Sexp::Atom(Atom::S(name)), value] = binding.as_slice() else {
319                        panic!("malformed let binding in Z3 output: {binding:?}");
320                    };
321                    substitutions.insert(name.as_str(), value);
322                }
323                self.decode(&substitute_sexp(&args[1], &substitutions))
324            }
325            "and" => Ok(Expr::And(decoded()?)),
326            "or" => Ok(Expr::Or(decoded()?)),
327            "not" => Ok(Expr::Not(Box::new(self.decode(&exact_arg(head, args, 1)[0])?))),
328            "=>" => {
329                let args = exact_arg(head, args, 2);
330                Ok(Expr::Imp(Box::new([self.decode(&args[0])?, self.decode(&args[1])?])))
331            }
332            "=" => {
333                let args = exact_arg(head, args, 2);
334                Ok(Expr::Atom(
335                    BinRel::Eq,
336                    Box::new([self.decode(&args[0])?, self.decode(&args[1])?]),
337                ))
338            }
339            "<" | "<=" | ">" | ">=" => {
340                let rel = match head {
341                    "<" => BinRel::Lt,
342                    "<=" => BinRel::Le,
343                    ">" => BinRel::Gt,
344                    ">=" => BinRel::Ge,
345                    _ => unreachable!(),
346                };
347                let args = exact_arg(head, args, 2);
348                Ok(Expr::Atom(rel, Box::new([self.decode(&args[0])?, self.decode(&args[1])?])))
349            }
350            "ite" => {
351                let args = exact_arg(head, args, 3);
352                Ok(Expr::IfThenElse(Box::new([
353                    self.decode(&args[0])?,
354                    self.decode(&args[1])?,
355                    self.decode(&args[2])?,
356                ])))
357            }
358            "-" if args.len() == 1 => Ok(Expr::Neg(Box::new(self.decode(&args[0])?))),
359            "+" | "-" | "*" | "div" | "mod" => {
360                if args.len() < 2 {
361                    panic!(
362                        "expected at least two arguments for `{head}` in Z3 output, got {}",
363                        args.len()
364                    );
365                }
366                let op = match head {
367                    "+" => BinOp::Add,
368                    "-" => BinOp::Sub,
369                    "*" => BinOp::Mul,
370                    "div" => BinOp::Div,
371                    "mod" => BinOp::Mod,
372                    _ => unreachable!(),
373                };
374                let mut args = decoded()?.into_iter();
375                let lhs = args
376                    .next()
377                    .expect("binary operator has at least two arguments");
378                Ok(args.fold(lhs, |lhs, rhs| Expr::BinaryOp(op, Box::new([lhs, rhs]))))
379            }
380            name => {
381                let var = self
382                    .symbol(name)
383                    .unwrap_or_else(|| panic!("unknown application in Z3 output: `{name}`"));
384                Ok(Expr::App(Box::new(Expr::Var(var.clone())), None, decoded()?, None))
385            }
386        }
387    }
388}
389
390fn substitute_sexp(sexp: &Sexp, substitutions: &HashMap<&str, &Sexp>) -> Sexp {
391    match sexp {
392        Sexp::Atom(Atom::S(name)) => {
393            substitutions
394                .get(name.as_str())
395                .copied()
396                .unwrap_or(sexp)
397                .clone()
398        }
399        Sexp::Atom(_) => sexp.clone(),
400        Sexp::List(items) => {
401            Sexp::List(
402                items
403                    .iter()
404                    .map(|item| substitute_sexp(item, substitutions))
405                    .collect(),
406            )
407        }
408    }
409}
410
411fn prune_vacuous<T: Types>(
412    expr: &mut Expr<T>,
413    env: &ConstraintGlobalEnv<T>,
414    session: &mut Z3Subprocess,
415) -> Result<bool, SuggestionSolverError> {
416    match expr {
417        Expr::And(conjuncts) => {
418            let copy = conjuncts.clone();
419            for (i, conjunct) in conjuncts.iter_mut().enumerate() {
420                let mut setup = String::new();
421                for (j, sibling) in copy.iter().enumerate() {
422                    if i != j {
423                        writeln!(setup, "(assert {})", env.expr(sibling)).unwrap();
424                    }
425                }
426                if session.scoped(&setup, |session| prune_vacuous(conjunct, env, session))? {
427                    *expr = Expr::FALSE;
428                    return Ok(true);
429                }
430            }
431            Ok(false)
432        }
433        Expr::Or(disjuncts) => {
434            let mut kept = Vec::with_capacity(disjuncts.len());
435            for mut disjunct in std::mem::take(disjuncts) {
436                if !prune_vacuous(&mut disjunct, env, session)? {
437                    kept.push(disjunct);
438                }
439            }
440            match kept.len() {
441                0 => {
442                    *expr = Expr::FALSE;
443                    Ok(true)
444                }
445                1 => {
446                    *expr = kept.pop().unwrap();
447                    Ok(false)
448                }
449                _ => {
450                    *disjuncts = kept;
451                    Ok(false)
452                }
453            }
454        }
455        _ => {
456            Ok(matches!(
457                session.check_sat(&format!("(assert {})", env.expr(expr)))?,
458                SatStatus::Unsat
459            ))
460        }
461    }
462}
463
464fn application_head(head: &Sexp) -> &str {
465    if let Sexp::Atom(Atom::S(name)) = head {
466        return name;
467    }
468    if let Sexp::List(items) = head
469        && atom_symbol(items.first()) == Some("as")
470        && let Some(Sexp::Atom(Atom::S(name))) = items.get(1)
471    {
472        return name;
473    }
474    panic!("unsupported application head in Z3 output: `{head:?}`")
475}
476
477fn atom_symbol(sexp: Option<&Sexp>) -> Option<&str> {
478    match sexp {
479        Some(Sexp::Atom(Atom::S(symbol))) => Some(symbol),
480        _ => None,
481    }
482}
483
484fn exact_arg<'a>(operator: &str, args: &'a [Sexp], expected: usize) -> &'a [Sexp] {
485    if args.len() == expected {
486        args
487    } else {
488        panic!(
489            "unexpected argument count for `{operator}` in Z3 output: expected {expected}, got {}",
490            args.len()
491        )
492    }
493}
494
495fn conjunction(assertions: &[String]) -> String {
496    match assertions {
497        [] => "true".to_string(),
498        [only] => only.clone(),
499        _ => format!("(and {})", assertions.join(" ")),
500    }
501}