1use serde::{Deserialize, Serialize};
17use std::collections::BTreeMap;
18
19use crate::output::{AnswerName, Counterexample, FunctionReport, ItfValue, OutcomeName};
20
21pub const VERSION: u32 = 1;
23
24const QUALIFIER_MODEL: &str = "values are the solver's model for one failed or unknown check; Sail does not evaluate them against the source, so they are not a validated concrete counterexample";
25const QUALIFIER_RAW: &str = "the raw model, including every internal constant, is retained in the obligation's counterexample";
26const QUALIFIER_UNKNOWN: &str =
27 "the check's answer was unknown, so the model may be partial or spurious";
28const QUALIFIER_POSITIONAL: &str =
29 "some struct field names were unavailable; those fields are named by declaration position";
30
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "kebab-case", tag = "kind")]
34pub enum Value {
35 Scalar {
37 itf: ItfValue,
39 },
40 Record {
42 constructor: String,
44 fields: Vec<Field>,
46 },
47}
48
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub struct Field {
52 pub name: String,
54 pub value: Value,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct Input {
61 pub name: String,
63 pub smt_name: String,
65 pub sort: String,
67 pub value: Value,
69}
70
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Decoded {
74 pub version: u32,
76 pub function: String,
78 pub obligation: String,
80 pub check: u32,
82 pub answer: Option<AnswerName>,
84 pub inputs: Vec<Input>,
86 pub omitted: usize,
88 pub qualifiers: Vec<String>,
90}
91
92pub type FieldNames = BTreeMap<String, Vec<String>>;
94
95#[must_use]
99pub fn decode(function: &FunctionReport, fields: &FieldNames) -> Option<Decoded> {
100 let (obligation, counterexample) = function
101 .obligations
102 .iter()
103 .flatten()
104 .filter(|o| !o.advisory && o.outcome != OutcomeName::Proved)
105 .find_map(|o| o.counterexample.as_ref().map(|c| (o, c)))?;
106 let answer = obligation
107 .checks
108 .get(usize::try_from(counterexample.check).ok()?)
109 .and_then(|check| check.answer);
110 let mut positional = false;
111 let (mut inputs, omitted) = inputs(counterexample, fields, &mut positional);
112 inputs.sort_by(|a, b| {
113 a.name
114 .cmp(&b.name)
115 .then_with(|| a.smt_name.cmp(&b.smt_name))
116 });
117 let mut qualifiers = vec![QUALIFIER_MODEL, QUALIFIER_RAW];
118 if answer != Some(AnswerName::Sat) {
119 qualifiers.push(QUALIFIER_UNKNOWN);
120 }
121 if positional {
122 qualifiers.push(QUALIFIER_POSITIONAL);
123 }
124 qualifiers.sort_unstable();
125 Some(Decoded {
126 version: VERSION,
127 function: function.function.clone(),
128 obligation: obligation.id.clone(),
129 check: counterexample.check,
130 answer,
131 inputs,
132 omitted,
133 qualifiers: qualifiers.into_iter().map(String::from).collect(),
134 })
135}
136
137fn inputs(
138 counterexample: &Counterexample,
139 fields: &FieldNames,
140 positional: &mut bool,
141) -> (Vec<Input>, usize) {
142 let mut decoded = Vec::new();
143 let mut omitted = 0;
144 for assignment in &counterexample.assignments {
145 let Some(name) = source_name(&assignment.name) else {
146 omitted += 1;
147 continue;
148 };
149 let value = match parse(&assignment.value) {
150 Some(Term::List(items)) => record(&items, fields, positional),
151 _ => None,
152 }
153 .unwrap_or_else(|| Value::Scalar {
154 itf: assignment.itf.clone(),
155 });
156 decoded.push(Input {
157 name: name.to_owned(),
158 smt_name: assignment.name.clone(),
159 sort: assignment.sort.clone(),
160 value,
161 });
162 }
163 (decoded, omitted)
164}
165
166fn source_name(smt: &str) -> Option<&str> {
168 let name = smt.strip_suffix('!')?;
169 let mut chars = name.chars();
170 let first = chars.next()?;
171 ((first.is_ascii_alphabetic() || first == '_')
172 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
173 && name != "_")
174 .then_some(name)
175}
176
177#[derive(Debug, PartialEq, Eq)]
178enum Term {
179 Atom(String),
180 List(Vec<Self>),
181}
182
183fn parse(text: &str) -> Option<Term> {
185 let mut tokens = Vec::new();
186 let mut atom = String::new();
187 for c in text.chars() {
188 if c == '(' || c == ')' || c.is_whitespace() {
189 if !atom.is_empty() {
190 tokens.push(std::mem::take(&mut atom));
191 }
192 if !c.is_whitespace() {
193 tokens.push(c.to_string());
194 }
195 } else if c == '|' || c == '"' {
196 return None;
197 } else {
198 atom.push(c);
199 }
200 }
201 if !atom.is_empty() {
202 tokens.push(atom);
203 }
204 let mut stack: Vec<Vec<Term>> = vec![Vec::new()];
205 for token in tokens {
206 match token.as_str() {
207 "(" => stack.push(Vec::new()),
208 ")" => {
209 let items = stack.pop()?;
210 stack.last_mut()?.push(Term::List(items));
211 }
212 _ => stack.last_mut()?.push(Term::Atom(token)),
213 }
214 }
215 let mut top = stack.pop()?;
216 (stack.is_empty() && top.len() == 1).then(|| top.remove(0))
217}
218
219fn record(items: &[Term], fields: &FieldNames, positional: &mut bool) -> Option<Value> {
221 let (Term::Atom(head), arguments) = items.split_first()? else {
222 return None;
223 };
224 let (path, constructor) = head.rsplit_once("./")?;
225 let (_, path) = path.split_once('!')?;
226 let structure = path.rsplit('.').next()?;
227 if structure != constructor || constructor.is_empty() {
228 return None;
229 }
230 let names = fields
231 .get(constructor)
232 .filter(|names| names.len() == arguments.len());
233 *positional |= names.is_none() && !arguments.is_empty();
234 let fields = arguments
235 .iter()
236 .enumerate()
237 .map(|(index, argument)| {
238 Some(Field {
239 name: names.map_or_else(|| index.to_string(), |names| names[index].clone()),
240 value: argument_value(argument, fields, positional)?,
241 })
242 })
243 .collect::<Option<Vec<_>>>()?;
244 Some(Value::Record {
245 constructor: constructor.to_owned(),
246 fields,
247 })
248}
249
250fn argument_value(term: &Term, fields: &FieldNames, positional: &mut bool) -> Option<Value> {
251 match term {
252 Term::Atom(atom) if atom == "true" || atom == "false" => Some(Value::Scalar {
253 itf: ItfValue::render("Bool", atom),
254 }),
255 Term::Atom(atom) => Some(Value::Scalar {
256 itf: ItfValue::render("Int", atom),
257 }),
258 Term::List(items) => match items.as_slice() {
259 [Term::Atom(minus), Term::Atom(digits)] if minus == "-" => Some(Value::Scalar {
260 itf: ItfValue::render("Int", &format!("(- {digits})")),
261 }),
262 _ => record(items, fields, positional),
263 },
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn only_plain_identifiers_followed_by_a_bang_are_source_names() {
273 for (smt, expected) in [
274 ("x!", Some("x")),
275 ("ret!", Some("ret")),
276 ("_tmp1!", Some("_tmp1")),
277 ("fuel%vstd!seq.group_seq_lemmas.", None),
278 ("TYPE%probe!Row.", None),
279 ("i@0", None),
280 ("$", None),
281 ("SZ", None),
282 ("%%location_label%%0", None),
283 ("_!", None),
284 ("1x!", None),
285 ("a.b!", None),
286 ] {
287 assert_eq!(source_name(smt), expected, "{smt}");
288 }
289 }
290
291 #[test]
292 fn constructor_terms_become_named_or_positional_records() {
293 let fields = FieldNames::from([
294 ("Row".into(), vec!["flag".into(), "count".into()]),
295 ("Outer".into(), vec!["row".into(), "delta".into()]),
296 ]);
297 let scalar = |itf: ItfValue| Value::Scalar { itf };
298 let int = |n: &str| {
299 scalar(ItfValue::BigInt {
300 bigint: n.to_owned(),
301 })
302 };
303 let row = |flag: bool, count: &str, names: [&str; 2]| Value::Record {
304 constructor: "Row".into(),
305 fields: vec![
306 Field {
307 name: names[0].into(),
308 value: scalar(ItfValue::Bool(flag)),
309 },
310 Field {
311 name: names[1].into(),
312 value: int(count),
313 },
314 ],
315 };
316 let mut positional = false;
317 let decode = |text: &str, fields: &FieldNames, positional: &mut bool| match parse(text) {
318 Some(Term::List(items)) => record(&items, fields, positional),
319 _ => None,
320 };
321 assert_eq!(
322 decode("(probe!Row./Row false 3)", &fields, &mut positional),
323 Some(row(false, "3", ["flag", "count"]))
324 );
325 assert!(!positional);
326 assert_eq!(
327 decode(
328 "(probe!m.Outer./Outer (probe!Row./Row true 0) (- 2))",
329 &fields,
330 &mut positional
331 ),
332 Some(Value::Record {
333 constructor: "Outer".into(),
334 fields: vec![
335 Field {
336 name: "row".into(),
337 value: row(true, "0", ["flag", "count"]),
338 },
339 Field {
340 name: "delta".into(),
341 value: int("-2"),
342 },
343 ],
344 })
345 );
346 assert_eq!(
347 decode(
348 "(probe!Row./Row false 3)",
349 &FieldNames::new(),
350 &mut positional
351 ),
352 Some(row(false, "3", ["0", "1"]))
353 );
354 assert!(positional);
355 for malformed in [
356 "(probe!Row./Other false 3)",
357 "(probe!Row./Row false 3",
358 "(probe!Row./Row false 3) extra",
359 "(Row false 3)",
360 "(|probe!Row./Row| false)",
361 "(probe!Row./Row (f 1))",
362 ] {
363 assert_eq!(
364 decode(malformed, &fields, &mut positional),
365 None,
366 "{malformed}"
367 );
368 }
369 }
370}