Skip to main content

leanfran_build/
lock.rs

1//! The lockfile `leanfran.lock`: the items each model was extracted from, with the hashes of
2//! their tokens, and the state of the proof of each obligation.
3
4use serde::Deserialize;
5use std::fmt::Write;
6use std::path::Path;
7
8/// The version of the lockfile format.
9pub const LOCK_VERSION: u32 = 1;
10
11#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
12pub struct Lock {
13    pub version: u32,
14    #[serde(default)]
15    pub aeneas: String,
16    #[serde(default)]
17    pub charon: String,
18    #[serde(default)]
19    pub model: Vec<Model>,
20}
21
22#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
23pub struct Model {
24    /// The unit name of the Rust function (`crate::sort::insert_sorted`).
25    pub rust: String,
26    /// The Lean name of the model.
27    pub lean: String,
28    /// The types of `instances` of a generic function, as written (without spaces).
29    #[serde(default)]
30    pub instances: Vec<String>,
31    #[serde(default)]
32    pub items: Vec<LockItem>,
33    #[serde(default)]
34    pub obligation: Vec<Obligation>,
35}
36
37#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
38pub struct LockItem {
39    pub rust: String,
40    pub hash: String,
41}
42
43#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
44pub struct Obligation {
45    pub label: String,
46    /// The Lean name of the spec.
47    pub spec: String,
48    /// The module path of the `lean!` block defining the spec (`crate::spec::sorting`).
49    #[serde(default)]
50    pub spec_block: String,
51    /// `sha256:<cache key>` of that block (without the csimp replacements), or the hash of the
52    /// generated function, when the obligation was extracted.
53    #[serde(default)]
54    pub spec_hash: String,
55    /// SHA-256 of the statement of the obligation and the spec key.
56    pub hash: String,
57    /// `proved`, `sorry`, `axioms`, `missing`, `mismatch`, `failed` or `unchecked`.
58    pub status: String,
59    #[serde(default)]
60    pub axioms: Vec<String>,
61    /// `lean/Proofs/Sort.lean:14`: the declaration of the proof.
62    #[serde(default)]
63    pub proof: String,
64}
65
66impl Obligation {
67    /// `<model>.obligation.<label>`.
68    pub fn statement(&self, model: &str) -> String {
69        format!("{model}.obligation.{}", self.label)
70    }
71
72    /// `<model>.proof.<label>`.
73    pub fn theorem(&self, model: &str) -> String {
74        format!("{model}.proof.{}", self.label)
75    }
76}
77
78fn quote(s: &str) -> String {
79    let mut out = String::from("\"");
80    for c in s.chars() {
81        match c {
82            '"' => out.push_str("\\\""),
83            '\\' => out.push_str("\\\\"),
84            '\n' => out.push_str("\\n"),
85            c => out.push(c),
86        }
87    }
88    out.push('"');
89    out
90}
91
92impl Lock {
93    /// Reads `path`; a missing file is an empty lockfile.
94    pub fn read(path: &Path) -> Result<Lock, String> {
95        let text = match std::fs::read_to_string(path) {
96            Ok(t) => t,
97            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
98                return Ok(Lock {
99                    version: LOCK_VERSION,
100                    ..Lock::default()
101                })
102            }
103            Err(e) => return Err(format!("{}: {e}", path.display())),
104        };
105        let lock: Lock = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
106        if lock.version != LOCK_VERSION {
107            return Err(format!(
108                "{}: version {} is not supported (this leanfran writes version {LOCK_VERSION})",
109                path.display(),
110                lock.version
111            ));
112        }
113        Ok(lock)
114    }
115
116    pub fn model(&self, rust: &str) -> Option<&Model> {
117        self.model.iter().find(|m| m.rust == rust)
118    }
119
120    /// The TOML text of the lockfile.
121    pub fn to_toml(&self) -> String {
122        let mut s = String::new();
123        let _ = writeln!(s, "version = {}", self.version);
124        let _ = writeln!(s, "aeneas = {}", quote(&self.aeneas));
125        let _ = writeln!(s, "charon = {}", quote(&self.charon));
126        for m in &self.model {
127            let _ = writeln!(s, "\n[[model]]");
128            let _ = writeln!(s, "rust = {}", quote(&m.rust));
129            let _ = writeln!(s, "lean = {}", quote(&m.lean));
130            if !m.instances.is_empty() {
131                let ts: Vec<String> = m.instances.iter().map(|t| quote(t)).collect();
132                let _ = writeln!(s, "instances = [{}]", ts.join(", "));
133            }
134            let _ = writeln!(s, "items = [");
135            for i in &m.items {
136                let _ = writeln!(
137                    s,
138                    "  {{ rust = {}, hash = {} }},",
139                    quote(&i.rust),
140                    quote(&i.hash)
141                );
142            }
143            let _ = writeln!(s, "]");
144            for o in &m.obligation {
145                let _ = writeln!(s, "\n[[model.obligation]]");
146                let _ = writeln!(s, "label = {}", quote(&o.label));
147                let _ = writeln!(s, "spec = {}", quote(&o.spec));
148                let _ = writeln!(s, "spec_block = {}", quote(&o.spec_block));
149                let _ = writeln!(s, "spec_hash = {}", quote(&o.spec_hash));
150                let _ = writeln!(s, "hash = {}", quote(&o.hash));
151                let _ = writeln!(s, "status = {}", quote(&o.status));
152                let axioms: Vec<String> = o.axioms.iter().map(|a| quote(a)).collect();
153                let _ = writeln!(s, "axioms = [{}]", axioms.join(", "));
154                let _ = writeln!(s, "proof = {}", quote(&o.proof));
155            }
156        }
157        s
158    }
159}