molecule-codegen 0.9.2

Code generator for molecule.
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::collections::HashSet;
use std::{ffi, fs, io::Read as _, path::Path, str::FromStr};

use pest::{error::Error as PestError, iterators::Pairs, Parser as _};
use same_file::is_same_file;

use crate::{
    ast::raw as ast,
    ast::raw::CustomUnionItemDecl,
    ast::raw::SyntaxVersion,
    parser,
    utils::{self, PairsUtils as _},
};

impl utils::PairsUtils for Pairs<'_, parser::Rule> {
    fn next_string(&mut self) -> String {
        self.next().unwrap().as_str().to_owned()
    }

    fn next_usize(&mut self) -> usize {
        usize::from_str(self.next().unwrap().as_str()).unwrap()
    }

    fn next_item(&mut self) -> ast::ItemDecl {
        ast::ItemDecl {
            typ: self.next_string(),
        }
    }

    fn next_items(&mut self) -> Vec<ast::ItemDecl> {
        let mut ret = Vec::new();
        for item in self {
            if item.as_rule() != parser::Rule::item_decl {
                unreachable!()
            }
            let mut pair = item.into_inner();
            let node = ast::ItemDecl {
                typ: pair.next_string(),
            };
            pair.next_should_be_none();
            ret.push(node);
        }
        ret
    }

    fn next_custom_union_items(&mut self) -> Vec<CustomUnionItemDecl> {
        let mut previous_id: Option<usize> = None;
        let mut ret = Vec::new();

        let mut custom_ids = HashSet::new();
        for item in self {
            match item.as_rule() {
                parser::Rule::item_decl => {
                    let mut pair = item.into_inner();
                    let node = ast::CustomUnionItemDecl {
                        typ: pair.next_string(),
                        id: if let Some(pre_id) = previous_id {
                            pre_id + 1
                        } else {
                            0
                        },
                    };
                    pair.next_should_be_none();
                    ret.push(node);
                }
                parser::Rule::custom_union_item_decl => {
                    let mut pair = item.into_inner();
                    let node = ast::CustomUnionItemDecl {
                        typ: pair.next_string(),
                        id: pair.next_usize(),
                    };
                    pair.next_should_be_none();
                    ret.push(node);
                }
                _ => unreachable!(),
            }

            if !custom_ids.insert(ret.last().unwrap().id) {
                panic!(
                    "Custom Union Item ID {} is duplicated",
                    ret.last().unwrap().id
                );
            }
            previous_id = Some(ret.last().unwrap().id);
        }
        // union items should be sorted by custom ID
        ret.sort_by_key(|item| item.id);
        ret
    }

    fn next_fields(&mut self) -> Vec<ast::FieldDecl> {
        let mut ret = Vec::new();
        for field in self {
            if field.as_rule() != parser::Rule::field_decl {
                unreachable!()
            }
            let mut pair = field.into_inner();
            let node = ast::FieldDecl {
                name: pair.next_string(),
                typ: pair.next_string(),
            };
            pair.next_should_be_none();
            ret.push(node);
        }
        ret
    }

    fn next_import<P: AsRef<Path>>(
        &mut self,
        imported_base: &P,
        imported_depth: usize,
    ) -> ast::ImportStmt {
        let mut paths = Vec::new();
        let mut path_supers = 0;
        if let Some(inner) = self.next() {
            if inner.as_rule() != parser::Rule::path {
                unreachable!()
            }
            let mut pair = inner.into_inner();
            loop {
                if let Some(inner) = pair.peek() {
                    if inner.as_rule() == parser::Rule::path_super {
                        pair.next();
                        path_supers += 1;
                        continue;
                    }
                }
                break;
            }
            for inner in pair {
                paths.push(inner.as_str().to_owned())
            }
        }
        ast::ImportStmt {
            name: paths.pop().unwrap(),
            paths,
            path_supers,
            imported_base: imported_base.as_ref().to_path_buf(),
            imported_depth,
        }
    }

    fn next_should_be_none(mut self) {
        if self.next().is_some() {
            unreachable!()
        }
    }
}

impl utils::ParserUtils for parser::Parser {
    fn preprocess<P: AsRef<Path>>(path: &P) -> Result<ast::Ast, Box<PestError<parser::Rule>>> {
        let namespace = path
            .as_ref()
            .file_stem()
            .and_then(ffi::OsStr::to_str)
            .unwrap()
            .to_owned();

        let mut ast = ast::Ast {
            namespace,
            ..Default::default()
        };

        let mut imported_depth = 0;

        Self::preprocess_single(&mut ast, path, imported_depth)?;

        let mut path_bufs = Vec::new();

        let mut imports = Vec::new();

        while !ast.imports.is_empty() {
            imported_depth += 1;
            while !ast.imports.is_empty() {
                let stmt = ast.imports.remove(0);
                let mut path_buf = stmt.imported_base().clone();
                path_buf.pop();
                for _ in 0..stmt.path_supers() {
                    path_buf.push("..");
                }
                for p in stmt.paths() {
                    path_buf.push(p);
                }
                path_buf.push(stmt.name());
                path_buf.set_extension("mol");
                let path_new = path_buf.as_path();
                if is_same_file(path, path_new).unwrap() {
                    panic!("found cyclic dependencies");
                }

                if path_bufs
                    .iter()
                    .any(|ref path_old| is_same_file(path_old, path_new).unwrap())
                {
                    continue;
                } else {
                    imports.push(stmt);
                    Self::preprocess_single(&mut ast, &path_new, imported_depth)?;
                    path_bufs.push(path_buf);
                }
            }
        }

        ast.imports = imports;

        Ok(ast)
    }
}

