leanfran-runtime 0.7.0

Runtime of the Rust code generated from Lean by leanfran
Documentation
//! Generates `EXTERNS`: the C names of the functions this crate provides, i.e. every
//! `pub unsafe fn` / `pub fn` named `lean_*` or after a `math.h` function, plus the `lean_*`
//! names defined through the macros of the crate.

use std::fs;
use std::path::Path;

fn main() {
    let src = Path::new("src");
    println!("cargo:rerun-if-changed=src");
    println!(
        "cargo:rustc-env=LEANFRAN_TARGET={}",
        std::env::var("TARGET").unwrap()
    );
    let mut names = Vec::new();
    let mut entries: Vec<_> = fs::read_dir(src)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    entries.sort();
    for path in entries {
        if path.extension().is_some_and(|e| e == "rs") {
            println!("cargo:rerun-if-changed={}", path.display());
            let text = fs::read_to_string(&path).unwrap();
            scan(&text, &mut names);
        }
    }
    names.sort();
    names.dedup();
    let mut out = String::from(
        "/// C names of the functions this runtime provides (generated by `build.rs`).\npub const EXTERNS: &[&str] = &[\n",
    );
    for n in &names {
        out.push_str(&format!("    \"{n}\",\n"));
    }
    out.push_str("];\n\n/// Refers to every name of [`EXTERNS`], so that a name that is not a function of the crate fails to compile.\n#[allow(dead_code)]\nfn check_externs() -> [*const (); EXTERNS.len()] {\n    [\n");
    for n in &names {
        out.push_str(&format!("        {n} as *const (),\n"));
    }
    out.push_str("    ]\n}\n");
    let dest = Path::new(&std::env::var("OUT_DIR").unwrap()).join("externs.rs");
    fs::write(dest, out).unwrap();
}

const LIBM: &[&str] = &[
    "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "asinh", "acosh",
    "atanh", "exp", "exp2", "log", "log2", "log10", "pow", "sqrt", "cbrt", "ceil", "floor",
    "round", "fabs", "fma",
];

fn is_extern_name(n: &str) -> bool {
    n.starts_with("lean_")
        || LIBM.contains(&n)
        || LIBM.iter().any(|m| n.strip_suffix('f') == Some(*m))
}

fn ident_at(s: &str) -> &str {
    let end = s
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .unwrap_or(s.len());
    &s[..end]
}

/// Collects `pub [unsafe] fn NAME` and the identifiers passed to the generating macros
/// (`uint_ops!`, `sint_ops!`, `float_common!`, `ctor_scalar!`, `apply_k!`, `libm1!`, `libm2!`,
/// `int_binop!`), keeping the names that are C names.
fn scan(text: &str, names: &mut Vec<String>) {
    for line in text.lines() {
        let l = line.trim_start();
        for prefix in ["pub unsafe fn ", "pub fn "] {
            if let Some(rest) = l.strip_prefix(prefix) {
                let n = ident_at(rest);
                if is_extern_name(n) && !n.starts_with('$') {
                    names.push(n.to_string());
                }
            }
        }
    }
    // Macro invocations: every identifier inside `name!( ... );` at the start of a line.
    let mut rest = text;
    while let Some(pos) = rest.find("\n") {
        let line_start = &rest[pos + 1..];
        let trimmed = line_start.trim_start();
        let is_invocation = [
            "uint_ops!(",
            "sint_ops!(",
            "float_common!(",
            "ctor_scalar!(",
            "apply_k!(",
            "libm1!(",
            "libm2!(",
            "int_binop!(",
        ]
        .iter()
        .any(|m| trimmed.starts_with(m));
        if is_invocation {
            let end = trimmed.find(");").unwrap_or(trimmed.len());
            let body = &trimmed[trimmed.find('(').unwrap() + 1..end];
            for tok in body.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
                if is_extern_name(tok) {
                    names.push(tok.to_string());
                }
            }
        }
        rest = line_start;
    }
}