Skip to main content

leanfran_macros/
lib.rs

1//! Procedural macros of leanfran.
2//!
3//! `lean!` expands to a module that includes the Rust code the build script generated from the
4//! Lean source: `include!(concat!(env!("OUT_DIR"), "/leanfran/<file hash>/<name>.rs"))`. It
5//! does not run Lean. The macro reads `OUT_DIR` and reports a missing build script or a
6//! missing generated file with `compile_error!`.
7
8mod model;
9
10use leanfran_build::syntax::{file_hash, normalize_path, LeanBlock};
11use proc_macro::TokenStream;
12use quote::quote;
13use std::path::{Path, PathBuf};
14use syn::parse_macro_input;
15
16/// Marks a generated public function with the full name of the Lean definition it runs. It
17/// changes nothing; tools read it to map Rust paths to Lean names.
18#[proc_macro_attribute]
19pub fn exported(_attr: TokenStream, item: TokenStream) -> TokenStream {
20    item
21}
22
23/// Binds a function (or the methods of an impl block) to Lean specs.
24///
25/// The item is unchanged. The macro adds the functions that call the specs (`requires`,
26/// `refines`, `ensures_<label>`), so that rustc checks the paths of the specs and their argument
27/// types, a property-based test of each spec under `#[cfg(test)]` (unless `check = false`), and
28/// the documentation of the state of the proofs that the build script writes.
29///
30/// ```ignore
31/// #[leanfran::model(
32///     requires = sorting::input_sorted,
33///     ensures(sorted = sorting::output_sorted, perm = "OutputPerm"),
34/// )]
35/// pub fn insert_sorted(x: i64, xs: &[i64]) -> Vec<i64> { /* .. */ }
36/// ```
37#[proc_macro_attribute]
38pub fn model(attr: TokenStream, item: TokenStream) -> TokenStream {
39    match model::expand(attr.into(), item.into()) {
40        Ok(ts) => ts.into(),
41        Err(e) => e.to_compile_error().into(),
42    }
43}
44
45/// A function whose body is not extracted: its Lean model is written by hand in
46/// `lean/External.lean`. The item is unchanged; under `#[cfg(test)]` the macro adds a
47/// proptest of the function against that model (keys `check` and `strategy` as in `#[model]`),
48/// when the build script generated it.
49#[proc_macro_attribute]
50pub fn opaque(attr: TokenStream, item: TokenStream) -> TokenStream {
51    let file = caller_rel_path()
52        .ok()
53        .zip(std::env::var("OUT_DIR").ok())
54        .map(|(rel, out)| (file_hash(&rel), out));
55    match model::expand_opaque(attr.into(), item.into(), file) {
56        Ok(ts) => ts.into(),
57        Err(e) => e.to_compile_error().into(),
58    }
59}
60
61/// Implements `Model` (the representation of the type in Aeneas's model: the constructor
62/// layout of the structure or inductive type Aeneas generates for it) and `SpecArg` (by
63/// `Clone`).
64#[proc_macro_derive(Model)]
65pub fn derive_model(input: TokenStream) -> TokenStream {
66    match model::derive(input.into()) {
67        Ok(ts) => ts.into(),
68        Err(e) => e.to_compile_error().into(),
69    }
70}
71
72/// Lean source checked and compiled by the build script.
73///
74/// ```ignore
75/// leanfran::lean! {
76///     /// Documentation of the module.
77///     #[lean(imports = ["Std.Data.HashMap"], uses = [crate::geometry::shapes])]
78///     pub mod arith;
79///     r#"
80///     def double (n : Nat) : Nat := n + n
81///     "#
82/// }
83/// ```
84#[proc_macro]
85pub fn lean(input: TokenStream) -> TokenStream {
86    let block = parse_macro_input!(input as LeanBlock);
87    match expand(&block) {
88        Ok(ts) => ts,
89        Err(msg) => {
90            let name = &block.name;
91            let vis = &block.vis;
92            quote! {
93                #vis mod #name {
94                    ::core::compile_error!(#msg);
95                }
96            }
97            .into()
98        }
99    }
100}
101
102fn caller_rel_path() -> Result<String, String> {
103    let file = proc_macro::Span::call_site()
104        .local_file()
105        .ok_or("lean!: the source file of the macro call is unknown")?;
106    let manifest = std::env::var_os("CARGO_MANIFEST_DIR")
107        .map(PathBuf::from)
108        .ok_or("lean!: CARGO_MANIFEST_DIR is not set (build with cargo)")?;
109    let abs = if file.is_absolute() {
110        file
111    } else {
112        std::env::current_dir()
113            .map_err(|e| format!("lean!: {e}"))?
114            .join(file)
115    };
116    let abs = abs.canonicalize().unwrap_or(abs);
117    let manifest = manifest.canonicalize().unwrap_or(manifest);
118    let rel = abs.strip_prefix(&manifest).map_err(|_| {
119        format!(
120            "lean!: {} is not inside the crate {}",
121            abs.display(),
122            manifest.display()
123        )
124    })?;
125    Ok(normalize_path(rel))
126}
127
128fn expand(block: &LeanBlock) -> Result<TokenStream, String> {
129    let rel = caller_rel_path()?;
130    let hash = file_hash(&rel);
131    let name = &block.name;
132    let file_name = format!("/{name}.rs");
133    let Some(out_dir) = std::env::var_os("OUT_DIR") else {
134        return Err("lean!: the crate has no build script. Add `build.rs` with \
135             `fn main() { leanfran_build::Builder::new().compile().unwrap(); }` and \
136             `leanfran-build` to [build-dependencies]"
137            .to_string());
138    };
139    let generated = Path::new(&out_dir)
140        .join("leanfran")
141        .join(&hash)
142        .join(format!("{name}.rs"));
143    if !generated.is_file() {
144        if model::extracting() {
145            let vis = &block.vis;
146            return Ok(quote! { #[allow(dead_code)] #vis mod #name {} }.into());
147        }
148        return Err(format!(
149            "lean!: {} was not generated for `mod {name}` in {rel}. The build script must call \
150             `leanfran_build::Builder::new().compile()`, which generates the lean! blocks of src/**/*.rs",
151            generated.display()
152        ));
153    }
154    let attrs = &block.attrs;
155    let vis = &block.vis;
156    Ok(quote! {
157        #(#attrs)*
158        #[allow(dead_code, non_snake_case, non_camel_case_types, unused_imports, unused_parens, unused_qualifications, unsafe_op_in_unsafe_fn, clippy::all)]
159        #vis mod #name {
160            include!(concat!(env!("OUT_DIR"), "/leanfran/", #hash, #file_name));
161        }
162    }
163    .into())
164}