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
|
const std = @import("std");
const tokenizer = @import("tokenizer.zig");
const ParserError = error{
ParsingError,
OutOfMemory,
};
const NodeType = enum {
PROGRAM,
STATEMENT,
VARIABLE_STATEMENT,
PRINT_STATEMENT,
EXPRESSION,
};
pub const Node = union(NodeType) { PROGRAM: struct {
statements: []*Node,
}, STATEMENT: struct {
statement: *Node,
}, VARIABLE_STATEMENT: struct {
is_declaration: bool,
name: []const u8,
expression: *Node,
}, PRINT_STATEMENT: struct {
expression: *Node,
}, EXPRESSION: union(enum) {
NUMBER: struct {
value: i64,
},
IDENTIFIER: struct {
name: []const u8,
},
} };
pub const Parser = struct {
tokens: []tokenizer.Token,
offset: u32,
allocator: std.mem.Allocator,
pub fn init(tokens: []tokenizer.Token, allocator: std.mem.Allocator) ParserError!*Parser {
const parser = try allocator.create(Parser);
parser.* = .{
.tokens = tokens,
.offset = 0,
.allocator = allocator,
};
return parser;
}
pub fn parse(self: *Parser) !*Node {
return self.parse_program();
}
// Program ::= Statement+
fn parse_program(self: *Parser) !*Node {
var nodes = std.ArrayList(*Node).init(self.allocator);
defer nodes.deinit();
while (self.offset < self.tokens.len) {
try nodes.append(@constCast(try self.parse_statement()));
}
return self.create_node(.{ .PROGRAM = .{
.statements = try nodes.toOwnedSlice(),
} });
}
// Statement ::= (VariableStatement | PrintStatement) SEMICOLON
fn parse_statement(self: *Parser) ParserError!*Node {
errdefer std.debug.print("Error parsing statement\n", .{});
const token = self.peek_token() orelse return ParserError.ParsingError;
const statement = switch (token) {
.PRINT => try self.parse_print_statement(),
else => try self.parse_variable_statement(),
};
_ = try self.accept_token(tokenizer.TokenType.SEMICOLON);
return self.create_node(.{
.STATEMENT = .{
.statement = statement,
},
});
}
// VariableStatement ::= ("let" IDENTIFIER | IDENTIFIER) EQUALS Expression
fn parse_variable_statement(self: *Parser) ParserError!*Node {
errdefer std.debug.print("Error parsing variable statement\n", .{});
const token = self.peek_token() orelse return ParserError.ParsingError;
var is_declaration: bool = false;
if (token == .LET) {
is_declaration = true;
_ = self.consume_token() orelse return ParserError.ParsingError;
}
const identifier = try self.accept_token(tokenizer.TokenType.IDENTIFIER);
_ = try self.accept_token(tokenizer.TokenType.EQUALS);
const expression = try self.parse_expression();
return self.create_node(.{
.VARIABLE_STATEMENT = .{
.is_declaration = is_declaration,
.name = try self.allocator.dupe(u8, identifier.IDENTIFIER),
.expression = @constCast(expression),
},
});
}
// PrintStatement :== PRINT LPAREN Expression RPAREN
fn parse_print_statement(self: *Parser) ParserError!*Node {
errdefer std.debug.print("Error parsing print statement\n", .{});
_ = try self.accept_token(tokenizer.TokenType.PRINT);
_ = try self.accept_token(tokenizer.TokenType.LPAREN);
const expression = try self.parse_expression();
_ = try self.accept_token(tokenizer.TokenType.RPAREN);
return self.create_node(.{
.PRINT_STATEMENT = .{
.expression = @constCast(expression),
},
});
}
// Expression :== NUMBER | IDENTIFIER
fn parse_expression(self: *Parser) ParserError!*Node {
errdefer std.debug.print("Error parsing expression\n", .{});
const token = self.consume_token() orelse return ParserError.ParsingError;
return switch (token) {
.NUMBER => |number_token| self.create_node(.{
.EXPRESSION = .{
.NUMBER = .{
.value = number_token,
},
},
}),
.IDENTIFIER => |identifier_token| self.create_node(.{
.EXPRESSION = .{
.IDENTIFIER = .{
.name = try self.allocator.dupe(u8, identifier_token),
},
},
}),
else => return ParserError.ParsingError,
};
}
fn accept_token(self: *Parser, expected_token: tokenizer.TokenType) ParserError!tokenizer.Token {
errdefer std.debug.print("Error accepting token: {any}\n", .{expected_token});
const token = self.peek_token() orelse return ParserError.ParsingError;
if (token != expected_token) return ParserError.ParsingError;
return self.consume_token() orelse unreachable;
}
fn consume_token(self: *Parser) ?tokenizer.Token {
if (self.offset >= self.tokens.len) return null;
defer self.offset += 1;
return self.tokens[self.offset];
}
fn peek_token(self: *Parser) ?tokenizer.Token {
if (self.offset >= self.tokens.len) return null;
return self.tokens[self.offset];
}
fn create_node(self: *Parser, node_value: Node) !*Node {
const node = try self.allocator.create(Node);
node.* = node_value;
return node;
}
};
test "parse print" {
const tokens: []tokenizer.Token = @constCast(&[_]tokenizer.Token{
tokenizer.Token{ .PRINT = void{} },
tokenizer.Token{ .LPAREN = void{} },
tokenizer.Token{ .NUMBER = 7 },
tokenizer.Token{ .RPAREN = void{} },
tokenizer.Token{ .SEMICOLON = void{} },
});
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var parser = try Parser.init(tokens, arena.allocator());
const actualNode = try parser.parse_print_statement();
const expectedNode = Node{ .PRINT_STATEMENT = .{
.expression = @constCast(&Node{ .EXPRESSION = .{
.NUMBER = .{ .value = 7 },
} }),
} };
try std.testing.expectEqualDeep(&expectedNode, actualNode);
}
test "parse identifier" {
const tokens: []tokenizer.Token = @constCast(&[_]tokenizer.Token{
tokenizer.Token{ .IDENTIFIER = @constCast("i") },
});
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var parser = try Parser.init(tokens, arena.allocator());
const actualNode = try parser.parse_expression();
const expectedNode = Node{ .EXPRESSION = .{
.IDENTIFIER = .{
.name = @constCast("i"),
},
} };
try std.testing.expectEqualDeep(&expectedNode, actualNode);
}
test "parse number" {
const tokens: []tokenizer.Token = @constCast(&[_]tokenizer.Token{
tokenizer.Token{ .NUMBER = 12 },
});
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var parser = try Parser.init(tokens, arena.allocator());
const actualNode = try parser.parse_expression();
const expectedNode = Node{ .EXPRESSION = .{
.NUMBER = .{
.value = 12,
},
} };
try std.testing.expectEqualDeep(&expectedNode, actualNode);
}
test "simple e2e" {
const tokens: []tokenizer.Token = @constCast(&[_]tokenizer.Token{
tokenizer.Token{ .LET = void{} },
tokenizer.Token{ .IDENTIFIER = @constCast("i") },
tokenizer.Token{ .EQUALS = void{} },
tokenizer.Token{ .NUMBER = 2 },
tokenizer.Token{ .SEMICOLON = void{} },
});
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var parser = try Parser.init(tokens, arena.allocator());
const ast = try parser.parse();
const expected_ast = Node{ .PROGRAM = .{ .statements = @constCast(&[_]*Node{@constCast(&Node{ .STATEMENT = .{ .statement = @constCast(&Node{ .VARIABLE_STATEMENT = .{
.is_declaration = true,
.name = @constCast("i"),
.expression = @constCast(&Node{ .EXPRESSION = .{
.NUMBER = .{ .value = 2 },
} }),
} }) } })}) } };
try std.testing.expectEqualDeep(&expected_ast, ast);
}
|