liquid_fixpoint/
z3_subprocess.rs1use std::{
5 io::{self, BufRead, BufReader, Read as _, Write as _},
6 path::Path,
7 process::{Child, ChildStdin, ChildStdout, Command, Stdio},
8 sync::{Arc, Mutex},
9 thread::JoinHandle,
10};
11
12use crate::sexp::{Atom, Parser, Sexp};
13
14#[derive(Debug)]
15pub(crate) enum Z3Error {
16 Io(io::Error),
17 Timeout,
18}
19
20impl From<io::Error> for Z3Error {
21 fn from(err: io::Error) -> Self {
22 Self::Io(err)
23 }
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub(crate) enum SatStatus {
28 Sat,
29 Unsat,
30 Unknown,
31}
32
33struct Response {
34 stdout: String,
35 stderr: String,
36}
37
38pub(crate) struct Z3Subprocess {
39 child: Child,
40 stdin: Option<ChildStdin>,
41 stdout: BufReader<ChildStdout>,
42 stderr: Arc<Mutex<Vec<u8>>>,
43 stderr_reader: Option<JoinHandle<()>>,
44 request_id: usize,
45}
46
47impl Z3Subprocess {
48 pub(crate) fn new(z3: Option<&Path>) -> io::Result<Self> {
50 let mut child = Command::new(z3.unwrap_or(Path::new("z3")))
51 .args(["-smt2", "-in"])
52 .stdin(Stdio::piped())
53 .stdout(Stdio::piped())
54 .stderr(Stdio::piped())
55 .spawn()?;
56 let stdin = child.stdin.take().expect("Z3 stdin is piped");
57 let stdout = child.stdout.take().expect("Z3 stdout is piped");
58 let mut child_stderr = child.stderr.take().expect("Z3 stderr is piped");
59 let stderr = Arc::new(Mutex::new(Vec::new()));
60 let stderr_buf = Arc::clone(&stderr);
61 let stderr_reader = std::thread::spawn(move || {
62 let mut chunk = [0; 4096];
63 loop {
64 match child_stderr.read(&mut chunk) {
65 Ok(0) | Err(_) => break,
66 Ok(len) => stderr_buf.lock().unwrap().extend_from_slice(&chunk[..len]),
67 }
68 }
69 });
70 Ok(Self {
71 child,
72 stdin: Some(stdin),
73 stdout: BufReader::new(stdout),
74 stderr,
75 stderr_reader: Some(stderr_reader),
76 request_id: 0,
77 })
78 }
79
80 fn request(&mut self, commands: &str) -> io::Result<Response> {
81 let marker = format!("__flux_z3_end_{}__", self.request_id);
82 self.request_id += 1;
83 self.stderr.lock().unwrap().clear();
84 let stdin = self.stdin.as_mut().expect("Z3 stdin is open");
85 writeln!(stdin, "{commands}")?;
86 writeln!(stdin, "(echo \"{marker}\")")?;
87 stdin.flush()?;
88
89 let mut response = String::new();
91 loop {
92 let mut line = String::new();
93 match self.stdout.read_line(&mut line)? {
94 0 => {
95 let status = self.child.try_wait()?.and_then(|status| status.code());
96 let stderr = self.take_stderr();
97 panic!(
98 "Z3 closed stdout before the response marker (status {status:?}); stdout: {response:?}; stderr: {stderr:?}"
99 );
100 }
101 _ if line.trim() == marker => {
102 return Ok(Response { stdout: response, stderr: self.take_stderr() });
103 }
104 _ => response.push_str(&line),
105 }
106 }
107 }
108
109 fn execute(&mut self, commands: &str) -> io::Result<()> {
110 let Response { stdout, stderr } = self.request(commands)?;
111 assert!(
112 stdout.trim().is_empty(),
113 "unexpected Z3 setup response; commands: {commands:?}; stdout: {stdout:?}; stderr: {stderr:?}"
114 );
115 Ok(())
116 }
117
118 pub(crate) fn check_sat(&mut self, setup: &str) -> Result<SatStatus, Z3Error> {
121 let Response { stdout, stderr } =
122 self.request(&format!("(push)\n{setup}\n(check-sat)\n(pop)"))?;
123 match stdout.trim() {
124 "sat" => Ok(SatStatus::Sat),
125 "unsat" => Ok(SatStatus::Unsat),
126 "unknown" => Ok(SatStatus::Unknown),
127 _ if is_timeout(&stdout) => Err(Z3Error::Timeout),
128 _ => panic!("unexpected Z3 status response; stdout: {stdout:?}; stderr: {stderr:?}"),
129 }
130 }
131
132 pub(crate) fn apply(&mut self, setup: &str, tactic: &str) -> Result<Vec<Vec<Sexp>>, Z3Error> {
135 let Response { stdout, stderr } =
136 self.request(&format!("(push)\n{setup}\n(apply {tactic})\n(pop)"))?;
137 if is_timeout(&stdout) {
138 return Err(Z3Error::Timeout);
139 }
140 Ok(parse_goals(&stdout, &stderr))
141 }
142
143 pub(crate) fn scoped<R, E>(
144 &mut self,
145 setup: &str,
146 f: impl FnOnce(&mut Self) -> Result<R, E>,
147 ) -> Result<R, E>
148 where
149 E: From<Z3Error> + From<io::Error>,
150 {
151 self.execute(&format!("(push)\n{setup}"))?;
152 let result = f(self);
153 let pop = self.execute("(pop)");
154 match result {
155 Err(err) => Err(err),
156 Ok(value) => pop.map(|_| value).map_err(E::from),
157 }
158 }
159
160 pub(crate) fn reset(&mut self, declarations: &str) -> io::Result<()> {
161 self.execute(&format!("(reset)\n{declarations}"))
162 }
163
164 fn take_stderr(&self) -> String {
165 let bytes = std::mem::take(&mut *self.stderr.lock().unwrap());
166 String::from_utf8_lossy(&bytes).into_owned()
167 }
168}
169
170impl Drop for Z3Subprocess {
171 fn drop(&mut self) {
172 self.stdin.take();
173 let _ = self.child.wait();
174 if let Some(reader) = self.stderr_reader.take() {
175 let _ = reader.join();
176 }
177 }
178}
179
180fn is_timeout(stdout: &str) -> bool {
181 let output = stdout.trim().to_ascii_lowercase();
182 output.starts_with("(error ") && output.contains("canceled")
184}
185
186fn parse_goals(stdout: &str, stderr: &str) -> Vec<Vec<Sexp>> {
187 let parsed = Parser::new(stdout).parse_all().unwrap_or_else(|err| {
188 panic!("failed to parse Z3 goals response: {err:?}; stdout: {stdout:?}; stderr: {stderr:?}")
189 });
190 let [Sexp::List(items)] = parsed.as_slice() else {
191 panic!("expected one `(goals ...)` response; stdout: {stdout:?}; stderr: {stderr:?}");
192 };
193 if atom_symbol(items.first()) != Some("goals") {
194 panic!(
195 "Z3 goals response does not start with `goals`; stdout: {stdout:?}; stderr: {stderr:?}"
196 );
197 }
198 items[1..]
199 .iter()
200 .map(|goal| {
201 let Sexp::List(entries) = goal else {
202 panic!("Z3 goal response entry is not a list; entry: {goal:?}; stdout: {stdout:?}; stderr: {stderr:?}");
203 };
204 if atom_symbol(entries.first()) != Some("goal") {
205 panic!("expected `(goal ...)` in Z3 goals response; entry: {goal:?}; stdout: {stdout:?}; stderr: {stderr:?}");
206 }
207 let metadata = entries[1..]
208 .iter()
209 .position(|entry| {
210 atom_symbol(Some(entry)).is_some_and(|name| name.starts_with(':'))
211 })
212 .unwrap_or(entries.len() - 1);
213 entries[1..1 + metadata].to_vec()
214 })
215 .collect()
216}
217
218fn atom_symbol(sexp: Option<&Sexp>) -> Option<&str> {
219 match sexp {
220 Some(Sexp::Atom(Atom::S(symbol))) => Some(symbol),
221 _ => None,
222 }
223}