Skip to main content

leanfran_build/
syntax.rs

1//! The syntax of `lean!`, shared by the macro and the build script.
2
3use sha2::{Digest, Sha256};
4use syn::parse::{Parse, ParseStream};
5use syn::punctuated::Punctuated;
6use syn::{bracketed, Attribute, Ident, LitStr, Path, Token, Visibility};
7
8/// A `lean!` block:
9///
10/// ```text
11/// /// documentation
12/// #[lean(imports = ["Std.Data.HashMap"], uses = [crate::geometry::shapes])]
13/// pub mod name;
14/// r#"Lean source"#
15/// ```
16pub struct LeanBlock {
17    /// The attributes other than `#[lean(...)]` (documentation), put on the module.
18    pub attrs: Vec<Attribute>,
19    pub imports: Vec<String>,
20    pub uses: Vec<Path>,
21    pub vis: Visibility,
22    pub name: Ident,
23    pub source: LitStr,
24}
25
26impl Parse for LeanBlock {
27    fn parse(input: ParseStream) -> syn::Result<Self> {
28        let all = input.call(Attribute::parse_outer)?;
29        let mut attrs = Vec::new();
30        let mut imports = Vec::new();
31        let mut uses = Vec::new();
32        for attr in all {
33            if !attr.path().is_ident("lean") {
34                attrs.push(attr);
35                continue;
36            }
37            attr.parse_nested_meta(|meta| {
38                let content;
39                if meta.path.is_ident("imports") {
40                    let value = meta.value()?;
41                    bracketed!(content in value);
42                    let lits = Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?;
43                    imports.extend(lits.iter().map(LitStr::value));
44                    Ok(())
45                } else if meta.path.is_ident("uses") {
46                    let value = meta.value()?;
47                    bracketed!(content in value);
48                    let paths = Punctuated::<Path, Token![,]>::parse_terminated(&content)?;
49                    uses.extend(paths);
50                    Ok(())
51                } else {
52                    Err(meta.error("expected `imports` or `uses`"))
53                }
54            })?;
55        }
56        let vis: Visibility = input.parse()?;
57        input.parse::<Token![mod]>()?;
58        let name: Ident = input.parse()?;
59        input.parse::<Token![;]>()?;
60        let source: LitStr = input.parse()?;
61        if !input.is_empty() {
62            return Err(input.error("unexpected tokens after the Lean source"));
63        }
64        Ok(LeanBlock {
65            attrs,
66            imports,
67            uses,
68            vis,
69            name,
70            source,
71        })
72    }
73}
74
75/// The first 16 hex digits of the SHA-256 of `rel_path` (the path of a Rust file relative to
76/// the crate root, with `/` separators): the directory of the file's blocks in `OUT_DIR`.
77pub fn file_hash(rel_path: &str) -> String {
78    let digest = Sha256::digest(rel_path.as_bytes());
79    digest.iter().take(8).map(|b| format!("{b:02x}")).collect()
80}
81
82/// `rel_path` with `/` separators.
83pub fn normalize_path(rel_path: &std::path::Path) -> String {
84    rel_path
85        .components()
86        .map(|c| c.as_os_str().to_string_lossy().into_owned())
87        .collect::<Vec<_>>()
88        .join("/")
89}