1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use std::io::Write;
use std::path::{Path, PathBuf};

#[cfg(feature = "dune")]
mod dune;

#[cfg(feature = "dune")]
pub use dune::Dune;

struct Source {
    path: PathBuf,
    functions: Vec<String>,
    types: Vec<String>,
}

pub struct Sigs {
    base_dir: PathBuf,
    output: PathBuf,
    source: Vec<Source>,
}

fn strip_quotes(s: &str) -> &str {
    s.trim_start_matches('"').trim_end_matches('"')
}

fn snake_case(s: &str) -> String {
    let mut dest = String::new();
    for c in s.chars() {
        if !dest.is_empty() && c.is_uppercase() {
            dest.push('_');
        }
        dest.push(c.to_ascii_lowercase());
    }
    dest
}

fn handle(attrs: Vec<syn::Attribute>, mut f: impl FnMut(&str)) {
    for attr in attrs {
        let attr_name = attr
            .path
            .segments
            .iter()
            .map(|x| x.ident.to_string())
            .collect::<Vec<_>>()
            .join("::");
        if attr_name == "sig" || attr_name == "ocaml::sig" {
            match &attr.tokens.into_iter().collect::<Vec<_>>()[..] {
                [proc_macro2::TokenTree::Group(g)] => {
                    let v = g.stream().into_iter().collect::<Vec<_>>();
                    if v.len() != 1 {
                        panic!("Invalid signature: {g}");
                    }
                    if let [proc_macro2::TokenTree::Literal(ref sig)] = v[..] {
                        let s = sig.to_string();
                        let ty = strip_quotes(&s);
                        f(ty)
                    }
                }
                [] => f(""),
                x => {
                    panic!("Invalid signature: {x:?}");
                }
            }
        }
    }
}

impl Sigs {
    pub fn new(p: impl AsRef<Path>) -> Sigs {
        let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
        let base_dir = root.join("src");
        Sigs {
            base_dir,
            output: p.as_ref().to_path_buf(),
            source: Vec::new(),
        }
    }

    pub fn with_source_dir(mut self, p: impl AsRef<Path>) -> Sigs {
        self.base_dir = p.as_ref().to_path_buf();
        self
    }

    fn parse(&mut self, path: &Path) -> Result<(), std::io::Error> {
        let files = std::fs::read_dir(path)?;

        for file in files {
            let file = file?;
            if file.metadata()?.is_dir() {
                self.parse(&file.path())?;
                continue;
            }

            if Some(Some("rs")) != file.path().extension().map(|x| x.to_str()) {
                continue;
            }

            let path = file.path();
            let mut src = Source {
                path: path.clone(),
                functions: Vec::new(),
                types: Vec::new(),
            };
            let s = std::fs::read_to_string(&path)?;
            let t: syn::File = syn::parse_str(&s)
                .unwrap_or_else(|_| panic!("Unable to parse input file: {}", path.display()));

            for item in t.items {
                match item {
                    syn::Item::Fn(item_fn) => {
                        let name = &item_fn.sig.ident;
                        handle(item_fn.attrs, |ty| {
                            let def = if item_fn.sig.inputs.len() > 5 {
                                format!("external {name}: {ty} = \"{name}_bytecode\" \"{name}\"")
                            } else {
                                format!("external {name}: {ty} = \"{name}\"")
                            };
                            src.functions.push(def);
                        });
                    }
                    syn::Item::Struct(item) => {
                        let name = snake_case(&item.ident.to_string());
                        handle(item.attrs, |ty| {
                            let def = if ty.is_empty() {
                                format!("type {name}")
                            } else if !ty.trim_start().starts_with('{') {
                                format!("type {}{name}{} = {ty}", '{', '}')
                            } else {
                                format!("type {name} = {ty}")
                            };
                            src.types.push(def);
                        });
                    }
                    syn::Item::Enum(item) => {
                        let name = snake_case(&item.ident.to_string());
                        handle(item.attrs, |ty| {
                            let def = if ty.is_empty() {
                                format!("type {name}")
                            } else {
                                format!("type {name} = {ty}")
                            };
                            src.types.push(def);
                        });
                    }
                    syn::Item::Type(item) => {
                        let name = snake_case(&item.ident.to_string());
                        handle(item.attrs, |_ty| src.types.push(format!("type {name}")));
                    }
                    _ => (),
                }
            }

            if !src.functions.is_empty() || !src.types.is_empty() {
                self.source.push(src);
            }
        }

        Ok(())
    }

    fn generate_ml(&mut self) -> Result<(), std::io::Error> {
        let mut f = std::fs::File::create(&self.output).unwrap();

        writeln!(f, "(* Generated by ocaml-rs *)\n")?;
        writeln!(f, "open! Bigarray")?;

        for src in &self.source {
            writeln!(
                f,
                "\n(* file: {} *)\n",
                src.path.strip_prefix(&self.base_dir).unwrap().display()
            )?;

            for t in &src.types {
                writeln!(f, "{t}")?;
            }

            for func in &src.functions {
                writeln!(f, "{func}")?;
            }
        }

        Ok(())
    }

    fn generate_mli(&mut self) -> Result<(), std::io::Error> {
        let filename = self.output.with_extension("mli");
        let mut f = std::fs::File::create(&filename).unwrap();

        writeln!(f, "(* Generated by ocaml-rs *)\n")?;
        writeln!(f, "open! Bigarray")?;

        for src in &self.source {
            writeln!(
                f,
                "\n(* file: {} *)\n",
                src.path.strip_prefix(&self.base_dir).unwrap().display()
            )?;

            for t in &src.types {
                writeln!(f, "{t}")?;
            }

            for func in &src.functions {
                writeln!(f, "{func}")?;
            }
        }

        Ok(())
    }

    pub fn generate(mut self) -> Result<(), std::io::Error> {
        let dir = self.base_dir.clone();
        self.parse(&dir)?;

        self.source.sort_by(|a, b| a.path.cmp(&b.path));
        self.generate_ml()?;
        self.generate_mli()
    }
}