Skip to main content

leanfran_build/
lib.rs

1//! Build script support of leanfran.
2//!
3//! The `main` of the build script (`build.rs`):
4//!
5//! ```no_run
6//! leanfran_build::Builder::new().compile().unwrap();
7//! ```
8//!
9//! [`Builder::compile`] finds the `lean!` blocks in `src/**/*.rs`, and for each block copies the
10//! cached Rust module from `.leanfran/cache/` to `OUT_DIR`. Blocks without a cache entry are
11//! written into the crate's Lean package (`lean/LeanRustGen/Embed/`), checked with `lake build`
12//! and generated with `leanfran module generate`.
13//!
14//! It also compares the `#[leanfran::model]` functions with the lockfile `leanfran.lock`
15//! (without Lean or Charon), reports the stale and unextracted obligations with
16//! `cargo:warning`, and writes the rustdoc of their states.
17//!
18//! Environment variables: `LEANFRAN_CLI` (the `leanfran` executable, default from `PATH`),
19//! `LEANFRAN_OFFLINE=1` (use the cache only), `LEANFRAN_EXTRACTING=1` (set by
20//! `cargo leanfran extract`: use the cache only and skip the lockfile),
21//! `LEANFRAN_REQUIRE=proved` (fail unless every obligation is proved, as
22//! `[package.metadata.leanfran] require = "proved"`).
23
24pub mod gen;
25pub mod lock;
26pub mod model;
27pub mod syntax;
28pub mod verify;
29
30use model::file_module;
31use sha2::{Digest, Sha256};
32use std::collections::{BTreeMap, BTreeSet, HashMap};
33use std::fmt;
34use std::fs;
35use std::path::{Path, PathBuf};
36use std::process::Command;
37use syn::visit::Visit;
38use syntax::{file_hash, normalize_path, LeanBlock};
39
40/// Version of the generated code: the `leanfran --generator-version` this crate works with, and part of every
41/// cache key.
42pub const GENERATOR_VERSION: &str = "5";
43
44/// The Lean toolchain of the crate's Lean package (`lean/lean-toolchain`).
45pub const LEAN_TOOLCHAIN: &str = "leanprover/lean4:v4.35.0";
46
47/// `LeanRust/Instances.lean` of leanfran's Lean library: the `rust_instances` command, written
48/// to `lean/LeanRustGen/Lib/Instances.lean` for the `lean!` blocks that use it.
49pub const INSTANCES_LEAN: &str = include_str!("../lean/Instances.lean");
50
51/// `LeanRust/AeneasModel.lean` of leanfran's Lean library: the classes of the laws of Rust's
52/// traits over Aeneas's models, written to `lean/LeanRustGen/Lib/AeneasModel.lean` by
53/// `cargo leanfran extract` for the obligations of generic functions.
54pub const AENEAS_MODEL_LEAN: &str = include_str!("../lean/AeneasModel.lean");
55
56/// The module of [`INSTANCES_LEAN`] in the crate's Lean package.
57pub const INSTANCES_MODULE: &str = "LeanRustGen.Lib.Instances";
58
59/// An error of the build script, with a message for the user.
60pub struct Error {
61    message: String,
62}
63
64impl Error {
65    fn new(message: impl Into<String>) -> Self {
66        Error {
67            message: message.into(),
68        }
69    }
70}
71
72impl fmt::Display for Error {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(&self.message)
75    }
76}
77
78impl fmt::Debug for Error {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.write_str(&self.message)
81    }
82}
83
84impl std::error::Error for Error {}
85
86impl From<std::io::Error> for Error {
87    fn from(e: std::io::Error) -> Self {
88        Error::new(e.to_string())
89    }
90}
91
92/// A `lean!` block found in the crate.
93#[derive(Debug, Clone)]
94pub struct Block {
95    /// Path of the Rust file relative to the crate root (`src/lib.rs`).
96    pub file: String,
97    /// [`syntax::file_hash`] of `file`.
98    pub file_hash: String,
99    /// Name of the Rust module (and of the Lean namespace).
100    pub name: String,
101    /// Rust module path of the block (`crate::geometry::shapes` as segments after `crate`).
102    pub path: Vec<String>,
103    pub imports: Vec<String>,
104    /// The blocks this one uses, as module paths.
105    pub uses: Vec<Vec<String>>,
106    /// The Lean source as written (before removing the common indentation).
107    pub source: String,
108    /// Line of the Rust file where the source literal starts.
109    pub line: usize,
110}
111
112impl Block {
113    /// `LeanRustGen.Embed.<crate>.h<file hash>.<name>`.
114    pub fn lean_module(&self, crate_ident: &str) -> String {
115        format!(
116            "LeanRustGen.Embed.{crate_ident}.h{}.{}",
117            self.file_hash, self.name
118        )
119    }
120
121    /// Path of the Lean file in the Lean package.
122    pub fn lean_file(&self, crate_ident: &str) -> PathBuf {
123        Path::new("LeanRustGen")
124            .join("Embed")
125            .join(crate_ident)
126            .join(format!("h{}", self.file_hash))
127            .join(format!("{}.lean", self.name))
128    }
129
130    /// Path of the generated module below `OUT_DIR`.
131    pub fn out_file(&self) -> PathBuf {
132        Path::new("leanfran")
133            .join(&self.file_hash)
134            .join(format!("{}.rs", self.name))
135    }
136
137    /// `true` when the source uses `rust_instances`, which imports [`INSTANCES_MODULE`].
138    pub fn uses_instances(&self) -> bool {
139        self.source.contains("rust_instances")
140    }
141}
142
143/// Configures and runs the build step.
144pub struct Builder {
145    manifest_dir: PathBuf,
146    out_dir: PathBuf,
147    crate_name: String,
148}
149
150impl Default for Builder {
151    fn default() -> Self {
152        Self::new()
153    }
154}
155
156fn env_required(name: &str) -> PathBuf {
157    match std::env::var_os(name) {
158        Some(v) => PathBuf::from(v),
159        None => panic!("leanfran-build: {name} is not set (run from a build script)"),
160    }
161}
162
163impl Builder {
164    /// A builder for the crate of the running build script (`CARGO_MANIFEST_DIR`, `OUT_DIR`,
165    /// `CARGO_PKG_NAME`).
166    pub fn new() -> Self {
167        Builder {
168            manifest_dir: env_required("CARGO_MANIFEST_DIR"),
169            out_dir: env_required("OUT_DIR"),
170            crate_name: std::env::var("CARGO_PKG_NAME")
171                .expect("leanfran-build: CARGO_PKG_NAME is not set"),
172        }
173    }
174
175    /// A builder for an explicit crate directory, output directory and crate name.
176    pub fn with_dirs(
177        manifest_dir: impl Into<PathBuf>,
178        out_dir: impl Into<PathBuf>,
179        crate_name: impl Into<String>,
180    ) -> Self {
181        Builder {
182            manifest_dir: manifest_dir.into(),
183            out_dir: out_dir.into(),
184            crate_name: crate_name.into(),
185        }
186    }
187
188    pub fn crate_ident(&self) -> String {
189        self.crate_name.replace('-', "_")
190    }
191
192    pub fn cache_dir(&self) -> PathBuf {
193        self.manifest_dir.join(".leanfran").join("cache")
194    }
195
196    pub fn lean_dir(&self) -> PathBuf {
197        self.manifest_dir.join("lean")
198    }
199
200    /// The lockfile of the crate.
201    pub fn lock_path(&self) -> PathBuf {
202        self.manifest_dir.join("leanfran.lock")
203    }
204
205    /// The `@[csimp]` replacements `cargo leanfran check` writes.
206    pub fn csimp_path(&self) -> PathBuf {
207        self.lean_dir().join("LeanRustGen").join("Csimp.lean")
208    }
209
210    /// The part of every cache key that depends on the `@[csimp]` replacements.
211    pub fn csimp_key(&self) -> String {
212        match fs::read(self.csimp_path()) {
213            Ok(text) => Sha256::digest(&text)
214                .iter()
215                .map(|b| format!("{b:02x}"))
216                .collect(),
217            Err(_) => String::new(),
218        }
219    }
220
221    /// Generates the Rust modules of all `lean!` blocks of the crate into `OUT_DIR`, and
222    /// compares the modelled functions with the lockfile.
223    pub fn compile(&self) -> Result<(), Error> {
224        println!("cargo:rerun-if-env-changed=LEANFRAN_EXTRACTING");
225        println!("cargo:rerun-if-env-changed=LEANFRAN_OFFLINE");
226        println!("cargo:rerun-if-env-changed=LEANFRAN_CLI");
227        println!("cargo:rerun-if-env-changed=LEANFRAN_REQUIRE");
228        let extracting = std::env::var("LEANFRAN_EXTRACTING").as_deref() == Ok("1");
229        self.check_toolchain()?;
230        let (blocks, files) = self.scan()?;
231        for f in &files {
232            println!("cargo:rerun-if-changed={}", f.display());
233        }
234        let src = self.manifest_dir.join("src");
235        if src.is_dir() {
236            println!("cargo:rerun-if-changed={}", src.display());
237        }
238        let keys = cache_keys(&self.crate_name, &blocks, &self.csimp_key())?;
239        let cache = self.cache_dir();
240        let mut missing = Vec::new();
241        for (i, b) in blocks.iter().enumerate() {
242            let cached = cache.join(format!("{}.rs", keys[i]));
243            if cached.is_file() {
244                write_if_changed(&self.out_dir.join(b.out_file()), &fs::read(&cached)?)?;
245            } else {
246                missing.push(i);
247            }
248        }
249        if !missing.is_empty() && !extracting {
250            if std::env::var("LEANFRAN_OFFLINE").as_deref() == Ok("1") {
251                let names: Vec<String> = missing
252                    .iter()
253                    .map(|&i| {
254                        format!(
255                            "  {} ({}::{})",
256                            blocks[i].file,
257                            module_path_string(&blocks[i].path),
258                            keys[i]
259                        )
260                    })
261                    .collect();
262                return Err(Error::new(format!(
263                    "leanfran-build: LEANFRAN_OFFLINE=1 and these lean! blocks are not in {}:\n{}",
264                    cache.display(),
265                    names.join("\n")
266                )));
267            }
268            self.generate(&blocks, &keys, &missing)?;
269        }
270        if cache.is_dir() {
271            println!("cargo:rerun-if-changed={}", cache.display());
272        }
273        for f in self.lean_user_files() {
274            println!("cargo:rerun-if-changed={}", f.display());
275        }
276        println!("cargo:rerun-if-changed={}", self.lock_path().display());
277        let doc_dir = self.out_dir.join("leanfran").join("doc");
278        fs::create_dir_all(&doc_dir)?;
279        if extracting {
280            return Ok(());
281        }
282        println!(
283            "cargo:rerun-if-changed={}",
284            self.model_dir()
285                .join("FunsExternal_Template.lean")
286                .display()
287        );
288        let offline = std::env::var("LEANFRAN_OFFLINE").as_deref() == Ok("1");
289        self.compile_opaque(&self.scan_items()?, offline)?;
290        self.verify(&blocks, &doc_dir)
291    }
292
293    /// Generates the cache entries of the `blocks` that `select` accepts and that are not
294    /// cached (with `lake build` and `leanfran module generate`).
295    pub fn generate_cache(
296        &self,
297        blocks: &[Block],
298        select: impl Fn(&Block) -> bool,
299    ) -> Result<(), Error> {
300        let keys = cache_keys(&self.crate_name, blocks, &self.csimp_key())?;
301        let cache = self.cache_dir();
302        let missing: Vec<usize> = (0..blocks.len())
303            .filter(|&i| select(&blocks[i]) && !cache.join(format!("{}.rs", keys[i])).is_file())
304            .collect();
305        if missing.is_empty() {
306            return Ok(());
307        }
308        self.generate(blocks, &keys, &missing)
309    }
310
311    fn check_toolchain(&self) -> Result<(), Error> {
312        let file = self.lean_dir().join("lean-toolchain");
313        match fs::read_to_string(&file) {
314            Ok(t) if t.trim() != LEAN_TOOLCHAIN => Err(Error::new(format!(
315                "leanfran-build: {} is `{}`; this leanfran needs `{LEAN_TOOLCHAIN}`",
316                file.display(),
317                t.trim()
318            ))),
319            _ => Ok(()),
320        }
321    }
322
323    /// The modelled functions, opaque functions, `use`s and item hashes of `src/**/*.rs`.
324    pub fn scan_items(&self) -> Result<model::CrateItems, Error> {
325        let mut files = Vec::new();
326        collect_rs(&self.manifest_dir.join("src"), &mut files)?;
327        files.sort();
328        let mut items = model::CrateItems::default();
329        for f in &files {
330            let rel = normalize_path(f.strip_prefix(&self.manifest_dir).unwrap_or(f));
331            let text = fs::read_to_string(f)?;
332            let ast = syn::parse_file(&text)
333                .map_err(|e| Error::new(format!("leanfran-build: cannot parse {rel}: {e}")))?;
334            model::scan_file(&rel, file_module(&rel), &ast, &mut items);
335        }
336        Ok(items)
337    }
338
339    /// The current hashes of the specs: `sha256:<cache key>` of the blocks (without the
340    /// `@[csimp]` replacements) by module path, and the hashes of the other functions by unit
341    /// name.
342    pub fn spec_hashes(
343        &self,
344        blocks: &[Block],
345        items: &model::CrateItems,
346    ) -> Result<BTreeMap<String, String>, Error> {
347        let keys = cache_keys(&self.crate_name, blocks, "")?;
348        let mut out: BTreeMap<String, String> = items.hashes.clone();
349        for (b, k) in blocks.iter().zip(&keys) {
350            out.insert(module_path_string(&b.path), format!("sha256:{k}"));
351        }
352        Ok(out)
353    }
354
355    /// `require = "proved"` of `[package.metadata.leanfran]`, or `LEANFRAN_REQUIRE`.
356    fn require_proved(&self) -> Result<bool, Error> {
357        if let Ok(v) = std::env::var("LEANFRAN_REQUIRE") {
358            return Ok(v == "proved");
359        }
360        let manifest = self.manifest_dir.join("Cargo.toml");
361        let Ok(text) = fs::read_to_string(&manifest) else {
362            return Ok(false);
363        };
364        let value: toml::Value = toml::from_str(&text)
365            .map_err(|e| Error::new(format!("leanfran-build: {}: {e}", manifest.display())))?;
366        let require = value
367            .get("package")
368            .and_then(|p| p.get("metadata"))
369            .and_then(|m| m.get("leanfran"))
370            .and_then(|l| l.get("require"))
371            .and_then(|r| r.as_str());
372        match require {
373            None => Ok(false),
374            Some("proved") => Ok(true),
375            Some(other) => Err(Error::new(format!(
376                "leanfran-build: {}: [package.metadata.leanfran] require = \"{other}\"; the supported value is \"proved\"",
377                manifest.display()
378            ))),
379        }
380    }
381
382    fn verify(&self, blocks: &[Block], doc_dir: &Path) -> Result<(), Error> {
383        let items = self.scan_items()?;
384        if !items.errors.is_empty() {
385            return Err(Error::new(format!(
386                "leanfran-build: invalid #[leanfran::model]:\n{}",
387                items.errors.join("\n")
388            )));
389        }
390        if items.models.is_empty() {
391            return Ok(());
392        }
393        let lock = lock::Lock::read(&self.lock_path()).map_err(Error::new)?;
394        let spec_hashes = self.spec_hashes(blocks, &items)?;
395        let states = verify::states(&items, &lock, &spec_hashes, &self.crate_ident());
396        for m in &states {
397            write_if_changed(&doc_dir.join(&m.doc_file), verify::doc_text(m).as_bytes())?;
398        }
399        for w in verify::warnings(&states) {
400            println!("cargo:warning={w}");
401        }
402        if self.require_proved()? {
403            let bad = verify::not_proved(&states);
404            if !bad.is_empty() {
405                return Err(Error::new(format!(
406                    "leanfran-build: require = \"proved\" and these obligations are not proved:\n  {}",
407                    bad.join("\n  ")
408                )));
409            }
410        }
411        Ok(())
412    }
413
414    /// The `lean!` blocks of `src/**/*.rs` and the scanned files.
415    pub fn scan(&self) -> Result<(Vec<Block>, Vec<PathBuf>), Error> {
416        let mut files = Vec::new();
417        collect_rs(&self.manifest_dir.join("src"), &mut files)?;
418        files.sort();
419        let mut blocks = Vec::new();
420        for f in &files {
421            let rel = normalize_path(f.strip_prefix(&self.manifest_dir).unwrap_or(f));
422            let text = fs::read_to_string(f)?;
423            let ast = syn::parse_file(&text)
424                .map_err(|e| Error::new(format!("leanfran-build: cannot parse {rel}: {e}")))?;
425            let mut v = Scanner {
426                file: rel.clone(),
427                hash: file_hash(&rel),
428                module: file_module(&rel),
429                blocks: Vec::new(),
430                error: None,
431            };
432            v.visit_file(&ast);
433            if let Some(e) = v.error {
434                return Err(e);
435            }
436            blocks.extend(v.blocks);
437        }
438        let mut seen: HashMap<Vec<String>, &Block> = HashMap::new();
439        for b in &blocks {
440            if let Some(o) = seen.insert(b.path.clone(), b) {
441                return Err(Error::new(format!(
442                    "leanfran-build: two lean! blocks define {} ({} and {})",
443                    module_path_string(&b.path),
444                    o.file,
445                    b.file
446                )));
447            }
448        }
449        Ok((blocks, files))
450    }
451
452    fn lean_user_files(&self) -> Vec<PathBuf> {
453        let mut out = Vec::new();
454        let lean = self.lean_dir();
455        if lean.is_dir() {
456            collect_user_files(&lean, &lean, &mut out);
457        }
458        out.sort();
459        out
460    }
461
462    fn ensure_package(&self) -> Result<(), Error> {
463        let lean = self.lean_dir();
464        if lean.join("lakefile.toml").exists() || lean.join("lakefile.lean").exists() {
465            return Ok(());
466        }
467        fs::create_dir_all(&lean)?;
468        let lakefile = format!(
469            "name = \"{}\"\ndefaultTargets = [\"LeanRustGen\"]\n\n[[lean_lib]]\nname = \"LeanRustGen\"\nglobs = [\"LeanRustGen.+\"]\n",
470            self.crate_ident()
471        );
472        fs::write(lean.join("lakefile.toml"), lakefile)?;
473        fs::write(lean.join("lean-toolchain"), format!("{LEAN_TOOLCHAIN}\n"))?;
474        fs::write(lean.join(".gitignore"), "/.lake/\n")?;
475        Ok(())
476    }
477
478    fn generate(&self, blocks: &[Block], keys: &[String], missing: &[usize]) -> Result<(), Error> {
479        let model = self
480            .lean_dir()
481            .join("LeanRustGen")
482            .join("Model")
483            .join(self.crate_ident());
484        if !model.is_dir() {
485            if let Some(&i) = missing
486                .iter()
487                .find(|&&i| depends_on_model(&blocks[i], blocks))
488            {
489                return Err(Error::new(format!(
490                    "leanfran-build: the lean! block {} ({}) imports the model of the crate, which `cargo leanfran extract` writes: run it first",
491                    module_path_string(&blocks[i].path),
492                    blocks[i].file
493                )));
494            }
495        }
496        let cli = std::env::var_os("LEANFRAN_CLI")
497            .map(PathBuf::from)
498            .unwrap_or_else(|| PathBuf::from("leanfran"));
499        let version = run_output(
500            Command::new(&cli).arg("--generator-version"),
501            &cli.display().to_string(),
502        )?;
503        if version.trim() != GENERATOR_VERSION {
504            return Err(Error::new(format!(
505                "leanfran-build: {} generates code of version `{}`; this build needs version `{GENERATOR_VERSION}`",
506                cli.display(),
507                version.trim()
508            )));
509        }
510        self.ensure_package()?;
511        let lean = self.lean_dir();
512        let crate_ident = self.crate_ident();
513        let by_path: HashMap<&[String], &Block> =
514            blocks.iter().map(|b| (b.path.as_slice(), b)).collect();
515        let mut sources = Vec::new();
516        for b in blocks {
517            let used: Vec<&Block> = b.uses.iter().map(|p| by_path[p.as_slice()]).collect();
518            let (text, header_lines, indent) = lean_source(b, &used, &crate_ident);
519            write_if_changed(&lean.join(b.lean_file(&crate_ident)), text.as_bytes())?;
520            sources.push((header_lines, indent));
521        }
522        let lib = lean.join("LeanRustGen").join("Lib").join("Instances.lean");
523        if blocks.iter().any(Block::uses_instances) {
524            write_if_changed(&lib, INSTANCES_LEAN.as_bytes())?;
525        } else if lib.is_file() {
526            fs::remove_file(&lib)?;
527        }
528        prune_dir(
529            &lean.join("LeanRustGen").join("Embed").join(&crate_ident),
530            &blocks
531                .iter()
532                .map(|b| lean.join(b.lean_file(&crate_ident)))
533                .collect(),
534        )?;
535        let csimp = self.csimp_path().is_file();
536        let mut modules: Vec<String> = missing
537            .iter()
538            .map(|&i| blocks[i].lean_module(&crate_ident))
539            .collect();
540        if csimp {
541            modules.push("LeanRustGen.Csimp".to_string());
542        }
543        let build = Command::new("lake")
544            .arg("build")
545            .args(&modules)
546            .current_dir(&lean)
547            .output()
548            .map_err(|e| Error::new(format!("leanfran-build: cannot run lake: {e}")))?;
549        let log = format!(
550            "{}{}",
551            String::from_utf8_lossy(&build.stdout),
552            String::from_utf8_lossy(&build.stderr)
553        );
554        let diagnostics = map_diagnostics(&log, blocks, &sources, &crate_ident);
555        for d in &diagnostics {
556            for (i, line) in d.lines().enumerate() {
557                if i == 0 {
558                    println!("cargo:warning={line}");
559                } else {
560                    println!("cargo:warning=  {line}");
561                }
562            }
563            eprintln!("{d}");
564        }
565        if !build.status.success() {
566            let detail = if diagnostics.is_empty() {
567                log
568            } else {
569                diagnostics.join("\n")
570            };
571            return Err(Error::new(format!(
572                "leanfran-build: Lean rejected the lean! blocks:\n{detail}"
573            )));
574        }
575        let lean_path = run_output(
576            Command::new("lake")
577                .args(["env", "printenv", "LEAN_PATH"])
578                .current_dir(&lean),
579            "lake env",
580        )?;
581        let tmp = self.out_dir.join("leanfran").join("tmp");
582        fs::create_dir_all(&tmp)?;
583        let jobs: Vec<serde_json::Value> = missing
584            .iter()
585            .map(|&i| {
586                let type_paths: serde_json::Map<String, serde_json::Value> =
587                    used_closure(i, blocks, &by_path)
588                        .into_iter()
589                        .map(|u| (u.name.clone(), module_path_string(&u.path).into()))
590                        .collect();
591                serde_json::json!({
592                    "module": blocks[i].lean_module(&crate_ident),
593                    "namespace": blocks[i].name,
594                    "type_paths": type_paths,
595                    "model_namespace": crate_ident,
596                    "output_file": tmp.join(format!("{}.rs", keys[i])).to_string_lossy(),
597                })
598            })
599            .collect();
600        let batch = tmp.join("batch.json");
601        fs::write(&batch, serde_json::Value::Array(jobs).to_string())?;
602        let mut cmd = Command::new(&cli);
603        cmd.current_dir(&lean)
604            .args(["module", "generate", "--batch"])
605            .arg(&batch);
606        if csimp {
607            cmd.args(["--import", "LeanRustGen.Csimp"]);
608        }
609        cmd.args(["--output", "json", "--search-path"]);
610        for p in lean_path.trim().split(':').filter(|p| !p.is_empty()) {
611            cmd.arg(p);
612        }
613        let out = cmd.output().map_err(|e| {
614            Error::new(format!("leanfran-build: cannot run {}: {e}", cli.display()))
615        })?;
616        let summary: Option<serde_json::Value> = serde_json::from_slice(&out.stdout).ok();
617        let mut errors = Vec::new();
618        if let Some(serde_json::Value::Array(items)) = &summary {
619            for (j, item) in items.iter().enumerate() {
620                let b = &blocks[missing[j]];
621                if let Some(e) = item.get("error").and_then(|e| e.as_str()) {
622                    errors.push(format!("{} ({}): {e}", b.file, module_path_string(&b.path)));
623                }
624                if let Some(serde_json::Value::Array(sk)) = item.get("skipped") {
625                    for s in sk {
626                        println!(
627                            "cargo:warning={} ({}): not public: {}: {}",
628                            b.file,
629                            module_path_string(&b.path),
630                            s.get("name").and_then(|v| v.as_str()).unwrap_or(""),
631                            s.get("reason").and_then(|v| v.as_str()).unwrap_or("")
632                        );
633                    }
634                }
635            }
636        }
637        if !out.status.success() || summary.is_none() {
638            if errors.is_empty() {
639                errors.push(String::from_utf8_lossy(&out.stderr).into_owned());
640            }
641            return Err(Error::new(format!(
642                "leanfran-build: leanfran module generate failed:\n{}",
643                errors.join("\n")
644            )));
645        }
646        let cache = self.cache_dir();
647        fs::create_dir_all(&cache)?;
648        for &i in missing {
649            let gen = tmp.join(format!("{}.rs", keys[i]));
650            run_output(
651                Command::new("rustfmt")
652                    .args(["--edition", "2021"])
653                    .arg(&gen),
654                "rustfmt",
655            )?;
656            let text = fs::read(&gen)?;
657            fs::write(cache.join(format!("{}.rs", keys[i])), &text)?;
658            write_if_changed(&self.out_dir.join(blocks[i].out_file()), &text)?;
659        }
660        let mut live: BTreeSet<PathBuf> =
661            keys.iter().map(|k| cache.join(format!("{k}.rs"))).collect();
662        for o in self.opaque_models(&self.scan_items()?)? {
663            live.insert(cache.join(format!("{}.rs", o.key)));
664        }
665        prune_dir(&cache, &live)?;
666        Ok(())
667    }
668}
669
670struct Scanner {
671    file: String,
672    hash: String,
673    module: Vec<String>,
674    blocks: Vec<Block>,
675    error: Option<Error>,
676}
677
678impl<'ast> Visit<'ast> for Scanner {
679    fn visit_item_mod(&mut self, m: &'ast syn::ItemMod) {
680        self.module.push(m.ident.to_string());
681        syn::visit::visit_item_mod(self, m);
682        self.module.pop();
683    }
684
685    fn visit_macro(&mut self, mac: &'ast syn::Macro) {
686        let segs: Vec<String> = mac
687            .path
688            .segments
689            .iter()
690            .map(|s| s.ident.to_string())
691            .collect();
692        let is_lean = matches!(segs.as_slice(), [l] if l == "lean")
693            || matches!(segs.as_slice(), [c, l] if c == "leanfran" && l == "lean");
694        if !is_lean {
695            syn::visit::visit_macro(self, mac);
696            return;
697        }
698        match mac.parse_body::<LeanBlock>() {
699            Ok(b) => {
700                let name = b.name.to_string();
701                let mut path = self.module.clone();
702                path.push(name.clone());
703                let uses = b
704                    .uses
705                    .iter()
706                    .map(|p| resolve_path(&self.module, p))
707                    .collect();
708                self.blocks.push(Block {
709                    file: self.file.clone(),
710                    file_hash: self.hash.clone(),
711                    name,
712                    path,
713                    imports: b.imports,
714                    uses,
715                    source: b.source.value(),
716                    line: b.source.span().start().line,
717                });
718            }
719            Err(e) => {
720                let at = e.span().start();
721                self.error.get_or_insert(Error::new(format!(
722                    "leanfran-build: {}:{}:{}: invalid lean! block: {e}",
723                    self.file,
724                    at.line,
725                    at.column + 1
726                )));
727            }
728        }
729    }
730}
731
732fn resolve_path(module: &[String], p: &syn::Path) -> Vec<String> {
733    let segs: Vec<String> = p.segments.iter().map(|s| s.ident.to_string()).collect();
734    let mut out: Vec<String> = Vec::new();
735    let mut rest = segs.as_slice();
736    match rest.first().map(String::as_str) {
737        Some("crate") => rest = &rest[1..],
738        Some("self") => {
739            out = module.to_vec();
740            rest = &rest[1..];
741        }
742        Some("super") => {
743            out = module.to_vec();
744            while rest.first().is_some_and(|s| s == "super") {
745                out.pop();
746                rest = &rest[1..];
747            }
748        }
749        _ => out = module.to_vec(),
750    }
751    out.extend(rest.iter().cloned());
752    out
753}
754
755/// The blocks `blocks[i]` uses, directly or through other blocks.
756fn used_closure<'a>(
757    i: usize,
758    blocks: &'a [Block],
759    by_path: &HashMap<&[String], &'a Block>,
760) -> Vec<&'a Block> {
761    let mut out: Vec<&Block> = Vec::new();
762    let mut stack: Vec<&[String]> = blocks[i].uses.iter().map(Vec::as_slice).collect();
763    while let Some(p) = stack.pop() {
764        let u = by_path[p];
765        if out.iter().any(|o| o.path == u.path) {
766            continue;
767        }
768        out.push(u);
769        stack.extend(u.uses.iter().map(Vec::as_slice));
770    }
771    out
772}
773
774pub fn module_path_string(path: &[String]) -> String {
775    let mut s = String::from("crate");
776    for p in path {
777        s.push_str("::");
778        s.push_str(p);
779    }
780    s
781}
782
783/// The cache key of every block: SHA-256 over the crate name, the file, the block name, the
784/// imports, the source, the keys of the used blocks, `extra` (the hash of the `@[csimp]`
785/// replacements) and [`GENERATOR_VERSION`].
786pub fn cache_keys(crate_name: &str, blocks: &[Block], extra: &str) -> Result<Vec<String>, Error> {
787    let index: HashMap<&[String], usize> = blocks
788        .iter()
789        .enumerate()
790        .map(|(i, b)| (b.path.as_slice(), i))
791        .collect();
792    let mut keys: Vec<Option<String>> = vec![None; blocks.len()];
793    fn key_of(
794        i: usize,
795        crate_name: &str,
796        extra: &str,
797        blocks: &[Block],
798        index: &HashMap<&[String], usize>,
799        keys: &mut Vec<Option<String>>,
800        stack: &mut Vec<usize>,
801    ) -> Result<String, Error> {
802        if let Some(k) = &keys[i] {
803            return Ok(k.clone());
804        }
805        let b = &blocks[i];
806        if stack.contains(&i) {
807            return Err(Error::new(format!(
808                "leanfran-build: lean! blocks use each other in a cycle through {}",
809                module_path_string(&b.path)
810            )));
811        }
812        stack.push(i);
813        let mut h = Sha256::new();
814        for part in [crate_name, &b.file, &b.name] {
815            h.update(part.as_bytes());
816            h.update([0]);
817        }
818        for imp in &b.imports {
819            h.update(imp.as_bytes());
820            h.update([1]);
821        }
822        h.update([0]);
823        h.update(b.source.as_bytes());
824        h.update([0]);
825        if b.uses_instances() {
826            h.update(INSTANCES_LEAN.as_bytes());
827        }
828        h.update([0]);
829        for u in &b.uses {
830            let Some(&j) = index.get(u.as_slice()) else {
831                return Err(Error::new(format!(
832                    "leanfran-build: {}: `uses` names {}, which is not a lean! block of this crate",
833                    b.file,
834                    module_path_string(u)
835                )));
836            };
837            h.update(key_of(j, crate_name, extra, blocks, index, keys, stack)?.as_bytes());
838            h.update([1]);
839        }
840        h.update([0]);
841        h.update(extra.as_bytes());
842        h.update([0]);
843        h.update(GENERATOR_VERSION.as_bytes());
844        stack.pop();
845        let k: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
846        keys[i] = Some(k.clone());
847        Ok(k)
848    }
849    let mut stack = Vec::new();
850    (0..blocks.len())
851        .map(|i| key_of(i, crate_name, extra, blocks, &index, &mut keys, &mut stack))
852        .collect()
853}
854
855/// The Lean file of a block, the number of lines before the source and the indentation
856/// removed from the source.
857pub fn lean_source(b: &Block, used: &[&Block], crate_ident: &str) -> (String, usize, usize) {
858    let mut text = String::new();
859    for imp in &b.imports {
860        text.push_str(&format!("import {imp}\n"));
861    }
862    if b.uses_instances() {
863        text.push_str(&format!("import {INSTANCES_MODULE}\n"));
864    }
865    for u in used {
866        text.push_str(&format!("import {}\n", u.lean_module(crate_ident)));
867    }
868    if !used.is_empty() {
869        let names: Vec<&str> = used.iter().map(|u| u.name.as_str()).collect();
870        text.push_str(&format!("open {}\n", names.join(" ")));
871    }
872    text.push_str(&format!("namespace {}\n", b.name));
873    let header = text.lines().count();
874    let indent = b
875        .source
876        .lines()
877        .filter(|l| !l.trim().is_empty())
878        .map(|l| l.len() - l.trim_start().len())
879        .min()
880        .unwrap_or(0);
881    for line in b.source.lines() {
882        if line.trim().is_empty() {
883            text.push('\n');
884        } else {
885            text.push_str(&line[indent.min(line.len())..]);
886            text.push('\n');
887        }
888    }
889    text.push_str(&format!("end {}\n", b.name));
890    (text, header, indent)
891}
892
893/// The diagnostics of a `lake build` log, with the positions of the Lean files of the blocks
894/// replaced by the Rust file and line of the `lean!` source.
895fn map_diagnostics(
896    log: &str,
897    blocks: &[Block],
898    sources: &[(usize, usize)],
899    crate_ident: &str,
900) -> Vec<String> {
901    let files: Vec<String> = blocks
902        .iter()
903        .map(|b| normalize_path(&b.lean_file(crate_ident)))
904        .collect();
905    let mut out: Vec<String> = Vec::new();
906    let mut current: Option<String> = None;
907    for line in log.lines() {
908        let kind = ["error: ", "warning: ", "info: "]
909            .iter()
910            .find(|p| line.starts_with(**p));
911        if let Some(kind) = kind {
912            if let Some(d) = current.take() {
913                out.push(d);
914            }
915            let rest = &line[kind.len()..];
916            for (i, f) in files.iter().enumerate() {
917                let Some(pos) = rest.find(f.as_str()) else {
918                    continue;
919                };
920                let after = &rest[pos + f.len()..];
921                let mut parts = after.splitn(4, ':');
922                let (Some(""), Some(l), Some(c), Some(msg)) =
923                    (parts.next(), parts.next(), parts.next(), parts.next())
924                else {
925                    continue;
926                };
927                let (Ok(l), Ok(c)) = (l.parse::<usize>(), c.parse::<usize>()) else {
928                    continue;
929                };
930                let (header, indent) = sources[i];
931                let b = &blocks[i];
932                let src_line = l.saturating_sub(header);
933                let rust_line = b.line + src_line.saturating_sub(1);
934                let label = kind.trim_end_matches(": ");
935                current = Some(format!(
936                    "{}:{}:{}: {label}:{msg}",
937                    b.file,
938                    rust_line,
939                    c + indent + 1
940                ));
941                break;
942            }
943        } else if let Some(d) = current.as_mut() {
944            let t = line.trim_start();
945            if t.starts_with('✖')
946                || t.starts_with('✔')
947                || t.starts_with("trace:")
948                || t.starts_with("Some required")
949                || t.starts_with("- ")
950            {
951                out.push(current.take().unwrap());
952            } else {
953                d.push('\n');
954                d.push_str(line);
955            }
956        }
957    }
958    if let Some(d) = current {
959        out.push(d);
960    }
961    out.into_iter().map(|d| d.trim_end().to_string()).collect()
962}
963
964fn run_output(cmd: &mut Command, what: &str) -> Result<String, Error> {
965    let out = cmd
966        .output()
967        .map_err(|e| Error::new(format!("leanfran-build: cannot run {what}: {e}")))?;
968    if !out.status.success() {
969        return Err(Error::new(format!(
970            "leanfran-build: {what} failed:\n{}{}",
971            String::from_utf8_lossy(&out.stdout),
972            String::from_utf8_lossy(&out.stderr)
973        )));
974    }
975    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
976}
977
978fn write_if_changed(path: &Path, content: &[u8]) -> Result<(), Error> {
979    if fs::read(path).ok().as_deref() == Some(content) {
980        return Ok(());
981    }
982    if let Some(dir) = path.parent() {
983        fs::create_dir_all(dir)?;
984    }
985    fs::write(path, content)?;
986    Ok(())
987}
988
989/// Removes the files below `dir` that are not in `live`, and the directories left empty.
990fn prune_dir(dir: &Path, live: &BTreeSet<PathBuf>) -> Result<(), Error> {
991    if !dir.is_dir() {
992        return Ok(());
993    }
994    for e in fs::read_dir(dir)? {
995        let p = e?.path();
996        if p.is_dir() {
997            prune_dir(&p, live)?;
998            if fs::read_dir(&p)?.next().is_none() {
999                fs::remove_dir(&p)?;
1000            }
1001        } else if !live.contains(&p) {
1002            fs::remove_file(&p)?;
1003        }
1004    }
1005    Ok(())
1006}
1007
1008fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), Error> {
1009    if !dir.is_dir() {
1010        return Ok(());
1011    }
1012    for e in fs::read_dir(dir)? {
1013        let p = e?.path();
1014        if p.is_dir() {
1015            collect_rs(&p, out)?;
1016        } else if p.extension().is_some_and(|x| x == "rs") {
1017            out.push(p);
1018        }
1019    }
1020    Ok(())
1021}
1022
1023fn collect_user_files(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) {
1024    let Ok(entries) = fs::read_dir(dir) else {
1025        return;
1026    };
1027    for e in entries.flatten() {
1028        let p = e.path();
1029        let rel = p.strip_prefix(root).unwrap_or(&p);
1030        let first = rel.components().next().map(|c| c.as_os_str().to_owned());
1031        if first.as_deref() == Some("LeanRustGen".as_ref())
1032            || first.as_deref() == Some(".lake".as_ref())
1033        {
1034            continue;
1035        }
1036        if p.is_dir() {
1037            collect_user_files(root, &p, out);
1038        } else {
1039            out.push(p);
1040        }
1041    }
1042}
1043
1044/// The rev of Aeneas this leanfran works with: the `require aeneas` of the crate's Lean
1045/// package.
1046pub const AENEAS_REV: &str = "c5eb4a28cef65e0aa27743105308243e535a2a2b";
1047
1048/// The version of the Charon bundled with that Aeneas.
1049pub const CHARON_VERSION: &str = "0.1.313";
1050
1051/// `true` when the block imports the crate's model (`LeanRustGen.Model`, `.Alias` or `.Extern`,
1052/// written by `cargo leanfran extract`), directly or through the blocks it uses.
1053pub fn depends_on_model(b: &Block, blocks: &[Block]) -> bool {
1054    let mut stack = vec![b];
1055    let mut seen: Vec<&[String]> = Vec::new();
1056    while let Some(x) = stack.pop() {
1057        if seen.contains(&x.path.as_slice()) {
1058            continue;
1059        }
1060        seen.push(&x.path);
1061        if x.imports.iter().any(|i| {
1062            [
1063                "LeanRustGen.Model.",
1064                "LeanRustGen.Alias.",
1065                "LeanRustGen.Extern.",
1066            ]
1067            .iter()
1068            .any(|p| i.starts_with(p))
1069        }) {
1070            return true;
1071        }
1072        stack.extend(blocks.iter().filter(|o| x.uses.contains(&o.path)));
1073    }
1074    false
1075}
1076
1077/// The Lean model of a `#[leanfran::opaque]` function, written in `lean/External.lean`.
1078#[derive(Debug, Clone)]
1079pub struct OpaqueModel {
1080    /// The unit name of the Rust function.
1081    pub rust: String,
1082    /// The candidate Lean names of the model (relative to the root and to the crate).
1083    pub lean: Vec<String>,
1084    /// The cache key of its generated Rust.
1085    pub key: String,
1086    /// The path of the generated Rust below `OUT_DIR`.
1087    pub out_file: PathBuf,
1088}
1089
1090fn sha_hex(parts: &[&[u8]]) -> String {
1091    let mut h = Sha256::new();
1092    for p in parts {
1093        h.update(p);
1094        h.update([0]);
1095    }
1096    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
1097}
1098
1099impl Builder {
1100    fn model_dir(&self) -> PathBuf {
1101        self.lean_dir()
1102            .join("LeanRustGen")
1103            .join("Model")
1104            .join(self.crate_ident())
1105    }
1106
1107    /// The opaque functions whose model Aeneas lists in `FunsExternal_Template.lean`, when
1108    /// `lean/External.lean` defines it.
1109    pub fn opaque_models(&self, items: &model::CrateItems) -> Result<Vec<OpaqueModel>, Error> {
1110        let template = self.model_dir().join("FunsExternal_Template.lean");
1111        let (Ok(template), Ok(external)) = (
1112            fs::read_to_string(&template),
1113            fs::read(self.lean_dir().join("External.lean")),
1114        ) else {
1115            return Ok(Vec::new());
1116        };
1117        let ident = self.crate_ident();
1118        let decls = gen::parse_aeneas(&template);
1119        let types = fs::read(self.lean_dir().join("ExternalTypes.lean")).unwrap_or_default();
1120        let model_types = fs::read(self.model_dir().join("Types.lean")).unwrap_or_default();
1121        let mut out = Vec::new();
1122        for o in &items.opaque {
1123            let unit = &o.unit;
1124            let Some(d) = decls.iter().find(|d| {
1125                d.rust
1126                    .as_deref()
1127                    .and_then(|r| gen::aeneas_unit(r, &ident))
1128                    .as_deref()
1129                    == Some(unit.as_str())
1130            }) else {
1131                continue;
1132            };
1133            if o.module != file_module(&o.file) {
1134                continue;
1135            }
1136            let lean = vec![d.lean.clone(), format!("{ident}.{}", d.lean)];
1137            let key = sha_hex(&[
1138                ident.as_bytes(),
1139                unit.as_bytes(),
1140                lean.join(" ").as_bytes(),
1141                &external,
1142                &types,
1143                &model_types,
1144                GENERATOR_VERSION.as_bytes(),
1145            ]);
1146            out.push(OpaqueModel {
1147                rust: unit.clone(),
1148                lean,
1149                key,
1150                out_file: Path::new("leanfran")
1151                    .join("opaque")
1152                    .join(file_hash(&o.file))
1153                    .join(format!("{}.rs", o.file_stem())),
1154            });
1155        }
1156        Ok(out)
1157    }
1158
1159    /// Writes the Rust of the models of the opaque functions to `OUT_DIR` from the cache,
1160    /// generating the missing ones with `leanfran module generate` unless `cached_only`.
1161    fn compile_opaque(&self, items: &model::CrateItems, cached_only: bool) -> Result<(), Error> {
1162        let models = self.opaque_models(items)?;
1163        let cache = self.cache_dir();
1164        let missing: Vec<&OpaqueModel> = models
1165            .iter()
1166            .filter(|m| !cache.join(format!("{}.rs", m.key)).is_file())
1167            .collect();
1168        if !missing.is_empty() && !cached_only {
1169            self.generate_opaque(&missing)?;
1170        }
1171        for m in &models {
1172            if let Ok(text) = fs::read(cache.join(format!("{}.rs", m.key))) {
1173                write_if_changed(&self.out_dir.join(&m.out_file), &text)?;
1174            }
1175        }
1176        Ok(())
1177    }
1178
1179    fn generate_opaque(&self, models: &[&OpaqueModel]) -> Result<(), Error> {
1180        let cli = std::env::var_os("LEANFRAN_CLI")
1181            .map(PathBuf::from)
1182            .unwrap_or_else(|| PathBuf::from("leanfran"));
1183        let lean = self.lean_dir();
1184        run_output(
1185            Command::new("lake")
1186                .args(["build", "External"])
1187                .current_dir(&lean),
1188            "lake build External",
1189        )?;
1190        let lean_path = run_output(
1191            Command::new("lake")
1192                .args(["env", "printenv", "LEAN_PATH"])
1193                .current_dir(&lean),
1194            "lake env",
1195        )?;
1196        let tmp = self.out_dir.join("leanfran").join("tmp");
1197        fs::create_dir_all(&tmp)?;
1198        let ident = self.crate_ident();
1199        let jobs: Vec<serde_json::Value> = models
1200            .iter()
1201            .map(|m| {
1202                serde_json::json!({
1203                    "module": "External",
1204                    "roots": m.lean,
1205                    "namespace": ident,
1206                    "model_namespace": ident,
1207                    "output_file": tmp.join(format!("{}.rs", m.key)).to_string_lossy(),
1208                })
1209            })
1210            .collect();
1211        let batch = tmp.join("opaque.json");
1212        fs::write(&batch, serde_json::Value::Array(jobs).to_string())?;
1213        let mut cmd = Command::new(&cli);
1214        cmd.current_dir(&lean)
1215            .args(["module", "generate", "--batch"])
1216            .arg(&batch)
1217            .args(["--output", "json", "--search-path"]);
1218        for p in lean_path.trim().split(':').filter(|p| !p.is_empty()) {
1219            cmd.arg(p);
1220        }
1221        let summary = run_output(&mut cmd, &format!("{} module generate", cli.display()))?;
1222        let summary: Vec<serde_json::Value> = serde_json::from_str(&summary).unwrap_or_default();
1223        let cache = self.cache_dir();
1224        fs::create_dir_all(&cache)?;
1225        for (i, m) in models.iter().enumerate() {
1226            let gen = tmp.join(format!("{}.rs", m.key));
1227            let mut text = fs::read_to_string(&gen)?;
1228            let public = summary
1229                .get(i)
1230                .and_then(|s| s.get("public"))
1231                .and_then(|p| p.as_array())
1232                .and_then(|p| p.first())
1233                .and_then(|p| p.get("rust"))
1234                .and_then(|r| r.as_str());
1235            match public {
1236                Some(r) => text.push_str(&format!(
1237                    "\n#[doc(hidden)]\npub use self::{r} as __leanfran_model;\n"
1238                )),
1239                None => println!(
1240                    "cargo:warning=leanfran: {}: lean/External.lean has no computable model to test it against",
1241                    m.rust
1242                ),
1243            }
1244            fs::write(&gen, &text)?;
1245            run_output(
1246                Command::new("rustfmt")
1247                    .args(["--edition", "2021"])
1248                    .arg(&gen),
1249                "rustfmt",
1250            )?;
1251            fs::write(cache.join(format!("{}.rs", m.key)), fs::read(&gen)?)?;
1252        }
1253        Ok(())
1254    }
1255}