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