From 0079d26b9d5a95b46c3a73f0aa5409a584d0bb1b Mon Sep 17 00:00:00 2001 From: Nic Gaffney Date: Wed, 17 Jul 2024 18:27:58 -0500 Subject: Added AST --- src/ast.zig | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/ast.zig (limited to 'src/ast.zig') diff --git a/src/ast.zig b/src/ast.zig new file mode 100644 index 0000000..2f8f209 --- /dev/null +++ b/src/ast.zig @@ -0,0 +1,67 @@ +const std = @import("std"); +const tok = @import("tokenize.zig"); + +const SyntaxError = error{SyntaxError}; +const expectedToken = error{ExpectedToken}; + +pub const BinOp = enum { + Add, + Sub, + Mul, + Div, +}; + +pub const Literal = union(enum) { + Int: i32, +}; + +pub const Ast = union(enum) { + Expr: struct { + kind: ExprKind, + }, + Stmt: struct { + kind: StmtKind, + }, +}; + +const StmtKind = union(enum) { + exit: Ast.Expr, +}; + +const ExprKind = union(enum) { + Literal: Literal, + BinaryOp: struct { + op: BinOp, + left: Ast.Expr, + right: Ast.Expr, + }, +}; + +fn checkType(token: tok.Token, typ: tok.TokenType) bool { + return switch (token) { + typ => true, + else => false, + }; +} + +const AstParser = struct { + tokens: tok.Iterator(tok.Token), + fn parseStmt(self: *AstParser) !Ast.Stmt { + return switch (self.tokens.peek().?) { + .ret => try self.exitStmt(), + }; + } + + fn parseExpr(self: *AstParser) !Ast.Expr { + + } + + fn exitStmt(self: *AstParser) !Ast.Stmt { + if (!checkType(self.tokens.consume().?, tok.TokenType.ret)) return expectedToken; + const value = self.parseExpr(); + + if (!checkType(self.tokens.consume().?, tok.TokenType.semiCol)) return expectedToken; + const kind = StmtKind{ .exit = value }; + return Ast.Stmt{ .kind = kind }; + } +}; -- cgit v1.2.3