Skip to main content

liquid_fixpoint/
lib.rs

1//! This crate implements an interface to the [liquid-fixpoint] binary
2//!
3//! [liquid-fixpoint]: https://github.com/ucsd-progsys/liquid-fixpoint
4#![cfg_attr(feature = "nightly", feature(rustc_private))]
5
6#[cfg(feature = "nightly")]
7extern crate rustc_data_structures;
8// Link rustc-private dependencies through the driver dylib in unit tests.
9#[cfg(all(test, feature = "nightly"))]
10#[allow(unused_extern_crates)]
11extern crate rustc_driver;
12#[cfg(feature = "nightly")]
13extern crate rustc_macros;
14#[cfg(feature = "nightly")]
15extern crate rustc_serialize;
16#[cfg(feature = "nightly")]
17extern crate rustc_span;
18
19mod constraint;
20#[cfg(feature = "rust-fixpoint")]
21mod constraint_fragments;
22#[cfg(feature = "rust-fixpoint")]
23mod constraint_solving;
24mod constraint_with_env;
25#[cfg(feature = "rust-fixpoint")]
26mod cstr2smt2;
27mod format;
28mod graph;
29pub mod parser;
30pub mod sexp;
31mod smt_fmt;
32pub mod smt_horn;
33mod suggestion_solver;
34mod z3_subprocess;
35
36use std::{
37    collections::{HashMap, hash_map::DefaultHasher},
38    fmt::{self, Debug},
39    hash::{Hash, Hasher},
40    io,
41    path::Path,
42    str::FromStr,
43    time::Duration,
44};
45#[cfg(not(feature = "rust-fixpoint"))]
46use std::{
47    io::{BufWriter, Write as IOWrite},
48    process::{Command, Stdio},
49};
50
51pub use constraint::{
52    Axiom, BinOp, BinRel, Bind, Constant, Constraint, DataCtor, DataDecl, DataField, Expr,
53    FlatConstraint, FunSort, Pred, QualParam, Qualifier, Quantifier, Sort, SortCtor, SortDecl,
54    WKVar,
55};
56use derive_where::derive_where;
57#[cfg(feature = "nightly")]
58use rustc_macros::{Decodable, Encodable};
59use serde::{Deserialize, Serialize, de};
60
61/// Type alias for qualifier assignments used in constraint solving
62pub type Assignments<'a, T> = HashMap<<T as Types>::KVar, Vec<(&'a Qualifier<T>, Vec<usize>)>>;
63
64#[cfg(not(feature = "rust-fixpoint"))]
65use process_control::{ChildExt, Control};
66
67#[cfg(feature = "rust-fixpoint")]
68use crate::constraint_with_env::ConstraintWithEnv;
69pub use crate::suggestion_solver::{SuggestionSolver, SuggestionSolverError};
70
71pub trait Types {
72    type Sort: Identifier + Hash + Clone + Debug + Eq;
73    type KVar: Identifier + Hash + Clone + Debug + Eq;
74    type Var: Identifier + Hash + Clone + Debug + Eq;
75    type String: FixpointFmt + Hash + Clone + Debug + Eq;
76    type Real: FixpointFmt + Hash + Clone + Debug + Eq;
77    type Tag: fmt::Display + FromStr + Hash + Clone + Debug;
78}
79
80pub trait FixpointFmt: Sized {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
82
83    /// Returns a type that implements [`fmt::Display`] using this [`FixpointFmt::fmt`] implementation.
84    fn display(&self) -> impl fmt::Display {
85        struct DisplayAdapter<T>(T);
86        impl<T: FixpointFmt> std::fmt::Display for DisplayAdapter<&T> {
87            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88                FixpointFmt::fmt(self.0, f)
89            }
90        }
91        DisplayAdapter(self)
92    }
93}
94
95pub trait Identifier: Sized {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
97
98    /// Returns a type that implements [`fmt::Display`] using this [`Identifier::fmt`] implementation.
99    fn display(&self) -> impl fmt::Display {
100        struct DisplayAdapter<T>(T);
101        impl<T: Identifier> fmt::Display for DisplayAdapter<&T> {
102            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103                Identifier::fmt(self.0, f)
104            }
105        }
106        DisplayAdapter(self)
107    }
108}
109
110impl Identifier for &str {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "{self}")
113    }
114}
115
116impl FixpointFmt for u32 {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        write!(f, "{self}")
119    }
120}
121
122impl FixpointFmt for String {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(f, "\"{self}\"")
125    }
126}
127
128#[macro_export]
129macro_rules! declare_types {
130    (   type Sort = $sort:ty;
131        type KVar = $kvar:ty;
132        type Var = $var:ty;
133        type String = $str:ty;
134        type Real = $real:ty;
135        type Tag = $tag:ty;
136    ) => {
137        pub mod fixpoint_generated {
138            pub struct FixpointTypes;
139            pub type Expr = $crate::Expr<FixpointTypes>;
140            pub type Constraint = $crate::Constraint<FixpointTypes>;
141            pub type FlatConstraint = $crate::FlatConstraint<FixpointTypes>;
142            pub type KVarDecl = $crate::KVarDecl<FixpointTypes>;
143            pub type ConstDecl = $crate::ConstDecl<FixpointTypes>;
144            pub type FunDef = $crate::FunDef<FixpointTypes>;
145            pub type FunSort = $crate::FunSort<FixpointTypes>;
146            pub type FunBody = $crate::FunBody<FixpointTypes>;
147            pub type Task = $crate::Task<FixpointTypes>;
148            pub type Qualifier = $crate::Qualifier<FixpointTypes>;
149            pub type Axiom = $crate::Axiom<FixpointTypes>;
150            pub type QualParam = $crate::QualParam<FixpointTypes>;
151            pub type Sort = $crate::Sort<FixpointTypes>;
152            pub type SortCtor = $crate::SortCtor<FixpointTypes>;
153            pub type SortDecl = $crate::SortDecl<FixpointTypes>;
154            pub type DataDecl = $crate::DataDecl<FixpointTypes>;
155            pub type DataCtor = $crate::DataCtor<FixpointTypes>;
156            pub type DataField = $crate::DataField<FixpointTypes>;
157            pub type Bind = $crate::Bind<FixpointTypes>;
158            pub type Constant = $crate::Constant<FixpointTypes>;
159            pub type Pred = $crate::Pred<FixpointTypes>;
160            pub use $crate::{BinOp, BinRel, Quantifier, ThyFunc, WKVar};
161        }
162
163        impl $crate::Types for fixpoint_generated::FixpointTypes {
164            type Sort = $sort;
165            type KVar = $kvar;
166            type Var = $var;
167            type String = $str;
168            type Real = $real;
169            type Tag = $tag;
170        }
171    };
172}
173
174pub fn qe_and_simplify<T: Types>(
175    solver: &mut SuggestionSolver<T>,
176    constraint: &FlatConstraint<T>,
177    binder_consts: &[ConstDecl<T>],
178) -> Result<Expr<T>, SuggestionSolverError> {
179    solver.qe_and_simplify(constraint, binder_consts)
180}
181
182pub fn check_validity<T: Types>(
183    solver: &mut SuggestionSolver<T>,
184    constraint: &FlatConstraint<T>,
185) -> Result<bool, SuggestionSolverError> {
186    solver.check_validity(constraint)
187}
188
189#[derive_where(Hash, Clone, Debug)]
190pub struct ConstDecl<T: Types> {
191    pub name: T::Var,
192    pub sort: Sort<T>,
193    #[derive_where(skip)]
194    pub comment: Option<String>,
195}
196
197#[derive_where(Hash, Clone, Debug)]
198pub struct FunDef<T: Types> {
199    pub name: T::Var,
200    pub sort: FunSort<T>,
201    pub body: Option<FunBody<T>>,
202    #[derive_where(skip)]
203    pub comment: Option<String>,
204}
205
206#[derive_where(Hash, Clone, Debug)]
207pub struct FunBody<T: Types> {
208    pub args: Vec<T::Var>,
209    pub expr: Expr<T>,
210}
211
212#[derive_where(Hash)]
213pub struct Task<T: Types> {
214    #[derive_where(skip)]
215    pub comments: Vec<String>,
216    pub constants: Vec<ConstDecl<T>>,
217    pub data_decls: Vec<DataDecl<T>>,
218    pub define_funs: Vec<FunDef<T>>,
219    pub kvars: Vec<KVarDecl<T>>,
220    pub constraint: Constraint<T>,
221    pub qualifiers: Vec<Qualifier<T>>,
222    pub axioms: Vec<Axiom<T>>,
223    pub scrape_quals: bool,
224    pub solver: SmtSolver,
225}
226
227#[derive(Clone, Copy, Hash)]
228pub enum SmtSolver {
229    Z3,
230    CVC5,
231}
232
233impl fmt::Display for SmtSolver {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        match self {
236            SmtSolver::Z3 => write!(f, "z3"),
237            SmtSolver::CVC5 => write!(f, "cvc5"),
238        }
239    }
240}
241
242#[derive(Serialize, Deserialize, Debug, Clone)]
243#[serde(
244    tag = "tag",
245    content = "contents",
246    bound(deserialize = "Tag: FromStr", serialize = "Tag: ToString")
247)]
248pub enum FixpointStatus<Tag> {
249    Safe(Stats),
250    Unsafe(Stats, Vec<Error<Tag>>),
251    Crash(CrashInfo),
252}
253
254/// An error that prevented fixpoint from producing a result
255#[derive(Debug)]
256pub enum FixpointError {
257    /// Fixpoint didn't finish within the given timeout and was killed
258    Timeout,
259    Io(io::Error),
260}
261
262impl From<io::Error> for FixpointError {
263    fn from(err: io::Error) -> Self {
264        FixpointError::Io(err)
265    }
266}
267
268#[derive(Serialize, Deserialize, Debug, Clone, Default)]
269#[serde(tag = "tag", content = "contents")]
270pub enum LeanStatus {
271    #[default]
272    Invalid,
273    /// The proof was checked when the user-written lean files had the given digest.
274    Valid(u64),
275}
276
277#[derive(Serialize, Deserialize, Debug, Clone)]
278#[serde(bound(deserialize = "Tag: FromStr", serialize = "Tag: ToString"))]
279pub struct VerificationResult<Tag> {
280    pub status: FixpointStatus<Tag>,
281    pub solution: Vec<KVarBind>,
282    #[serde(rename = "nonCutsSolution")]
283    pub non_cuts_solution: Vec<KVarBind>,
284    #[serde(default)]
285    pub lean_status: LeanStatus,
286}
287
288#[derive(Serialize, Deserialize, Debug, Clone)]
289pub struct KVarBind {
290    pub kvar: String,
291    pub val: String,
292}
293
294impl KVarBind {
295    pub fn dump(&self) -> String {
296        format!("{} := {}", self.kvar, self.val)
297    }
298}
299
300impl<Tag> FixpointStatus<Tag> {
301    pub fn is_safe(&self) -> bool {
302        matches!(self, FixpointStatus::Safe(_))
303    }
304
305    pub fn merge(self, other: FixpointStatus<Tag>) -> Self {
306        use FixpointStatus as FR;
307        match (self, other) {
308            (FR::Safe(stats1), FR::Safe(stats2)) => FR::Safe(stats1.merge(&stats2)),
309            (FR::Safe(stats1), FR::Unsafe(stats2, errors)) => {
310                FR::Unsafe(stats1.merge(&stats2), errors)
311            }
312            (FR::Unsafe(stats1, mut errors1), FR::Unsafe(stats2, errors2)) => {
313                errors1.extend(errors2);
314                FR::Unsafe(stats1.merge(&stats2), errors1)
315            }
316            (FR::Unsafe(stats1, errors), FR::Safe(stats2)) => {
317                FR::Unsafe(stats1.merge(&stats2), errors)
318            }
319            (FR::Crash(info1), FR::Crash(info2)) => FR::Crash(info1.merge(info2)),
320            (FR::Crash(info), _) => FR::Crash(info),
321            (_, FR::Crash(info)) => FR::Crash(info),
322        }
323    }
324}
325
326#[derive(Debug, Clone)]
327pub struct Error<Tag> {
328    pub id: i32,
329    pub tag: Tag,
330}
331
332#[derive(Debug, Serialize, Deserialize, Default, Clone)]
333#[serde(rename_all = "camelCase")]
334pub struct Stats {
335    pub num_cstr: i32,
336    pub num_iter: i32,
337    pub num_chck: i32,
338    pub num_vald: i32,
339}
340
341impl Stats {
342    pub fn merge(&self, other: &Stats) -> Self {
343        Stats {
344            num_cstr: self.num_cstr + other.num_cstr,
345            num_iter: self.num_iter + other.num_iter,
346            num_chck: self.num_chck + other.num_chck,
347            num_vald: self.num_vald + other.num_vald,
348        }
349    }
350}
351
352#[derive(Serialize, Deserialize, Debug, Clone)]
353pub struct CrashInfo(Vec<serde_json::Value>);
354
355impl CrashInfo {
356    pub fn merge(self, other: CrashInfo) -> Self {
357        let mut v = self.0;
358        v.extend(other.0);
359        CrashInfo(v)
360    }
361}
362
363#[derive_where(Debug, Clone, Hash)]
364pub struct KVarDecl<T: Types> {
365    pub kvid: T::KVar,
366    pub sorts: Vec<Sort<T>>,
367    /// Number of leading arguments in `sorts` that are self arguments. Fixpoint only instantiates
368    /// qualifiers whose self parameters are bound to self arguments, so a kvar with no self
369    /// arguments can only be solved to `true` or `false`.
370    pub self_args: usize,
371}
372
373impl<T: Types> Task<T> {
374    pub fn hash_with_default(&self) -> u64 {
375        let mut hasher = DefaultHasher::new();
376        self.hash(&mut hasher);
377        hasher.finish()
378    }
379
380    /// Runs the task. The timeout and executables are ignored by the rust implementation, which
381    /// uses z3 as a library.
382    #[cfg(feature = "rust-fixpoint")]
383    pub fn run(
384        &self,
385        _timeout: Option<Duration>,
386        _fixpoint: Option<&Path>,
387        _solver: Option<&Path>,
388    ) -> Result<VerificationResult<T::Tag>, FixpointError> {
389        let mut cstr_with_env = ConstraintWithEnv::new(
390            self.data_decls.clone(),
391            self.kvars.clone(),
392            self.qualifiers.clone(),
393            self.constants.clone(),
394            self.constraint.clone(),
395        );
396        Ok(VerificationResult {
397            status: cstr_with_env.is_satisfiable(),
398            solution: vec![],
399            non_cuts_solution: vec![],
400            lean_status: LeanStatus::default(),
401        })
402    }
403
404    /// Runs the task by calling the `fixpoint` executable, which runs the `solver` executable for
405    /// [`Task::solver`]. Either is looked up in `PATH` if not given. If `timeout` is given and
406    /// fixpoint doesn't finish in time, the process is killed and [`FixpointError::Timeout`] is
407    /// returned.
408    #[cfg(not(feature = "rust-fixpoint"))]
409    pub fn run(
410        &self,
411        timeout: Option<Duration>,
412        fixpoint: Option<&Path>,
413        solver: Option<&Path>,
414    ) -> Result<VerificationResult<T::Tag>, FixpointError> {
415        let mut command = Command::new(fixpoint.unwrap_or(Path::new("fixpoint")));
416        if let Some(solver) = solver {
417            command.arg(format!("--solver-path={}", solver.display()));
418        }
419        let mut child = command
420            .arg("-q")
421            .arg("--stdin")
422            .arg("--sorted-solution")
423            .arg("--json")
424            .arg("--allowho")
425            .arg("--allowhoqs")
426            .arg(format!("--solver={}", self.solver))
427            .stdin(Stdio::piped())
428            .stdout(Stdio::piped())
429            .stderr(Stdio::piped())
430            .spawn()?;
431        let mut stdin = None;
432        std::mem::swap(&mut stdin, &mut child.stdin);
433        {
434            let mut w = BufWriter::new(stdin.unwrap());
435            // Use compact formatting to reduce overhead when communicating with fixpoint
436            writeln!(w, "{}", format::CompactTask(self))?;
437        }
438
439        let mut control = child.controlled_with_output();
440        if let Some(timeout) = timeout {
441            control = control.time_limit(timeout).terminate_for_timeout();
442        }
443        let out = control.wait()?.ok_or(FixpointError::Timeout)?;
444
445        serde_json::from_slice(&out.stdout).map_err(|err| {
446            // If we fail to parse stdout fixpoint may have outputed something to stderr
447            // so use that for the error instead
448            if !out.stderr.is_empty() {
449                let stderr = std::str::from_utf8(&out.stderr)
450                    .unwrap_or("fixpoint exited with a non-zero return code");
451                FixpointError::Io(io::Error::other(stderr))
452            } else {
453                FixpointError::Io(err.into())
454            }
455        })
456    }
457}
458
459impl<T: Types> KVarDecl<T> {
460    pub fn new(kvid: T::KVar, sorts: Vec<Sort<T>>, self_args: usize) -> Self {
461        Self { kvid, sorts, self_args }
462    }
463}
464
465#[derive(Serialize, Deserialize)]
466struct ErrorInner(i32, String);
467
468impl<Tag: ToString> Serialize for Error<Tag> {
469    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
470    where
471        S: serde::Serializer,
472    {
473        ErrorInner(self.id, self.tag.to_string()).serialize(serializer)
474    }
475}
476
477impl<'de, Tag: FromStr> Deserialize<'de> for Error<Tag> {
478    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
479    where
480        D: serde::Deserializer<'de>,
481    {
482        let ErrorInner(id, tag) = Deserialize::deserialize(deserializer)?;
483        let tag = tag
484            .parse()
485            .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(&tag), &"valid tag"))?;
486        Ok(Error { id, tag })
487    }
488}
489
490#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
491#[cfg_attr(feature = "nightly", derive(Encodable, Decodable))]
492pub enum ThyFunc {
493    // STRINGS
494    StrLen,
495    StrConcat,
496    StrPrefixOf,
497    StrSuffixOf,
498    StrContains,
499
500    // BIT VECTORS
501    BvZeroExtend(u8),
502    BvSignExtend(u8),
503    IntToBv8,
504    Bv8ToInt,
505    IntToBv32,
506    Bv32ToInt,
507    IntToBv64,
508    Bv64ToInt,
509    IntToBv128,
510    Bv128ToInt,
511    BvUle,
512    BvSle,
513    BvUge,
514    BvSge,
515    BvUdiv,
516    BvSdiv,
517    BvSrem,
518    BvUrem,
519    BvLshr,
520    BvAshr,
521    BvAnd,
522    BvOr,
523    BvXor,
524    BvNot,
525    BvAdd,
526    BvNeg,
527    BvSub,
528    BvMul,
529    BvShl,
530    BvUgt,
531    BvSgt,
532    BvUlt,
533    BvSlt,
534
535    // SETS
536    /// Make an empty set
537    SetEmpty,
538    /// Make a singleton set
539    SetSng,
540    /// Set union
541    SetCup,
542    /// Set intersection
543    SetCap,
544    /// Set difference
545    SetDif,
546    /// Subset
547    SetSub,
548    /// Set membership
549    SetMem,
550
551    // MAPS
552    /// Create a map where all keys point to a value
553    MapDefault,
554    /// Select a key in a map
555    MapSelect,
556    /// Store a key value pair in a map
557    MapStore,
558}
559
560impl ThyFunc {
561    pub const ALL: [ThyFunc; 46] = [
562        ThyFunc::StrLen,
563        ThyFunc::StrConcat,
564        ThyFunc::StrPrefixOf,
565        ThyFunc::StrSuffixOf,
566        ThyFunc::StrContains,
567        ThyFunc::IntToBv8,
568        ThyFunc::Bv8ToInt,
569        ThyFunc::IntToBv32,
570        ThyFunc::Bv32ToInt,
571        ThyFunc::IntToBv64,
572        ThyFunc::Bv64ToInt,
573        ThyFunc::IntToBv128,
574        ThyFunc::Bv128ToInt,
575        ThyFunc::BvAdd,
576        ThyFunc::BvNeg,
577        ThyFunc::BvSub,
578        ThyFunc::BvShl,
579        ThyFunc::BvLshr,
580        ThyFunc::BvAshr,
581        ThyFunc::BvMul,
582        ThyFunc::BvUdiv,
583        ThyFunc::BvSdiv,
584        ThyFunc::BvUrem,
585        ThyFunc::BvSrem,
586        ThyFunc::BvAnd,
587        ThyFunc::BvOr,
588        ThyFunc::BvXor,
589        ThyFunc::BvNot,
590        ThyFunc::BvUle,
591        ThyFunc::BvSle,
592        ThyFunc::BvUge,
593        ThyFunc::BvSge,
594        ThyFunc::BvUgt,
595        ThyFunc::BvSgt,
596        ThyFunc::BvUlt,
597        ThyFunc::BvSlt,
598        ThyFunc::SetEmpty,
599        ThyFunc::SetSng,
600        ThyFunc::SetCup,
601        ThyFunc::SetMem,
602        ThyFunc::SetCap,
603        ThyFunc::SetDif,
604        ThyFunc::SetSub,
605        ThyFunc::MapDefault,
606        ThyFunc::MapSelect,
607        ThyFunc::MapStore,
608    ];
609}
610
611impl fmt::Display for ThyFunc {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        match self {
614            ThyFunc::StrLen => write!(f, "strLen"),
615            ThyFunc::StrConcat => write!(f, "strConcat"),
616            ThyFunc::StrPrefixOf => write!(f, "strPrefixOf"),
617            ThyFunc::StrSuffixOf => write!(f, "strSuffixOf"),
618            ThyFunc::StrContains => write!(f, "strContains"),
619            ThyFunc::BvZeroExtend(size) => {
620                // `app` is a hack in liquid-fixpoint used to implement indexed identifiers
621                write!(f, "app (_ zero_extend {size})")
622            }
623            ThyFunc::BvSignExtend(size) => write!(f, "app (_ sign_extend {size})"),
624            ThyFunc::IntToBv32 => write!(f, "int_to_bv32"),
625            ThyFunc::Bv32ToInt => write!(f, "bv32_to_int"),
626            ThyFunc::IntToBv8 => write!(f, "int_to_bv8"),
627            ThyFunc::Bv8ToInt => write!(f, "bv8_to_int"),
628            ThyFunc::IntToBv64 => write!(f, "int_to_bv64"),
629            ThyFunc::Bv64ToInt => write!(f, "bv64_to_int"),
630            ThyFunc::IntToBv128 => write!(f, "int_to_bv128"),
631            ThyFunc::Bv128ToInt => write!(f, "bv128_to_int"),
632            ThyFunc::BvUle => write!(f, "bvule"),
633            ThyFunc::BvSle => write!(f, "bvsle"),
634            ThyFunc::BvUge => write!(f, "bvuge"),
635            ThyFunc::BvSge => write!(f, "bvsge"),
636            ThyFunc::BvUdiv => write!(f, "bvudiv"),
637            ThyFunc::BvSdiv => write!(f, "bvsdiv"),
638            ThyFunc::BvUrem => write!(f, "bvurem"),
639            ThyFunc::BvSrem => write!(f, "bvsrem"),
640            ThyFunc::BvLshr => write!(f, "bvlshr"),
641            ThyFunc::BvAshr => write!(f, "bvashr"),
642            ThyFunc::BvAnd => write!(f, "bvand"),
643            ThyFunc::BvOr => write!(f, "bvor"),
644            ThyFunc::BvXor => write!(f, "bvxor"),
645            ThyFunc::BvNot => write!(f, "bvnot"),
646            ThyFunc::BvAdd => write!(f, "bvadd"),
647            ThyFunc::BvNeg => write!(f, "bvneg"),
648            ThyFunc::BvSub => write!(f, "bvsub"),
649            ThyFunc::BvMul => write!(f, "bvmul"),
650            ThyFunc::BvShl => write!(f, "bvshl"),
651            ThyFunc::BvUgt => write!(f, "bvugt"),
652            ThyFunc::BvSgt => write!(f, "bvsgt"),
653            ThyFunc::BvUlt => write!(f, "bvult"),
654            ThyFunc::BvSlt => write!(f, "bvslt"),
655            ThyFunc::SetEmpty => write!(f, "Set_empty"),
656            ThyFunc::SetSng => write!(f, "Set_sng"),
657            ThyFunc::SetCup => write!(f, "Set_cup"),
658            ThyFunc::SetCap => write!(f, "Set_cap"),
659            ThyFunc::SetDif => write!(f, "Set_dif"),
660            ThyFunc::SetMem => write!(f, "Set_mem"),
661            ThyFunc::SetSub => write!(f, "Set_sub"),
662            ThyFunc::MapDefault => write!(f, "Map_default"),
663            ThyFunc::MapSelect => write!(f, "Map_select"),
664            ThyFunc::MapStore => write!(f, "Map_store"),
665        }
666    }
667}
668
669impl FromStr for ThyFunc {
670    type Err = String;
671    fn from_str(s: &str) -> Result<Self, Self::Err> {
672        match s {
673            "strLen" => Ok(ThyFunc::StrLen),
674            "int_to_bv32" => Ok(ThyFunc::IntToBv32),
675            "bv32_to_int" => Ok(ThyFunc::Bv32ToInt),
676            "int_to_bv8" => Ok(ThyFunc::IntToBv8),
677            "bv8_to_int" => Ok(ThyFunc::Bv8ToInt),
678            "int_to_bv64" => Ok(ThyFunc::IntToBv64),
679            "bv64_to_int" => Ok(ThyFunc::Bv64ToInt),
680            "int_to_bv128" => Ok(ThyFunc::IntToBv128),
681            "bv128_to_int" => Ok(ThyFunc::Bv128ToInt),
682            "bvule" => Ok(ThyFunc::BvUle),
683            "bvsle" => Ok(ThyFunc::BvSle),
684            "bvuge" => Ok(ThyFunc::BvUge),
685            "bvsge" => Ok(ThyFunc::BvSge),
686            "bvudiv" => Ok(ThyFunc::BvUdiv),
687            "bvsdiv" => Ok(ThyFunc::BvSdiv),
688            "bvurem" => Ok(ThyFunc::BvUrem),
689            "bvsrem" => Ok(ThyFunc::BvSrem),
690            "bvlshr" => Ok(ThyFunc::BvLshr),
691            "bvashr" => Ok(ThyFunc::BvAshr),
692            "bvand" => Ok(ThyFunc::BvAnd),
693            "bvor" => Ok(ThyFunc::BvOr),
694            "bvxor" => Ok(ThyFunc::BvXor),
695            "bvnot" => Ok(ThyFunc::BvNot),
696            "bvadd" => Ok(ThyFunc::BvAdd),
697            "bvneg" => Ok(ThyFunc::BvNeg),
698            "bvsub" => Ok(ThyFunc::BvSub),
699            "bvmul" => Ok(ThyFunc::BvMul),
700            "bvshl" => Ok(ThyFunc::BvShl),
701            "bvugt" => Ok(ThyFunc::BvUgt),
702            "bvsgt" => Ok(ThyFunc::BvSgt),
703            "bvult" => Ok(ThyFunc::BvUlt),
704            "bvslt" => Ok(ThyFunc::BvSlt),
705            "Set_empty" => Ok(ThyFunc::SetEmpty),
706            "Set_sng" => Ok(ThyFunc::SetSng),
707            "Set_cup" => Ok(ThyFunc::SetCup),
708            "Set_mem" => Ok(ThyFunc::SetMem),
709            "Map_default" => Ok(ThyFunc::MapDefault),
710            "Map_select" => Ok(ThyFunc::MapSelect),
711            "Map_store" => Ok(ThyFunc::MapStore),
712            // TODO: (ck) Fix this?
713            // NOTE: (ck) There isn't a straightforward way to translate
714            // the name of a Z3 node to the BvZeroExtend and BvSignExtend,
715            // so this is a partial parse.
716            _ => Err(format!("Unexpected ThyFunc {}", s)),
717        }
718    }
719}