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
|
pub const Expr = union(enum) {
IntegerLiteral: Token,
BinOp: struct { lhs: *const Expr, op: Token, rhs: *const Expr },
Invalid: Token,
};
pub fn expression(allocator: Allocator, lexer: *Peekable(Lexer)) error{OutOfMemory}!*Expr {
return addExpr(allocator, lexer);
}
pub fn addExpr(allocator: Allocator, lexer: *Peekable(Lexer)) !*Expr {
const lhs = try primaryExpr(allocator, lexer);
const token: ?Lexer.Token = lexer.peek();
const op = (if (token) |t| if (t.type == .Plus) t else null else null) orelse return lhs;
_ = lexer.next();
const rhs = try primaryExpr(allocator, lexer);
return allocate(allocator, .{ .BinOp = .{ .lhs = lhs, .op = op, .rhs = rhs } });
}
pub fn primaryExpr(allocator: Allocator, lexer: *Peekable(Lexer)) !*Expr {
const token = lexer.next().?;
// std.debug.print("term {}\n", .{token});
return allocate(allocator, switch (token.type) {
.LeftParen => {
const res = expression(allocator, lexer);
const right_paren = lexer.next().?;
if (right_paren.type != .RightParen)
return allocate(allocator, .{ .Invalid = right_paren });
return res;
},
.IntegerLiteral => .{ .IntegerLiteral = token },
else => .{ .Invalid = token },
});
}
fn allocate(allocator: Allocator, expr: Expr) !*Expr {
const res = try allocator.create(Expr);
res.* = expr;
return res;
}
const std = @import("std");
const Allocator = std.mem.Allocator;
const Lexer = @import("./lexer.zig");
const Token = Lexer.Token;
const root = @import("root");
const Peekable = root.Peekable;
const peekable = root.peekable;
|