finish make_exprs.py script

- add src/expr.zig
This commit is contained in:
Luna 2019-05-31 23:43:46 -03:00
parent 8007df6853
commit 6ff75a0926
2 changed files with 44 additions and 6 deletions

View file

@ -4,7 +4,7 @@ from pathlib import Path
EXPR_TYPES = { EXPR_TYPES = {
'Binary': ('left: Expr', 'operator: Token', 'right: Expr'), 'Binary': ('left: Expr', 'operator: Token', 'right: Expr'),
'Grouping': ('expression: Expr'), 'Grouping': ('expression: Expr',),
'Unary': ('operator: Token', 'right: Expr'), 'Unary': ('operator: Token', 'right: Expr'),
# NOTE: when adding new Literals, add new Literal types, instead of just # NOTE: when adding new Literals, add new Literal types, instead of just
@ -18,7 +18,9 @@ def _gen_expr_decls():
res.append(f'pub const {expr_type} = struct {{') res.append(f'pub const {expr_type} = struct {{')
for param in expr_params: for param in expr_params:
res.append(f'{param},') res.append(f' {param},')
res.append('};\n')
return '\n'.join(res) return '\n'.join(res)
@ -28,19 +30,27 @@ def do_base_union(union_name: str):
'const Token = @import("token.zig").Token;\n' 'const Token = @import("token.zig").Token;\n'
] ]
res.extend(_gen_expr_decls()) res.append(_gen_expr_decls())
res.append(f'pub const {union_name} = union {{')
res.append(f'pub const {union_name}Type = enum {{')
for expr_type in EXPR_TYPES:
res.append(f' {expr_type},')
res.append('};\n')
res.append(f'pub const {union_name} = union({union_name}Type) {{')
for expr_type in EXPR_TYPES: for expr_type in EXPR_TYPES:
res.append(f'{expr_type}: {expr_type},') res.append(f' {expr_type}: {expr_type},')
res.append('}\n') res.append('};\n')
return '\n'.join(res) return '\n'.join(res)
def main(): def main():
expr_file = Path('./src') / 'expr.zig' expr_file = Path('./src') / 'expr.zig'
expr_file.touch()
expr_file.unlink() expr_file.unlink()
expr_file.write_text(do_base_union('Expr')) expr_file.write_text(do_base_union('Expr'))

28
src/expr.zig Normal file
View file

@ -0,0 +1,28 @@
const Token = @import("token.zig").Token;
pub const Binary = struct {
left: Expr,
operator: Token,
right: Expr,
};
pub const Grouping = struct {
expression: Expr,
};
pub const Unary = struct {
operator: Token,
right: Expr,
};
pub const ExprType = enum {
Binary,
Grouping,
Unary,
};
pub const Expr = union(ExprType) {
Binary: Binary,
Grouping: Grouping,
Unary: Unary,
};