const std = @import("std"); const tokens = @import("tokens.zig"); const Token = tokens.Token; pub const NodeList = std.ArrayList(*Node); pub const ExprList = std.ArrayList(*Expr); pub const ParamList = std.ArrayList(ParamDecl); pub const ConstList = std.ArrayList(SingleConst); // TODO convert FnCall to something like PrefixOp / InfixOp / SuffixOp pub const NodeType = enum { Root, FnDecl, ConstDecl, Block, Expr, }; pub const ParamDecl = struct { name: Token, // TODO types typ: Token, }; pub const FnDecl = struct { func_name: Token, params: ParamList, body: NodeList, }; pub const SingleConst = struct { name: Token, // TODO expr value: Token, }; pub const BinaryExpr = struct { left: *Expr, op: Token, right: *Expr, }; pub const UnaryExpr = struct { op: Token, right: *Expr, }; pub const LiteralExpr = union(enum) { Bool: bool, Integer: []const u8, Float: []const u8, String: []const u8, }; pub const Expr = union(enum) { Binary: BinaryExpr, Unary: UnaryExpr, Literal: LiteralExpr, Grouping: *Expr, }; pub const Node = union(NodeType) { Root: NodeList, FnDecl: FnDecl, ConstDecl: ConstList, Block: ExprList, Expr: *Expr, }; pub fn mkRoot(allocator: *std.mem.Allocator) !*Node { var node = try allocator.create(Node); node.* = Node{ .Root = NodeList.init(allocator) }; return node; } fn print(ident: usize, comptime fmt: []const u8, args: ...) void { var i: usize = 0; while (i < ident) : (i += 1) { std.debug.warn("\t"); } std.debug.warn(fmt, args); } pub fn printNode(node: *Node, ident: usize) void { switch (node.*) { .FnDecl => |decl| { print(ident, "FnDecl name='{}'\n", decl.func_name.lexeme); for (decl.params.toSlice()) |param| { print( ident + 1, "param: '{}' {}\n", param.name.lexeme, param.typ.lexeme, ); } }, .ConstDecl => |consts| { print(ident, "ConstDecl ({} consts)\n", consts.len); for (consts.toSlice()) |const_decl| { print( ident + 1, "'{}' = '{}'\n", const_decl.name.lexeme, const_decl.value.lexeme, ); } }, .Root => { for (node.Root.toSlice()) |child| { printNode(child, ident + 1); } }, else => { print(ident, "unknown node: {}\n", node); }, } }