impl parser::Parser {
    fn preprocess_single<P: AsRef<Path>>(
        ast: &mut ast::Ast,
        path: &P,
        imported_depth: usize,
    ) -> Result<(), Box<PestError<parser::Rule>>> {
        let buffer = {
            let mut buffer = String::new();
            let mut file_in = fs::OpenOptions::new().read(true).open(path).unwrap();
            file_in.read_to_string(&mut buffer).unwrap();
            buffer
        };
        let mut file_content = parser::InnerParser::parse(parser::Rule::grammar, &buffer)?;
        let grammar = file_content
            .next()
            .unwrap_or_else(|| panic!("grammar should only have one pair"));
        if file_content.peek().is_some() {
            panic!("grammar should only have only one pair");
        }
        let mut eoi = false;
        for pair in grammar.into_inner() {
            if eoi {
                panic!("grammar should have only one EOI");
            }
            match pair.as_rule() {
                parser::Rule::syntax_version_stmt => {
                    let mut pair = pair.into_inner();
                    let syntax_version = SyntaxVersion {
                        version: pair.next_usize(),
                    };
                    pair.next_should_be_none();
                    if ast.syntax_version.is_some() {
                        // compare ast.syntax_version and syntax_version
                        // panic if there is a conflict syntax_version
                        if ast.syntax_version != Some(syntax_version) {
                            panic!("all schema files' syntax version should be same");
                        }
                    } else {
                        ast.syntax_version = Some(syntax_version);
                    }
                }
                parser::Rule::import_stmt => {
                    let mut pair = pair.into_inner();
                    let node = pair.next_import(path, imported_depth);
                    pair.next_should_be_none();
                    ast.add_import(node);
                }
                parser::Rule::option_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::OptionDecl {
                        name: pair.next_string(),
                        item: pair.next_item(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::union_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::UnionDecl {
                        name: pair.next_string(),
                        items: pair.next_custom_union_items(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::array_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::ArrayDecl {
                        name: pair.next_string(),
                        item: pair.next_item(),
                        item_count: pair.next_usize(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::struct_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::StructDecl {
                        name: pair.next_string(),
                        fields: pair.next_fields(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::vector_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::VectorDecl {
                        name: pair.next_string(),
                        item: pair.next_item(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::table_decl => {
                    let mut pair = pair.into_inner();
                    let node = ast::TableDecl {
                        name: pair.next_string(),
                        fields: pair.next_fields(),
                        imported_depth,
                    };
                    pair.next_should_be_none();
                    ast.add_decl(node);
                }
                parser::Rule::EOI => {
                    if eoi {
                        panic!("grammar could not have more than one EOI");
                    }
                    eoi = true;
                }
                _ => {
                    unreachable!();
                }
            }
        }
        if !eoi {
            panic!("grammar should have only one EOI");
        }

        if ast.syntax_version.is_none() {
            ast.syntax_version = Some(SyntaxVersion::default());
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{parser, utils, SyntaxVersion};
    use std::io::Write;

    #[test]
    fn test_default_syntax_version_should_be_1_0() {
        use utils::ParserUtils;
        // get path of  file
        let mut schema_file = tempfile::NamedTempFile::new().unwrap();
        let _ = schema_file.write(b"array uint32 [byte; 4];").unwrap();
        schema_file.flush().unwrap();

        let file = schema_file.into_temp_path();

        let ast = parser::Parser::preprocess(&file).unwrap();
        assert_eq!(ast.syntax_version, Some(SyntaxVersion { version: 1 }));
    }

    #[test]
    fn test_parse_syntax_version() {
        use utils::ParserUtils;
        // get path of  file
        let mut schema_file = tempfile::NamedTempFile::new().unwrap();
        let test_version = SyntaxVersion { version: 7 };
        schema_file
            .write_fmt(format_args!("syntax = {};", test_version.version))
            .unwrap();
        let _ = schema_file.write(b"array uint32 [byte; 4];").unwrap();
        schema_file.flush().unwrap();

        let file = schema_file.into_temp_path();

        let ast = parser::Parser::preprocess(&file).unwrap();
        assert_eq!(ast.syntax_version, Some(test_version));
    }

    #[test]
    #[should_panic]
    // if A `syntax = 1` schema file imports a `syntax = 2` schema file, it should panic
    fn test_different_syntax_version_should_panic() {
        use utils::ParserUtils;

        let mut child_schema_file = tempfile::NamedTempFile::new().unwrap();
        child_schema_file
            .write_fmt(format_args!("syntax = 2;"))
            .unwrap();
        let _ = child_schema_file.write(b"array uint64 [byte; 8];").unwrap();
        child_schema_file.flush().unwrap();

        let child_file = child_schema_file.into_temp_path();
        let child_file_path = child_file.to_str().unwrap();

        let mut root_schema_file = tempfile::NamedTempFile::new().unwrap();
        root_schema_file
            .write_fmt(format_args!("syntax = 1;",))
            .unwrap();
        root_schema_file
            .write_fmt(format_args!("import {:?}", child_file_path))
            .unwrap();
        let _ = root_schema_file.write(b"array uint32 [byte; 4];").unwrap();
        root_schema_file.flush().unwrap();

        let file = root_schema_file.into_temp_path();

        parser::Parser::preprocess(&file).unwrap();
    }
}