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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const root = @import("root");
const Lexer = root.Lexer;
const Token = Lexer.Token;
const Location = Lexer.Location;
fn Fmt(T: type) type {
return std.fmt.Formatter(struct {
fn format(
data: struct { T, []const u8, usize },
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
const self, const file_source, const indent = data;
return self.format(writer, file_source, indent);
}
}.format);
}
pub fn fmt(tree: anytype, source: []const u8, indent: usize) Fmt(@TypeOf(tree)) {
return .{ .data = .{ tree, source, indent } };
}
pub const File = struct {
decls: []Decl,
const Decl = struct {
loc: Location,
inner: Stmt.Type.AssignVar,
};
fn format(self: File, writer: anytype, source: []const u8, indent: usize) !void {
for (0.., self.decls) |i, decl| {
try writer.print("{s}{s} {s} {}\n", .{
if (i == 0) "" else "\n",
decl.inner.ident.getIdent(source),
":=",
fmt(decl.inner.value, source, indent),
});
}
}
};
pub const Block = struct {
loc: Location,
stmts: []Stmt,
fn format(self: Block, writer: anytype, source: []const u8, indent: usize) !void {
try writer.writeAll("{\n");
for (self.stmts) |stmt| {
try writer.print("{}\n", .{fmt(stmt, source, indent + 4)});
}
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("}");
}
};
pub const Stmt = struct {
loc: Location,
type: Type,
pub const Type = union(enum) {
expr: *const Expr,
assign_var: AssignVar,
block: Block,
@"while": While,
pub const AssignVar = struct {
ident: Location,
is_decl: bool,
value: *const Expr,
};
pub const While = struct {
cond: *const Expr,
do: Block,
};
};
fn format(self: Stmt, writer: anytype, source: []const u8, indent: usize) !void {
try writer.writeByteNTimes(' ', indent);
return switch (self.type) {
.expr => |expr| writer.print("{}", .{fmt(expr, source, indent)}),
.block => |b| writer.print("{}", .{fmt(b, source, indent)}),
.assign_var => |assign_var| writer.print("{s} {s} {}", .{
assign_var.ident.getIdent(source),
if (assign_var.is_decl) ":=" else "=",
fmt(assign_var.value, source, indent),
}),
.@"while" => |@"while"| try writer.print("while {} {}", .{
fmt(@"while".cond, source, indent),
fmt(@"while".do, source, indent),
}),
};
}
};
pub const Expr = struct {
loc: Location,
type: Type,
pub const Type = union(enum) {
integer_literal,
bin_op: BinOp,
call: Call,
identifier,
@"if": If,
proc: Proc,
pub const BinOp = struct {
lhs: *const Expr,
rhs: *const Expr,
op: Op,
const Op = enum {
plus,
minus,
left_angle,
right_angle,
left_angle_equal,
right_angle_equal,
pub fn format(self: Op, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try writer.writeAll(switch (self) {
.plus => "+",
.minus => "-",
.left_angle => "<",
.right_angle => ">",
.left_angle_equal => "<=",
.right_angle_equal => ">=",
});
}
};
};
pub const Call = struct {
proc: *const Expr,
arg: *const Expr,
};
pub const If = struct {
cond: *const Expr,
then: Block,
@"else": ?Block,
};
pub const Proc = struct {
body: Block,
param: ?Location,
};
};
fn format(self: Expr, writer: anytype, source: []const u8, indent: usize) !void {
switch (self.type) {
.integer_literal => try writer.print("{}", .{self.loc.getInt(source)}),
.bin_op => |bin_op| {
try writer.print("{} {} {}", .{ fmt(bin_op.lhs, source, indent), bin_op.op, fmt(bin_op.rhs, source, indent) });
},
.call => |call| {
try writer.print("{}({})", .{ fmt(call.proc, source, indent), fmt(call.arg, source, indent) });
},
.identifier => try writer.print("{s}", .{self.loc.getIdent(source)}),
.@"if" => |@"if"| {
try writer.print("if {} {}", .{
fmt(@"if".cond, source, indent),
fmt(@"if".then, source, indent),
});
if (@"if".@"else") |@"else"| {
try writer.print(" else {}", .{fmt(@"else", source, indent)});
}
},
.proc => |proc| {
try writer.print("proc() {}", .{fmt(proc.body, source, indent)});
},
}
}
};
const ParseError = error{
OutOfMemory,
ExpectedRightParen,
UnexpectedToken,
InvalidAssignTarget,
ExprStatementMustBeCall,
};
pub fn file(allocator: Allocator, lexer: *Lexer) !File {
var decls: std.ArrayList(File.Decl) = .init(allocator);
while (lexer.peek().type != .eof) {
const stmt = try parseStatement(allocator, lexer);
if (stmt.type != .assign_var or !stmt.type.assign_var.is_decl) {
return error.ExpectedProcedureDeclaration;
}
try decls.append(.{
.loc = stmt.loc,
.inner = stmt.type.assign_var,
});
}
return .{
.decls = try decls.toOwnedSlice(),
};
}
fn parseBlock(allocator: Allocator, lexer: *Lexer) !Block {
const left_curly = try mustEat(lexer, .left_curly);
var stmts: std.ArrayList(Stmt) = .init(allocator);
while (lexer.peek().type != .right_curly) {
try stmts.append(try parseStatement(allocator, lexer));
}
const right_curly = try mustEat(lexer, .right_curly);
return .{
.loc = left_curly.loc.combine(right_curly.loc),
.stmts = try stmts.toOwnedSlice(),
};
}
fn parseStatement(allocator: Allocator, lexer: *Lexer) ParseError!Stmt {
switch (lexer.peek().type) {
.left_curly => {
const b = try parseBlock(allocator, lexer);
return .{
.loc = b.loc,
.type = .{ .block = b },
};
},
.@"while" => {
const @"while" = lexer.next();
const cond = try expression(allocator, lexer);
const do = try parseBlock(allocator, lexer);
return .{
.loc = @"while".loc.combine(do.loc),
.type = .{ .@"while" = .{
.cond = cond,
.do = do,
} },
};
},
else => {
const lhs = try expression(allocator, lexer);
const colon = if (lexer.peek().type == .colon)
try mustEat(lexer, .colon)
else
null;
if (colon != null or lexer.peek().type == .equal) {
_ = try mustEat(lexer, .equal);
const value = try expression(allocator, lexer);
if (lhs.type != .identifier) {
std.debug.print("Invalid assign target. Found '{s}', expected an identifier.", .{@tagName(lhs.type)});
return error.InvalidAssignTarget;
}
return .{
.loc = lhs.loc.combine(value.loc),
.type = .{ .assign_var = .{ .ident = lhs.loc, .is_decl = colon != null, .value = value } },
};
} else if (lhs.type != .call) {
return error.ExprStatementMustBeCall;
}
return .{
.loc = lhs.loc,
.type = .{ .expr = lhs },
};
},
}
}
fn expression(allocator: Allocator, lexer: *Lexer) ParseError!*Expr {
return parseProc(allocator, lexer);
}
fn parseProc(allocator: Allocator, lexer: *Lexer) ParseError!*Expr {
if (lexer.peek().type != .proc) return parseComparisons(allocator, lexer);
const proc = try mustEat(lexer, .proc);
_ = try mustEat(lexer, .left_paren);
const param_tok = lexer.next();
const param: ?Location = switch (param_tok.type) {
.identifier => param_tok.loc,
.right_paren => null,
else => |ty| return expected(&.{ .identifier, .right_paren }, ty),
};
if (param != null) _ = try mustEat(lexer, .right_paren);
const body = try parseBlock(allocator, lexer);
return allocate(Expr, allocator, .{
.loc = proc.loc.combine(body.loc),
.type = .{ .proc = .{ .body = body, .param = param } },
});
}
fn parseComparisons(allocator: Allocator, lexer: *Lexer) ParseError!*Expr {
const lhs = try parseTerms(allocator, lexer);
const op: Expr.Type.BinOp.Op = switch (lexer.peek().type) {
.left_angle => .left_angle,
.right_angle => .right_angle,
.left_angle_equal => .left_angle_equal,
.right_angle_equal => .right_angle_equal,
else => return lhs,
};
_ = lexer.next();
const rhs = try parseTerms(allocator, lexer);
return try allocate(Expr, allocator, .{
.loc = lhs.loc.combine(rhs.loc),
.type = .{ .bin_op = .{ .lhs = lhs, .op = op, .rhs = rhs } },
});
}
fn parseTerms(allocator: Allocator, lexer: *Lexer) !*Expr {
var lhs = try parseIf(allocator, lexer);
while (true) {
const op: Expr.Type.BinOp.Op = switch (lexer.peek().type) {
.plus => .plus,
.minus => .minus,
else => break,
};
_ = lexer.next();
const rhs = try parseIf(allocator, lexer);
lhs = try allocate(Expr, allocator, .{
.loc = lhs.loc.combine(rhs.loc),
.type = .{ .bin_op = .{ .lhs = lhs, .op = op, .rhs = rhs } },
});
}
return lhs;
}
fn parseIf(allocator: Allocator, lexer: *Lexer) !*Expr {
switch (lexer.peek().type) {
.@"if" => {
const @"if" = lexer.next();
const cond = try expression(allocator, lexer);
const then = try parseBlock(allocator, lexer);
const @"else" = if (lexer.peek().type == .@"else") blk: {
_ = lexer.next();
break :blk try parseBlock(allocator, lexer);
} else null;
return try allocate(Expr, allocator, .{
.loc = @"if".loc.combine((@"else" orelse then).loc),
.type = .{ .@"if" = .{
.cond = cond,
.then = then,
.@"else" = @"else",
} },
});
},
else => return try parseInvocations(allocator, lexer),
}
}
fn parseInvocations(allocator: Allocator, lexer: *Lexer) !*Expr {
var proc = try parsePrimaryExpr(allocator, lexer);
while (true) {
if (lexer.peek().type != .left_paren) break;
_ = lexer.next();
const arg = try expression(allocator, lexer);
_ = try mustEat(lexer, .right_paren);
proc = try allocate(Expr, allocator, .{
.loc = proc.loc.combine(arg.loc),
.type = .{ .call = .{ .proc = proc, .arg = arg } },
});
}
return proc;
}
fn parsePrimaryExpr(allocator: Allocator, lexer: *Lexer) !*Expr {
const token = lexer.next();
return allocate(Expr, allocator, switch (token.type) {
.left_paren => {
const res = expression(allocator, lexer);
const right_paren = lexer.next();
if (right_paren.type != .right_paren)
return error.ExpectedRightParen;
return res;
},
.integer_literal => .{ .loc = token.loc, .type = .integer_literal },
.identifier => .{ .loc = token.loc, .type = .identifier },
else => |t| {
std.debug.print("Expected '(', integer literal, or identifier. Got '{s}'\n", .{@tagName(t)});
return error.UnexpectedToken;
},
});
}
fn expected(one_of: []const Token.Type, got: Token.Type) error{UnexpectedToken} {
for (one_of) |ty|
std.debug.assert(ty != got);
std.debug.print("Expected ", .{});
for (0.., one_of) |i, ty| {
std.debug.print("{s}{s}", .{ if (i == 0) "" else " or ", @tagName(ty) });
}
std.debug.print(". Got {s}.\n", .{@tagName(got)});
return error.UnexpectedToken;
}
fn mustEat(lexer: *Lexer, ty: Token.Type) !Token {
const token = lexer.next();
if (token.type != ty) {
std.debug.print("Expected {s}. Got {s} at {}.\n", .{ @tagName(ty), @tagName(token.type), token.loc });
return error.UnexpectedToken;
}
return token;
}
fn allocate(T: type, allocator: Allocator, t: T) !*T {
const res = try allocator.create(T);
res.* = t;
return res;
}
|