Skip to main content

leanfran_build/
model.rs

1//! The syntax of `#[leanfran::model]`, shared by the macro, the build script and
2//! `cargo leanfran`: the attribute keys, the signature of a modelled function, its loops, and
3//! the items of a crate with the hashes of their tokens.
4
5use proc_macro2::{TokenStream, TokenTree};
6use quote::ToTokens;
7use sha2::{Digest, Sha256};
8use std::collections::BTreeMap;
9use syn::parse::Parser;
10use syn::spanned::Spanned;
11use syn::visit::Visit;
12use syn::{Attribute, FnArg, ImplItem, Item, LitBool, LitStr, Pat, Path, ReturnType, Type};
13
14/// A spec named by an attribute key.
15#[derive(Debug, Clone)]
16pub enum SpecRef {
17    /// A Rust path to a public function generated from Lean.
18    Path(Path),
19    /// A Lean name.
20    Lean(String),
21}
22
23impl SpecRef {
24    pub fn describe(&self) -> String {
25        match self {
26            SpecRef::Path(p) => path_string(p),
27            SpecRef::Lean(s) => format!("\"{s}\""),
28        }
29    }
30}
31
32/// How the obligations of a generic function are stated.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum ObligationMode {
35    /// One obligation for every type, assuming the laws of the trait bounds (`LeanRust.OrdModel`).
36    Generic,
37    /// One obligation per type of `instances`, with Aeneas's instances of the traits.
38    PerInstance,
39}
40
41/// The keys of `#[leanfran::model(..)]`.
42#[derive(Debug, Clone, Default)]
43pub struct ModelAttr {
44    pub refines: Option<SpecRef>,
45    pub requires: Option<SpecRef>,
46    pub ensures: Vec<(String, SpecRef)>,
47    pub check: Option<bool>,
48    pub strategy: Option<Path>,
49    /// The types the tests of a generic function run with: one type per type parameter, a
50    /// tuple for several.
51    pub instances: Vec<Type>,
52    pub obligations: Option<ObligationMode>,
53}
54
55/// The text of a type without spaces: `Vec<u32>`, `(u32,String)`.
56pub fn type_text(t: &Type) -> String {
57    t.to_token_stream()
58        .to_string()
59        .chars()
60        .filter(|c| !c.is_whitespace())
61        .collect()
62}
63
64/// The part of a name standing for a type: `u32`, `Vec_u32`, `u32_String`.
65pub fn instance_name(t: &Type) -> String {
66    let mut out = String::new();
67    for c in type_text(t).chars() {
68        if c.is_alphanumeric() || c == '_' {
69            out.push(c);
70        } else if !out.is_empty() && !out.ends_with('_') {
71            out.push('_');
72        }
73    }
74    out.trim_end_matches('_').to_string()
75}
76
77impl ModelAttr {
78    /// The labels and specs of the obligations: `refines` first, then the `ensures`.
79    pub fn obligations(&self) -> Vec<(String, &SpecRef)> {
80        let mut out = Vec::new();
81        if let Some(r) = &self.refines {
82            out.push(("refines".to_string(), r));
83        }
84        for (l, s) in &self.ensures {
85            out.push((l.clone(), s));
86        }
87        out
88    }
89
90    /// `true` for `obligations = per_instance`.
91    pub fn per_instance(&self) -> bool {
92        self.obligations == Some(ObligationMode::PerInstance)
93    }
94
95    /// The obligations with their labels in the lockfile: `<label>.<type>` per type of
96    /// `instances` for `obligations = per_instance`, with the index of the type.
97    pub fn obligation_labels(&self) -> Vec<(String, &SpecRef, Option<usize>)> {
98        let mut out = Vec::new();
99        for (label, spec) in self.obligations() {
100            if self.per_instance() {
101                for (i, t) in self.instances.iter().enumerate() {
102                    out.push((format!("{label}.{}", instance_name(t)), spec, Some(i)));
103                }
104            } else {
105                out.push((label, spec, None));
106            }
107        }
108        out
109    }
110
111    /// The keys of `inner` over the keys of `self`.
112    pub fn merge(&self, inner: &ModelAttr) -> ModelAttr {
113        ModelAttr {
114            refines: inner.refines.clone().or_else(|| self.refines.clone()),
115            requires: inner.requires.clone().or_else(|| self.requires.clone()),
116            ensures: if inner.ensures.is_empty() {
117                self.ensures.clone()
118            } else {
119                inner.ensures.clone()
120            },
121            check: inner.check.or(self.check),
122            strategy: inner.strategy.clone().or_else(|| self.strategy.clone()),
123            instances: if inner.instances.is_empty() {
124                self.instances.clone()
125            } else {
126                inner.instances.clone()
127            },
128            obligations: inner.obligations.or(self.obligations),
129        }
130    }
131}
132
133fn spec_value(input: syn::parse::ParseStream) -> syn::Result<SpecRef> {
134    if input.peek(LitStr) {
135        let s: LitStr = input.parse()?;
136        Ok(SpecRef::Lean(s.value()))
137    } else {
138        Ok(SpecRef::Path(input.parse()?))
139    }
140}
141
142/// Parses the arguments of `#[leanfran::model(..)]`.
143pub fn parse_model_args(tokens: TokenStream) -> syn::Result<ModelAttr> {
144    let mut attr = ModelAttr::default();
145    let parser = syn::meta::parser(|meta| {
146        if meta.path.is_ident("refines") {
147            attr.refines = Some(spec_value(meta.value()?)?);
148        } else if meta.path.is_ident("requires") {
149            attr.requires = Some(spec_value(meta.value()?)?);
150        } else if meta.path.is_ident("ensures") {
151            meta.parse_nested_meta(|inner| {
152                let Some(label) = inner.path.get_ident() else {
153                    return Err(inner.error("expected a label"));
154                };
155                let label = label.to_string();
156                if attr.ensures.iter().any(|(l, _)| *l == label) || label == "refines" {
157                    return Err(inner.error(format!("the label `{label}` is used twice")));
158                }
159                attr.ensures.push((label, spec_value(inner.value()?)?));
160                Ok(())
161            })?;
162        } else if meta.path.is_ident("check") {
163            let b: LitBool = meta.value()?.parse()?;
164            attr.check = Some(b.value);
165        } else if meta.path.is_ident("strategy") {
166            attr.strategy = Some(meta.value()?.parse()?);
167        } else if meta.path.is_ident("instances") {
168            let input = meta.value()?;
169            let content;
170            syn::bracketed!(content in input);
171            let types =
172                syn::punctuated::Punctuated::<Type, syn::Token![,]>::parse_terminated(&content)?;
173            attr.instances = types.into_iter().collect();
174        } else if meta.path.is_ident("obligations") {
175            let mode: syn::Ident = meta.value()?.parse()?;
176            attr.obligations = Some(match mode.to_string().as_str() {
177                "generic" => ObligationMode::Generic,
178                "per_instance" => ObligationMode::PerInstance,
179                _ => {
180                    return Err(syn::Error::new(
181                        mode.span(),
182                        "expected `generic` or `per_instance`",
183                    ))
184                }
185            });
186        } else {
187            return Err(meta.error(
188                "expected `refines`, `requires`, `ensures(..)`, `check`, `strategy`, `instances` or `obligations`",
189            ));
190        }
191        Ok(())
192    });
193    parser.parse2(tokens)?;
194    Ok(attr)
195}
196
197/// `true` for `#[model]`, `#[leanfran::model]` and `#[::leanfran::model]`.
198pub fn is_attr(attr: &Attribute, name: &str) -> bool {
199    let segs: Vec<String> = attr
200        .path()
201        .segments
202        .iter()
203        .map(|s| s.ident.to_string())
204        .collect();
205    matches!(segs.as_slice(), [n] if n == name)
206        || matches!(segs.as_slice(), [c, n] if c == "leanfran" && n == name)
207}
208
209/// The keys of the `#[leanfran::model]` attributes of `attrs`, if there is one.
210pub fn model_attr(attrs: &[Attribute]) -> syn::Result<Option<ModelAttr>> {
211    let mut out: Option<ModelAttr> = None;
212    for a in attrs.iter().filter(|a| is_attr(a, "model")) {
213        let parsed = match &a.meta {
214            syn::Meta::Path(_) => ModelAttr::default(),
215            syn::Meta::List(l) => parse_model_args(l.tokens.clone())?,
216            syn::Meta::NameValue(nv) => {
217                return Err(syn::Error::new(
218                    nv.span(),
219                    "expected `#[leanfran::model(..)]`",
220                ))
221            }
222        };
223        out = Some(match out {
224            Some(o) => o.merge(&parsed),
225            None => parsed,
226        });
227    }
228    Ok(out)
229}
230
231pub fn path_string(p: &Path) -> String {
232    let mut s = String::new();
233    if p.leading_colon.is_some() {
234        s.push_str("::");
235    }
236    let segs: Vec<String> = p.segments.iter().map(|s| s.ident.to_string()).collect();
237    s.push_str(&segs.join("::"));
238    s
239}
240
241/* Signatures */
242
243/// How a parameter is passed.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum Mode {
246    Value,
247    Ref,
248    RefMut,
249}
250
251#[derive(Debug, Clone)]
252pub struct Param {
253    /// The name of the parameter (`self` for the receiver, `arg<i>` for patterns).
254    pub name: String,
255    pub mode: Mode,
256    /// The type, without the reference for `Ref` and `RefMut`; `None` for `self` receivers.
257    pub ty: Option<Type>,
258    pub is_self: bool,
259}
260
261/// A type parameter of a generic function, with the traits of its bounds (the last segments of
262/// their paths).
263#[derive(Debug, Clone)]
264pub struct TypeParam {
265    pub name: String,
266    pub bounds: Vec<String>,
267}
268
269#[derive(Debug, Clone)]
270pub struct Sig {
271    /// The type parameters of the impl block, then of the function.
272    pub generics: Vec<TypeParam>,
273    /// The number of the type parameters of the impl block.
274    pub impl_generics: usize,
275    pub params: Vec<Param>,
276    /// `None` for `()`.
277    pub ret: Option<Type>,
278}
279
280impl Sig {
281    /// The parameters passed as `&mut`, whose values after the call are results of the model.
282    pub fn muts(&self) -> Vec<&Param> {
283        self.params
284            .iter()
285            .filter(|p| p.mode == Mode::RefMut)
286            .collect()
287    }
288}
289
290fn is_unit(t: &Type) -> bool {
291    matches!(t, Type::Tuple(t) if t.elems.is_empty())
292}
293
294fn bounds_of(
295    bounds: &syn::punctuated::Punctuated<syn::TypeParamBound, syn::Token![+]>,
296) -> Vec<String> {
297    bounds
298        .iter()
299        .filter_map(|b| match b {
300            syn::TypeParamBound::Trait(t) => t.path.segments.last().map(|s| s.ident.to_string()),
301            _ => None,
302        })
303        .collect()
304}
305
306/// The type parameters of `generics` (the impl block's, then the function's), with the bounds
307/// of their `where` clauses.
308pub fn type_params(generics: &[&syn::Generics]) -> syn::Result<Vec<TypeParam>> {
309    let mut out: Vec<TypeParam> = Vec::new();
310    for g in generics {
311        for p in &g.params {
312            match p {
313                syn::GenericParam::Lifetime(_) => {}
314                syn::GenericParam::Const(c) => {
315                    return Err(syn::Error::new(
316                        c.span(),
317                        "leanfran::model: const generics are not supported",
318                    ))
319                }
320                syn::GenericParam::Type(t) => out.push(TypeParam {
321                    name: t.ident.to_string(),
322                    bounds: bounds_of(&t.bounds),
323                }),
324            }
325        }
326        if let Some(w) = &g.where_clause {
327            for pred in &w.predicates {
328                let syn::WherePredicate::Type(pt) = pred else {
329                    continue;
330                };
331                let Type::Path(tp) = &pt.bounded_ty else {
332                    continue;
333                };
334                let Some(id) = tp.path.get_ident() else {
335                    continue;
336                };
337                if let Some(p) = out.iter_mut().find(|p| *id == p.name) {
338                    p.bounds.extend(bounds_of(&pt.bounds));
339                }
340            }
341        }
342    }
343    Ok(out)
344}
345
346/// The signature of a function (a method of an impl block with the generics `outer`), or an
347/// error for the signatures `#[model]` does not support.
348pub fn signature(sig: &syn::Signature, outer: Option<&syn::Generics>) -> syn::Result<Sig> {
349    let impl_generics = match outer {
350        Some(g) => type_params(&[g])?.len(),
351        None => 0,
352    };
353    let mut all = Vec::new();
354    all.extend(outer);
355    all.push(&sig.generics);
356    let generics = type_params(&all)?;
357    if sig.asyncness.is_some()
358        || matches!(sig.safety, syn::Safety::Unsafe(_))
359        || sig.variadic.is_some()
360    {
361        return Err(syn::Error::new(
362            sig.span(),
363            "leanfran::model: async, unsafe and variadic functions are not supported",
364        ));
365    }
366    let mut params = Vec::new();
367    for (i, input) in sig.inputs.iter().enumerate() {
368        match input {
369            FnArg::Receiver(r) => {
370                let mode = match &r.kind {
371                    syn::ReceiverKind::Reference(_, _, Some(_)) => Mode::RefMut,
372                    syn::ReceiverKind::Reference(_, _, None) => Mode::Ref,
373                    syn::ReceiverKind::Typed(_, ty) => match &**ty {
374                        Type::Reference(t) if t.mutability.is_some() => Mode::RefMut,
375                        Type::Reference(_) => Mode::Ref,
376                        _ => Mode::Value,
377                    },
378                    _ => Mode::Value,
379                };
380                params.push(Param {
381                    name: "self".to_string(),
382                    mode,
383                    ty: None,
384                    is_self: true,
385                });
386            }
387            FnArg::Typed(pt) => {
388                let name = match &*pt.pat {
389                    Pat::Ident(pi) if pi.subpat.is_none() => pi.ident.to_string(),
390                    _ => format!("arg{i}"),
391                };
392                let (mode, ty) = match &*pt.ty {
393                    Type::Reference(r) if r.mutability.is_some() => {
394                        (Mode::RefMut, (*r.elem).clone())
395                    }
396                    Type::Reference(r) => (Mode::Ref, (*r.elem).clone()),
397                    t => (Mode::Value, t.clone()),
398                };
399                params.push(Param {
400                    name,
401                    mode,
402                    ty: Some(ty),
403                    is_self: false,
404                });
405            }
406        }
407    }
408    let ret = match &sig.output {
409        ReturnType::Default => None,
410        ReturnType::Type(_, t) if is_unit(t) => None,
411        ReturnType::Type(_, t) => Some((**t).clone()),
412    };
413    Ok(Sig {
414        generics,
415        impl_generics,
416        params,
417        ret,
418    })
419}
420
421/* Loops */
422
423/// A loop of a function body or a macro call (whose loops are not visible).
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum LoopNode {
426    Loop {
427        label: Option<String>,
428        line: usize,
429        column: usize,
430        children: Vec<LoopNode>,
431    },
432    Macro {
433        start: (usize, usize),
434        end: (usize, usize),
435    },
436}
437
438struct LoopVisitor {
439    stack: Vec<Vec<LoopNode>>,
440}
441
442impl LoopVisitor {
443    fn enter(&mut self) {
444        self.stack.push(Vec::new());
445    }
446
447    fn leave(&mut self, label: Option<&syn::Label>, span: proc_macro2::Span) {
448        let children = self.stack.pop().unwrap_or_default();
449        let start = span.start();
450        self.stack.last_mut().unwrap().push(LoopNode::Loop {
451            label: label.map(|l| l.name.ident.to_string()),
452            line: start.line,
453            column: start.column + 1,
454            children,
455        });
456    }
457
458    fn mac(&mut self, span: proc_macro2::Span) {
459        let (s, e) = (span.start(), span.end());
460        self.stack.last_mut().unwrap().push(LoopNode::Macro {
461            start: (s.line, s.column),
462            end: (e.line, e.column),
463        });
464    }
465}
466
467impl<'ast> Visit<'ast> for LoopVisitor {
468    fn visit_expr_for_loop(&mut self, e: &'ast syn::ExprForLoop) {
469        self.visit_expr(&e.expr);
470        self.enter();
471        self.visit_block(&e.body);
472        self.leave(e.label.as_ref(), e.for_token.span);
473    }
474
475    fn visit_expr_while(&mut self, e: &'ast syn::ExprWhile) {
476        self.enter();
477        self.visit_expr(&e.cond);
478        self.visit_block(&e.body);
479        self.leave(e.label.as_ref(), e.while_token.span);
480    }
481
482    fn visit_expr_loop(&mut self, e: &'ast syn::ExprLoop) {
483        self.enter();
484        self.visit_block(&e.body);
485        self.leave(e.label.as_ref(), e.loop_token.span);
486    }
487
488    fn visit_macro(&mut self, m: &'ast syn::Macro) {
489        self.mac(m.span());
490    }
491
492    fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
493
494    fn visit_item(&mut self, _: &'ast Item) {}
495}
496
497/// The loops of a function body, as a tree of nesting.
498pub fn loops(block: &syn::Block) -> Vec<LoopNode> {
499    let mut v = LoopVisitor {
500        stack: vec![Vec::new()],
501    };
502    v.visit_block(block);
503    v.stack.pop().unwrap_or_default()
504}
505
506/* Hashes */
507
508fn strip_docs(attrs: &mut Vec<Attribute>) {
509    attrs.retain(|a| !a.path().is_ident("doc"));
510}
511
512struct DocStripper;
513
514impl syn::visit_mut::VisitMut for DocStripper {
515    fn visit_attributes_mut(&mut self, attrs: &mut Vec<Attribute>) {
516        strip_docs(attrs);
517    }
518}
519
520fn token_text(ts: TokenStream, out: &mut String) {
521    for t in ts {
522        match t {
523            TokenTree::Group(g) => {
524                let (o, c) = match g.delimiter() {
525                    proc_macro2::Delimiter::Parenthesis => ("(", ")"),
526                    proc_macro2::Delimiter::Brace => ("{", "}"),
527                    proc_macro2::Delimiter::Bracket => ("[", "]"),
528                    proc_macro2::Delimiter::None => ("", ""),
529                };
530                out.push_str(o);
531                token_text(g.stream(), out);
532                out.push_str(c);
533                out.push(' ');
534            }
535            TokenTree::Punct(p) => {
536                out.push(p.as_char());
537                if p.spacing() == proc_macro2::Spacing::Alone {
538                    out.push(' ');
539                }
540            }
541            t => {
542                out.push_str(&t.to_string());
543                out.push(' ');
544            }
545        }
546    }
547}
548
549/// `sha256:<hex>` of the tokens of `item` without its doc comments.
550pub fn item_hash<T: ToTokens + Clone>(item: &T, strip: impl FnOnce(&mut T)) -> String {
551    let mut item = item.clone();
552    strip(&mut item);
553    let mut text = String::new();
554    token_text(item.to_token_stream(), &mut text);
555    let digest = Sha256::digest(text.as_bytes());
556    let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
557    format!("sha256:{hex}")
558}
559
560fn fn_hash(f: &syn::ItemFn) -> String {
561    item_hash(f, |f| {
562        syn::visit_mut::VisitMut::visit_item_fn_mut(&mut DocStripper, f)
563    })
564}
565
566fn method_hash(f: &syn::ImplItemFn) -> String {
567    item_hash(f, |f| {
568        syn::visit_mut::VisitMut::visit_impl_item_fn_mut(&mut DocStripper, f)
569    })
570}
571
572fn type_hash(i: &Item) -> String {
573    item_hash(i, |i| {
574        syn::visit_mut::VisitMut::visit_item_mut(&mut DocStripper, i)
575    })
576}
577
578/* Crate scan */
579
580/// The last identifier of a type path (`crate::inv::Item<T>` → `Item`).
581pub fn type_name(t: &Type) -> Option<String> {
582    match t {
583        Type::Path(p) => p.path.segments.last().map(|s| s.ident.to_string()),
584        Type::Reference(r) => type_name(&r.elem),
585        Type::Paren(p) => type_name(&p.elem),
586        Type::Group(g) => type_name(&g.elem),
587        _ => None,
588    }
589}
590
591/// A modelled function of the crate.
592#[derive(Debug, Clone)]
593pub struct ModelFn {
594    /// `crate::a::f`, `crate::a::Item::f` or `crate::a::<Item as Trait>::f`.
595    pub rust: String,
596    /// Module path below the crate root, including inline modules.
597    pub module: Vec<String>,
598    pub self_ty: Option<String>,
599    pub trait_name: Option<String>,
600    /// The paths of the type and the trait of the impl block, as written.
601    pub self_path: Option<Vec<String>>,
602    pub trait_path: Option<Vec<String>>,
603    pub name: String,
604    pub attr: ModelAttr,
605    pub sig: Sig,
606    pub loops: Vec<LoopNode>,
607    /// Path of the file relative to the crate root.
608    pub file: String,
609    pub line: usize,
610}
611
612impl ModelFn {
613    /// The name of the rustdoc file: `<module path>::<Self>::<Trait>::<f>.md` with the module
614    /// path of `module_path!()`.
615    pub fn doc_file(&self, crate_ident: &str) -> String {
616        let mut parts = vec![crate_ident.to_string()];
617        parts.extend(self.module.iter().cloned());
618        parts.extend(self.self_ty.iter().cloned());
619        parts.extend(self.trait_name.iter().cloned());
620        parts.push(self.name.clone());
621        format!("{}.md", parts.join("::"))
622    }
623
624    /// The Rust expression calling the function from a sibling module (`super::f`).
625    pub fn callee(&self) -> String {
626        match (&self.self_ty, &self.trait_name) {
627            (Some(t), Some(tr)) => format!("<{t} as {tr}>::{}", self.name),
628            (Some(t), None) => format!("{t}::{}", self.name),
629            _ => self.name.clone(),
630        }
631    }
632}
633
634/// A `use` of a module: the local name and the path it stands for.
635#[derive(Debug, Clone, Default)]
636pub struct Uses {
637    pub names: BTreeMap<String, Vec<String>>,
638    pub globs: Vec<Vec<String>>,
639}
640
641/// A function of `#[leanfran::opaque]`, or a method of an inherent impl block with it.
642#[derive(Debug, Clone)]
643pub struct OpaqueFn {
644    /// The unit name: `crate::<module>::<name>`, or `crate::<module>::<Type>::<name>`.
645    pub unit: String,
646    /// The file, relative to the crate.
647    pub file: String,
648    /// The module path.
649    pub module: Vec<String>,
650    /// The type of the impl block of a method, as written there.
651    pub self_path: Option<Vec<String>>,
652    pub name: String,
653}
654
655impl OpaqueFn {
656    /// The file stem of its generated model below `leanfran/opaque/<file hash>/`: `<name>`,
657    /// or `<Type>.<name>` for a method.
658    pub fn file_stem(&self) -> String {
659        match self.self_path.as_ref().and_then(|p| p.last()) {
660            Some(t) => format!("{t}.{}", self.name),
661            None => self.name.clone(),
662        }
663    }
664}
665
666/// What a scan of `src/**/*.rs` finds.
667#[derive(Debug, Default)]
668pub struct CrateItems {
669    pub models: Vec<ModelFn>,
670    /// `#[leanfran::opaque]` functions and methods.
671    pub opaque: Vec<OpaqueFn>,
672    /// Hash of every function, method and type, by unit name.
673    pub hashes: BTreeMap<String, String>,
674    /// `use` declarations, by module path.
675    pub uses: BTreeMap<Vec<String>, Uses>,
676    /// `#[leanfran::exported("<Lean name>")]` functions, by unit name: the arguments and the
677    /// file.
678    pub exported: BTreeMap<String, (Exported, String)>,
679    /// Inline and file modules, by module path.
680    pub modules: Vec<Vec<String>>,
681    pub errors: Vec<String>,
682}
683
684fn unit_name(module: &[String], rest: &[&str]) -> String {
685    let mut s = String::from("crate");
686    for m in module {
687        s.push_str("::");
688        s.push_str(m);
689    }
690    for r in rest {
691        s.push_str("::");
692        s.push_str(r);
693    }
694    s
695}
696
697/// The unit name of a trait method: `crate::a::<Item as Trait>::f`.
698pub fn trait_unit(module: &[String], self_ty: &str, trait_name: &str, f: &str) -> String {
699    let mut s = unit_name(module, &[]);
700    s.push_str(&format!("::<{self_ty} as {trait_name}>::{f}"));
701    s
702}
703
704/// The arguments of `#[leanfran::exported(..)]`: the Lean name, and for a generic function
705/// generated from `rust_instances` the type parameters of the Lean function and its
706/// instantiations by Rust type (`type_params = ["α"], instances = [("u32", "f.inst_U32")]`).
707#[derive(Debug, Clone, Default, PartialEq)]
708pub struct Exported {
709    pub lean: String,
710    pub type_params: Vec<String>,
711    pub instances: Vec<(String, String)>,
712}
713
714/// The arguments of an `exported` attribute.
715pub fn parse_exported(a: &Attribute) -> Option<Exported> {
716    a.parse_args_with(|input: syn::parse::ParseStream| {
717        let lean: LitStr = input.parse()?;
718        let mut e = Exported {
719            lean: lean.value(),
720            ..Exported::default()
721        };
722        while input.peek(syn::Token![,]) {
723            input.parse::<syn::Token![,]>()?;
724            if input.is_empty() {
725                break;
726            }
727            let key: syn::Ident = input.parse()?;
728            input.parse::<syn::Token![=]>()?;
729            let content;
730            syn::bracketed!(content in input);
731            if key == "type_params" {
732                let names =
733                    syn::punctuated::Punctuated::<LitStr, syn::Token![,]>::parse_terminated(&content)?;
734                e.type_params = names.iter().map(LitStr::value).collect();
735            } else if key == "instances" {
736                let pairs = syn::punctuated::Punctuated::<syn::ExprTuple, syn::Token![,]>::parse_terminated(
737                    &content,
738                )?;
739                for p in pairs {
740                    let s: Vec<String> = p
741                        .elems
742                        .iter()
743                        .filter_map(|x| match x {
744                            syn::Expr::Lit(syn::ExprLit {
745                                lit: syn::Lit::Str(s),
746                                ..
747                            }) => Some(s.value()),
748                            _ => None,
749                        })
750                        .collect();
751                    if let [ty, lean] = s.as_slice() {
752                        e.instances.push((ty.clone(), lean.clone()));
753                    }
754                }
755            } else {
756                return Err(syn::Error::new(key.span(), "unknown key"));
757            }
758        }
759        Ok(e)
760    })
761    .ok()
762}
763
764/// A Rust type of an instance in the form both sides write: without spaces and the paths of
765/// `leanfran` (`(rt::Nat, String)` and `(leanfran::Nat,String)` are `(Nat,String)`).
766pub fn normalize_type(t: &str) -> String {
767    let t: String = t.chars().filter(|c| !c.is_whitespace()).collect();
768    t.replace("::leanfran::runtime::", "")
769        .replace("::leanfran::", "")
770        .replace("leanfran::runtime::", "")
771        .replace("leanfran::", "")
772        .replace("rt::", "")
773}
774
775fn exported_name(attrs: &[Attribute]) -> Option<Exported> {
776    attrs
777        .iter()
778        .filter(|a| is_attr(a, "exported"))
779        .find_map(parse_exported)
780}
781
782fn collect_use(tree: &syn::UseTree, prefix: &mut Vec<String>, uses: &mut Uses) {
783    match tree {
784        syn::UseTree::Path(p) => {
785            prefix.push(p.ident.to_string());
786            collect_use(&p.tree, prefix, uses);
787            prefix.pop();
788        }
789        syn::UseTree::Name(n) => {
790            let name = n.ident.to_string();
791            if name == "self" {
792                if let Some(last) = prefix.last() {
793                    uses.names.insert(last.clone(), prefix.clone());
794                }
795            } else {
796                let mut p = prefix.clone();
797                p.push(name.clone());
798                uses.names.insert(name, p);
799            }
800        }
801        syn::UseTree::Rename(r) => {
802            let mut p = prefix.clone();
803            if r.ident != "self" {
804                p.push(r.ident.to_string());
805            }
806            uses.names.insert(r.rename.to_string(), p);
807        }
808        syn::UseTree::Glob(_) => uses.globs.push(prefix.clone()),
809        syn::UseTree::Group(g) => {
810            for t in &g.items {
811                collect_use(t, prefix, uses);
812            }
813        }
814    }
815}
816
817struct Scanner<'a> {
818    file: String,
819    module: Vec<String>,
820    out: &'a mut CrateItems,
821}
822
823impl Scanner<'_> {
824    fn error(&mut self, span: proc_macro2::Span, msg: impl std::fmt::Display) {
825        let at = span.start();
826        self.out.errors.push(format!(
827            "{}:{}:{}: {msg}",
828            self.file,
829            at.line,
830            at.column + 1
831        ));
832    }
833
834    fn model_fn(
835        &mut self,
836        attr: ModelAttr,
837        sig: &syn::Signature,
838        block: &syn::Block,
839        (self_ty, trait_name): (Option<String>, Option<String>),
840        paths: (Option<Vec<String>>, Option<Vec<String>>),
841        outer: Option<&syn::Generics>,
842    ) {
843        let name = sig.ident.to_string();
844        let rust = match (&self_ty, &trait_name) {
845            (Some(t), Some(tr)) => trait_unit(&self.module, t, tr, &name),
846            (Some(t), None) => unit_name(&self.module, &[t, &name]),
847            _ => unit_name(&self.module, &[&name]),
848        };
849        let parsed = match signature(sig, outer) {
850            Ok(s) => s,
851            Err(e) => {
852                self.error(e.span(), e);
853                return;
854            }
855        };
856        self.out.models.push(ModelFn {
857            rust,
858            module: self.module.clone(),
859            self_ty,
860            trait_name,
861            self_path: paths.0,
862            trait_path: paths.1,
863            name,
864            attr,
865            sig: parsed,
866            loops: loops(block),
867            file: self.file.clone(),
868            line: sig.ident.span().start().line,
869        });
870    }
871
872    fn item_impl(&mut self, i: &syn::ItemImpl) {
873        let Some(self_ty) = type_name(&i.self_ty) else {
874            return;
875        };
876        let trait_name = i
877            .trait_
878            .as_ref()
879            .and_then(|(p, _)| p.segments.last().map(|s| s.ident.to_string()));
880        let segs = |p: &Path| {
881            p.segments
882                .iter()
883                .map(|s| s.ident.to_string())
884                .collect::<Vec<_>>()
885        };
886        let self_path = match &*i.self_ty {
887            Type::Path(p) => Some(segs(&p.path)),
888            _ => None,
889        };
890        let trait_path = i.trait_.as_ref().map(|(p, _)| segs(p));
891        let opaque = trait_name.is_none() && i.attrs.iter().any(|a| is_attr(a, "opaque"));
892        let outer = match model_attr(&i.attrs) {
893            Ok(a) => a,
894            Err(e) => {
895                self.error(e.span(), e);
896                return;
897            }
898        };
899        for item in &i.items {
900            let ImplItem::Fn(f) = item else { continue };
901            let name = f.sig.ident.to_string();
902            let unit = match &trait_name {
903                Some(tr) => trait_unit(&self.module, &self_ty, tr, &name),
904                None => unit_name(&self.module, &[&self_ty, &name]),
905            };
906            self.out.hashes.insert(unit.clone(), method_hash(f));
907            if opaque {
908                self.out.opaque.push(OpaqueFn {
909                    unit: unit.clone(),
910                    file: self.file.clone(),
911                    module: self.module.clone(),
912                    self_path: self_path.clone(),
913                    name: name.clone(),
914                });
915            }
916            if let Some(n) = exported_name(&f.attrs) {
917                self.out.exported.insert(unit, (n, self.file.clone()));
918            }
919            let inner = match model_attr(&f.attrs) {
920                Ok(a) => a,
921                Err(e) => {
922                    self.error(e.span(), e);
923                    continue;
924                }
925            };
926            let attr = match (&outer, inner) {
927                (Some(o), Some(i)) => o.merge(&i),
928                (Some(o), None) => o.clone(),
929                (None, Some(i)) => i,
930                (None, None) => continue,
931            };
932            self.model_fn(
933                attr,
934                &f.sig,
935                &f.block,
936                (Some(self_ty.clone()), trait_name.clone()),
937                (self_path.clone(), trait_path.clone()),
938                Some(&i.generics),
939            );
940        }
941    }
942}
943
944impl<'ast> Visit<'ast> for Scanner<'_> {
945    fn visit_item(&mut self, item: &'ast Item) {
946        match item {
947            Item::Fn(f) => {
948                let name = f.sig.ident.to_string();
949                let unit = unit_name(&self.module, &[&name]);
950                self.out.hashes.insert(unit.clone(), fn_hash(f));
951                if f.attrs.iter().any(|a| is_attr(a, "opaque")) {
952                    self.out.opaque.push(OpaqueFn {
953                        unit: unit.clone(),
954                        file: self.file.clone(),
955                        module: self.module.clone(),
956                        self_path: None,
957                        name: name.clone(),
958                    });
959                }
960                if let Some(n) = exported_name(&f.attrs) {
961                    self.out.exported.insert(unit, (n, self.file.clone()));
962                }
963                match model_attr(&f.attrs) {
964                    Ok(Some(attr)) => {
965                        self.model_fn(attr, &f.sig, &f.block, (None, None), (None, None), None)
966                    }
967                    Ok(None) => {}
968                    Err(e) => self.error(e.span(), e),
969                }
970            }
971            Item::Struct(s) => {
972                let unit = unit_name(&self.module, &[&s.ident.to_string()]);
973                self.out.hashes.insert(unit, type_hash(item));
974            }
975            Item::Enum(e) => {
976                let unit = unit_name(&self.module, &[&e.ident.to_string()]);
977                self.out.hashes.insert(unit, type_hash(item));
978            }
979            Item::Impl(i) => self.item_impl(i),
980            Item::Use(u) => {
981                let uses = self.out.uses.entry(self.module.clone()).or_default();
982                collect_use(&u.tree, &mut Vec::new(), uses);
983            }
984            Item::Mod(m) => {
985                self.module.push(m.ident.to_string());
986                self.out.modules.push(self.module.clone());
987                if let Some((_, items)) = &m.content {
988                    for i in items {
989                        self.visit_item(i);
990                    }
991                }
992                self.module.pop();
993            }
994            _ => {}
995        }
996    }
997}
998
999/// Scans the parsed file `ast` (at `file`, relative to the crate root, in module `module`).
1000pub fn scan_file(file: &str, module: Vec<String>, ast: &syn::File, out: &mut CrateItems) {
1001    if !out.modules.contains(&module) {
1002        out.modules.push(module.clone());
1003    }
1004    let mut s = Scanner {
1005        file: file.to_string(),
1006        module,
1007        out,
1008    };
1009    for item in &ast.items {
1010        s.visit_item(item);
1011    }
1012}
1013
1014/// Module path of a file relative to the crate root: `src/a/b.rs` and `src/a/b/mod.rs` →
1015/// `[a, b]`; `src/lib.rs`, `src/main.rs` and `src/bin/*.rs` are crate roots.
1016pub fn file_module(rel: &str) -> Vec<String> {
1017    let rest = rel.strip_prefix("src/").unwrap_or(rel);
1018    if rest == "lib.rs" || rest == "main.rs" || rest.starts_with("bin/") {
1019        return Vec::new();
1020    }
1021    let mut parts: Vec<String> = rest
1022        .trim_end_matches(".rs")
1023        .split('/')
1024        .map(str::to_string)
1025        .collect();
1026    if parts.last().is_some_and(|p| p == "mod") {
1027        parts.pop();
1028    }
1029    parts
1030}
1031
1032impl CrateItems {
1033    /// The absolute path (segments after `crate`) that `path` names in `module`, following
1034    /// the `use` declarations of the modules.
1035    pub fn resolve(&self, module: &[String], path: &Path) -> Vec<String> {
1036        let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
1037        self.resolve_segments(module, &segs, 0)
1038    }
1039
1040    pub fn resolve_segments(
1041        &self,
1042        module: &[String],
1043        segs: &[String],
1044        depth: usize,
1045    ) -> Vec<String> {
1046        let Some(first) = segs.first() else {
1047            return module.to_vec();
1048        };
1049        match first.as_str() {
1050            "crate" => return segs[1..].to_vec(),
1051            "self" => {
1052                let mut out = module.to_vec();
1053                out.extend(segs[1..].iter().cloned());
1054                return out;
1055            }
1056            "super" => {
1057                let mut out = module.to_vec();
1058                let mut rest = segs;
1059                while rest.first().is_some_and(|s| s == "super") {
1060                    out.pop();
1061                    rest = &rest[1..];
1062                }
1063                out.extend(rest.iter().cloned());
1064                return out;
1065            }
1066            _ => {}
1067        }
1068        if depth < 16 {
1069            if let Some(u) = self.uses.get(module) {
1070                if let Some(target) = u.names.get(first) {
1071                    let mut full = target.clone();
1072                    full.extend(segs[1..].iter().cloned());
1073                    let parent = module.to_vec();
1074                    return self.resolve_segments(&parent, &full, depth + 1);
1075                }
1076            }
1077        }
1078        let mut local = module.to_vec();
1079        local.push(first.clone());
1080        let known_local = self.modules.contains(&local)
1081            || self
1082                .hashes
1083                .keys()
1084                .any(|k| k.starts_with(&unit_name(&local, &[])));
1085        if !known_local && depth < 16 {
1086            if let Some(u) = self.uses.get(module) {
1087                for g in &u.globs {
1088                    let mut full = g.clone();
1089                    full.extend(segs.iter().cloned());
1090                    let resolved = self.resolve_segments(module, &full, depth + 1);
1091                    let mut parent = resolved.clone();
1092                    parent.pop();
1093                    if self.modules.contains(&parent) {
1094                        return resolved;
1095                    }
1096                }
1097            }
1098        }
1099        let mut out = module.to_vec();
1100        out.extend(segs.iter().cloned());
1101        out
1102    }
1103}