-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathparser.zig
More file actions
1770 lines (1414 loc) · 65.6 KB
/
parser.zig
File metadata and controls
1770 lines (1414 loc) · 65.6 KB
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const lexer = @import("tokenizer.zig");
const ast = @import("ast.zig");
const diag = @import("diagnostics.zig");
const Location = @import("location.zig").Location;
const EscapedStringIterator = @import("string-escaping.zig").EscapedStringIterator;
/// Parses a sequence of tokens into an abstract syntax tree.
/// Returns either a successfully parsed tree or puts all found
/// syntax errors into `diagnostics`.
pub fn parse(
allocator: std.mem.Allocator,
diagnostics: *diag.Diagnostics,
sequence: []const lexer.Token,
) !ast.Program {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
const alloc = arena.allocator();
var root_script = std.ArrayList(ast.Statement).empty;
defer root_script.deinit(alloc);
var functions = std.ArrayList(ast.Function).empty;
defer functions.deinit(alloc);
const Parser = struct {
const Self = @This();
const Predicate = *const (fn (lexer.Token) bool);
const AcceptError = error{SyntaxError};
const ParseError = std.mem.Allocator.Error || AcceptError;
const SavedState = struct {
index: usize,
};
allocator: std.mem.Allocator,
sequence: []const lexer.Token,
index: usize = 0,
diagnostics: *diag.Diagnostics,
fn emitDiagnostics(self: *Self, comptime fmt: []const u8, args: anytype) error{ OutOfMemory, SyntaxError } {
try self.diagnostics.emit(.@"error", self.getCurrentLocation(), fmt, args);
return error.SyntaxError;
}
fn getCurrentLocation(self: Self) Location {
return self.sequence[self.index].location;
}
/// Applies all known string escape codes
fn escapeString(self: Self, input: []const u8) ![]u8 {
var iterator = EscapedStringIterator.init(input);
var len: usize = 0;
while (try iterator.next()) |_| {
len += 1;
}
iterator = EscapedStringIterator.init(input);
const result = try self.allocator.alloc(u8, len);
var i: usize = 0;
while (iterator.next() catch unreachable) |c| {
result[i] = c;
i += 1;
}
std.debug.assert(i == len);
return result;
}
/// Create a save state that allows rewinding the parser process.
/// This should be used when a parsing function calls accept mulitple
/// times and may emit a syntax error.
/// The state should be restored in a errdefer.
fn saveState(self: Self) SavedState {
return SavedState{
.index = self.index,
};
}
/// Restores a previously created save state.
fn restoreState(self: *Self, state: SavedState) void {
self.index = state.index;
}
fn moveToHeap(self: *Self, value: anytype) !*@TypeOf(value) {
const T = @TypeOf(value);
std.debug.assert(@typeInfo(T) != .pointer);
const ptr = try self.allocator.create(T);
ptr.* = value;
std.debug.assert(std.meta.eql(ptr.*, value));
return ptr;
}
fn any(token: lexer.Token) bool {
_ = token;
return true;
}
fn is(comptime kind: lexer.TokenType) Predicate {
return struct {
fn pred(token: lexer.Token) bool {
return token.type == kind;
}
}.pred;
}
fn oneOf(comptime kinds: anytype) Predicate {
return struct {
fn pred(token: lexer.Token) bool {
return inline for (kinds) |k| {
if (token.type == k)
break true;
} else false;
}
}.pred;
}
fn peek(self: Self) AcceptError!lexer.Token {
if (self.index >= self.sequence.len)
return error.SyntaxError;
return self.sequence[self.index];
}
fn accept(self: *Self, predicate: Predicate) AcceptError!lexer.Token {
if (self.index >= self.sequence.len)
return error.SyntaxError;
const tok = self.sequence[self.index];
if (predicate(tok)) {
self.index += 1;
return tok;
} else {
// std.debug.print("cannot accept {} here!\n", .{tok});
return error.SyntaxError;
}
}
fn acceptFunction(self: *Self) ParseError!ast.Function {
const state = self.saveState();
errdefer self.restoreState(state);
const initial_pos = try self.accept(is(.function));
const name = try self.accept(is(.identifier));
_ = try self.accept(is(.@"("));
var args = std.ArrayList([]const u8).empty;
while (true) {
const arg_or_end = try self.accept(oneOf(.{ .identifier, .@")" }));
switch (arg_or_end.type) {
.@")" => break,
.identifier => {
try args.append(self.allocator, arg_or_end.text);
const delimit = try self.accept(oneOf(.{ .@",", .@")" }));
if (delimit.type == .@")")
break;
},
else => unreachable,
}
}
const block = try self.acceptBlock();
return ast.Function{
.location = initial_pos.location,
.name = name.text,
.parameters = try args.toOwnedSlice(self.allocator),
.body = block,
};
}
fn acceptBlock(self: *Self) ParseError!ast.Statement {
const state = self.saveState();
errdefer self.restoreState(state);
const begin = try self.accept(is(.@"{"));
var body = std.ArrayList(ast.Statement).empty;
while (true) {
const stmt = self.acceptStatement() catch break;
try body.append(self.allocator, stmt);
}
_ = try self.accept(is(.@"}"));
return ast.Statement{
.location = begin.location,
.type = .{
.block = try body.toOwnedSlice(self.allocator),
},
};
}
fn acceptStatement(self: *Self) ParseError!ast.Statement {
const state = self.saveState();
errdefer self.restoreState(state);
const start = try self.peek();
switch (start.type) {
.@";" => {
_ = try self.accept(is(.@";"));
return ast.Statement{
.location = start.location,
.type = .empty,
};
},
.@"break" => {
_ = try self.accept(is(.@"break"));
_ = try self.accept(is(.@";"));
return ast.Statement{
.location = start.location,
.type = .@"break",
};
},
.@"continue" => {
_ = try self.accept(is(.@"continue"));
_ = try self.accept(is(.@";"));
return ast.Statement{
.location = start.location,
.type = .@"continue",
};
},
.@"{" => {
return try self.acceptBlock();
},
.@"while" => {
_ = try self.accept(is(.@"while"));
_ = try self.accept(is(.@"("));
const condition = try self.acceptExpression();
_ = try self.accept(is(.@")"));
const body = try self.acceptBlock();
return ast.Statement{
.location = start.location,
.type = .{
.while_loop = .{
.condition = condition,
.body = try self.moveToHeap(body),
},
},
};
},
.@"if" => {
_ = try self.accept(is(.@"if"));
_ = try self.accept(is(.@"("));
const condition = try self.acceptExpression();
_ = try self.accept(is(.@")"));
const true_body = try self.acceptStatement();
if (self.accept(is(.@"else"))) |_| {
const false_body = try self.acceptStatement();
return ast.Statement{
.location = start.location,
.type = .{
.if_statement = .{
.condition = condition,
.true_body = try self.moveToHeap(true_body),
.false_body = try self.moveToHeap(false_body),
},
},
};
} else |_| {
return ast.Statement{
.location = start.location,
.type = .{
.if_statement = .{
.condition = condition,
.true_body = try self.moveToHeap(true_body),
.false_body = null,
},
},
};
}
},
.@"for" => {
_ = try self.accept(is(.@"for"));
_ = try self.accept(is(.@"("));
const name = try self.accept(is(.identifier));
_ = try self.accept(is(.in));
const source = try self.acceptExpression();
_ = try self.accept(is(.@")"));
const body = try self.acceptBlock();
return ast.Statement{
.location = start.location,
.type = .{
.for_loop = .{
.variable = name.text,
.source = source,
.body = try self.moveToHeap(body),
},
},
};
},
.@"return" => {
_ = try self.accept(is(.@"return"));
if (self.accept(is(.@";"))) |_| {
return ast.Statement{
.location = start.location,
.type = .return_void,
};
} else |_| {
const value = try self.acceptExpression();
_ = try self.accept(is(.@";"));
return ast.Statement{
.location = start.location,
.type = .{
.return_expr = value,
},
};
}
},
.@"var", .@"const" => {
const decl_type = try self.accept(oneOf(.{ .@"var", .@"const" }));
const name = try self.accept(is(.identifier));
const decider = try self.accept(oneOf(.{ .@";", .@"=" }));
var stmt = ast.Statement{
.location = start.location.merge(name.location),
.type = .{
.declaration = .{
.variable = name.text,
.initial_value = null,
.is_const = (decl_type.type == .@"const"),
},
},
};
if (decider.type == .@"=") {
const value = try self.acceptExpression();
_ = try self.accept(is(.@";"));
stmt.type.declaration.initial_value = value;
}
return stmt;
},
else => {
const expr = try self.acceptExpression();
if ((expr.type == .function_call) or (expr.type == .method_call)) {
_ = try self.accept(is(.@";"));
return ast.Statement{
.location = expr.location,
.type = .{
.discard_value = expr,
},
};
} else {
const mode = try self.accept(oneOf(.{
.@"=",
.@"+=",
.@"-=",
.@"*=",
.@"/=",
.@"%=",
}));
const value = try self.acceptExpression();
_ = try self.accept(is(.@";"));
return switch (mode.type) {
.@"+=", .@"-=", .@"*=", .@"/=", .@"%=" => ast.Statement{
.location = expr.location,
.type = .{
.assignment = .{
.target = expr,
.value = ast.Expression{
.location = expr.location,
.type = .{
.binary_operator = .{
.operator = switch (mode.type) {
.@"+=" => .add,
.@"-=" => .subtract,
.@"*=" => .multiply,
.@"/=" => .divide,
.@"%=" => .modulus,
else => unreachable,
},
.lhs = try self.moveToHeap(expr),
.rhs = try self.moveToHeap(value),
},
},
},
},
},
},
.@"=" => ast.Statement{
.location = expr.location,
.type = .{
.assignment = .{
.target = expr,
.value = value,
},
},
},
else => unreachable,
};
}
},
}
}
fn acceptExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
return try self.acceptLogicCombinatorExpression();
}
fn acceptLogicCombinatorExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var expr = try self.acceptComparisonExpression();
while (true) {
const and_or = self.accept(oneOf(.{ .@"and", .@"or" })) catch break;
const rhs = try self.acceptComparisonExpression();
const new_expr = ast.Expression{
.location = expr.location.merge(and_or.location).merge(rhs.location),
.type = .{
.binary_operator = .{
.operator = switch (and_or.type) {
.@"and" => .boolean_and,
.@"or" => .boolean_or,
else => unreachable,
},
.lhs = try self.moveToHeap(expr),
.rhs = try self.moveToHeap(rhs),
},
},
};
expr = new_expr;
}
return expr;
}
fn acceptComparisonExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var expr = try self.acceptSumExpression();
while (true) {
const and_or = self.accept(oneOf(.{
.@"<=",
.@">=",
.@">",
.@"<",
.@"==",
.@"!=",
})) catch break;
const rhs = try self.acceptSumExpression();
const new_expr = ast.Expression{
.location = expr.location.merge(and_or.location).merge(rhs.location),
.type = .{
.binary_operator = .{
.operator = switch (and_or.type) {
.@"<=" => .less_or_equal_than,
.@">=" => .greater_or_equal_than,
.@">" => .greater_than,
.@"<" => .less_than,
.@"==" => .equal,
.@"!=" => .different,
else => unreachable,
},
.lhs = try self.moveToHeap(expr),
.rhs = try self.moveToHeap(rhs),
},
},
};
expr = new_expr;
}
return expr;
}
fn acceptSumExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var expr = try self.acceptMulExpression();
while (true) {
const and_or = self.accept(oneOf(.{
.@"+",
.@"-",
})) catch break;
const rhs = try self.acceptMulExpression();
const new_expr = ast.Expression{
.location = expr.location.merge(and_or.location).merge(rhs.location),
.type = .{
.binary_operator = .{
.operator = switch (and_or.type) {
.@"+" => .add,
.@"-" => .subtract,
else => unreachable,
},
.lhs = try self.moveToHeap(expr),
.rhs = try self.moveToHeap(rhs),
},
},
};
expr = new_expr;
}
return expr;
}
fn acceptMulExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var expr = try self.acceptUnaryPrefixOperatorExpression();
while (true) {
const and_or = self.accept(oneOf(.{
.@"*",
.@"/",
.@"%",
})) catch break;
const rhs = try self.acceptUnaryPrefixOperatorExpression();
const new_expr = ast.Expression{
.location = expr.location.merge(and_or.location).merge(rhs.location),
.type = .{
.binary_operator = .{
.operator = switch (and_or.type) {
.@"*" => .multiply,
.@"/" => .divide,
.@"%" => .modulus,
else => unreachable,
},
.lhs = try self.moveToHeap(expr),
.rhs = try self.moveToHeap(rhs),
},
},
};
expr = new_expr;
}
return expr;
}
fn acceptUnaryPrefixOperatorExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
if (self.accept(oneOf(.{ .not, .@"-" }))) |prefix| {
// this must directly recurse as we can write `not not x`
const value = try self.acceptUnaryPrefixOperatorExpression();
return ast.Expression{
.location = prefix.location.merge(value.location),
.type = .{
.unary_operator = .{
.operator = switch (prefix.type) {
.not => .boolean_not,
.@"-" => .negate,
else => unreachable,
},
.value = try self.moveToHeap(value),
},
},
};
} else |_| {
return try self.acceptIndexingExpression();
}
}
fn acceptIndexingExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var value = try self.acceptCallExpression();
while (self.accept(is(.@"["))) |_| {
const index = try self.acceptExpression();
_ = try self.accept(is(.@"]"));
const new_value = ast.Expression{
.location = value.location.merge(index.location),
.type = .{
.array_indexer = .{
.value = try self.moveToHeap(value),
.index = try self.moveToHeap(index),
},
},
};
value = new_value;
} else |_| {}
return value;
}
fn acceptCallExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
var value = try self.acceptValueExpression();
while (self.accept(oneOf(.{ .@"(", .@"." }))) |sym| {
const new_value = switch (sym.type) {
// call
.@"(" => blk: {
var args = std.ArrayList(ast.Expression).empty;
defer args.deinit(self.allocator);
var loc = value.location;
if (self.accept(is(.@")"))) |_| {
// this is the end of the argument list
} else |_| {
while (true) {
const arg = try self.acceptExpression();
try args.append(self.allocator, arg);
const terminator = try self.accept(oneOf(.{ .@")", .@"," }));
loc = terminator.location.merge(loc);
if (terminator.type == .@")")
break;
}
}
break :blk ast.Expression{
.location = loc,
.type = .{
.function_call = .{
.function = try self.moveToHeap(value),
.arguments = try args.toOwnedSlice(self.allocator),
},
},
};
},
//field access or method call
.@"." => blk: {
const field_name = try self.accept(is(.identifier));
if (self.accept(is(.@"("))) |_| {
// method call
var args = std.ArrayList(ast.Expression).empty;
defer args.deinit(self.allocator);
var loc = value.location;
if (self.accept(is(.@")"))) |_| {
// this is the end of the argument list
} else |_| {
while (true) {
const arg = try self.acceptExpression();
try args.append(self.allocator, arg);
const terminator = try self.accept(oneOf(.{ .@")", .@"," }));
loc = terminator.location.merge(loc);
if (terminator.type == .@")")
break;
}
}
break :blk ast.Expression{
.location = loc,
.type = .{
.method_call = .{
.object = try self.moveToHeap(value),
.name = field_name.text,
.arguments = try args.toOwnedSlice(self.allocator),
},
},
};
} else |_| {
//field access
break :blk ast.Expression{
.location = value.location,
.type = .{
.field_access = .{
.@"struct" = try self.moveToHeap(value),
.name = field_name.text,
},
},
};
}
},
else => unreachable,
};
value = new_value;
} else |_| {}
return value;
}
fn acceptStructExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
const token = try self.accept(is(.@"["));
var loc: Location = token.location;
var entries: std.ArrayList(struct { []const u8, *ast.Expression }) = .empty;
errdefer {
for (entries.items) |entry| {
self.allocator.destroy(entry.@"1");
}
entries.deinit(self.allocator);
}
while (true) {
if (self.accept(is(.@"]"))) |_| {
break;
} else |_| {
_ = try self.accept(is(.@"."));
const field = try self.accept(is(.identifier));
_ = try self.accept(is(.@"="));
const item = try self.acceptExpression();
try entries.append(self.allocator, .{ field.text, try self.moveToHeap(item) });
const delimit = try self.accept(oneOf(.{ .@",", .@"]" }));
loc = loc.merge(delimit.location);
if (delimit.type == .@"]")
break;
}
}
if (entries.items.len == 0) {
//this is a list type by default
entries.deinit(self.allocator);
return ast.Expression{
.location = loc,
.type = .{ .array_literal = try self.allocator.alloc(ast.Expression, 0) },
};
}
return ast.Expression{
.location = loc,
.type = .{
.struct_literal = try entries.toOwnedSlice(self.allocator),
},
};
}
fn acceptValueExpression(self: *Self) ParseError!ast.Expression {
const state = self.saveState();
errdefer self.restoreState(state);
if (self.acceptStructExpression()) |t| {
return t;
} else |_| {
self.restoreState(state);
}
const token = try self.accept(oneOf(.{
.@"(",
.@"[",
.number_literal,
.string_literal,
.character_literal,
.identifier,
}));
switch (token.type) {
.@"(" => {
const value = try self.acceptExpression();
_ = try self.accept(is(.@")"));
return value;
},
.@"[" => {
var array = std.ArrayList(ast.Expression).empty;
defer array.deinit(self.allocator);
while (true) {
if (self.accept(is(.@"]"))) |_| {
break;
} else |_| {
const item = try self.acceptExpression();
try array.append(self.allocator, item);
const delimit = try self.accept(oneOf(.{ .@",", .@"]" }));
if (delimit.type == .@"]")
break;
}
}
return ast.Expression{
.location = token.location,
.type = .{
.array_literal = try array.toOwnedSlice(self.allocator),
},
};
},
.number_literal => {
const val = if (std.mem.startsWith(u8, token.text, "0x"))
@as(f64, @floatFromInt(std.fmt.parseInt(i54, token.text[2..], 16) catch return self.emitDiagnostics("`{s}` is not a valid hexadecimal number!", .{token.text})))
else
std.fmt.parseFloat(f64, token.text) catch return self.emitDiagnostics("`{s}` is not a valid number!", .{token.text});
return ast.Expression{
.location = token.location,
.type = .{
.number_literal = val,
},
};
},
.string_literal => {
std.debug.assert(token.text.len >= 2);
return ast.Expression{
.location = token.location,
.type = .{
.string_literal = self.escapeString(token.text[1 .. token.text.len - 1]) catch return self.emitDiagnostics("Invalid escape sequence in {s}!", .{token.text}),
},
};
},
.character_literal => {
std.debug.assert(token.text.len >= 2);
const escaped_text = self.escapeString(token.text[1 .. token.text.len - 1]) catch return self.emitDiagnostics("Invalid escape sequence in {s}!", .{token.text});
var value: u21 = undefined;
if (escaped_text.len == 0) {
return error.SyntaxError;
} else if (escaped_text.len == 1) {
// this is a shortcut for non-utf8 encoded files.
// it's not a perfect heuristic, but it's okay.
value = escaped_text[0];
} else {
const utf8_len = std.unicode.utf8ByteSequenceLength(escaped_text[0]) catch return self.emitDiagnostics("Invalid utf8 sequence: `{s}`!", .{escaped_text});
if (escaped_text.len != utf8_len)
return error.SyntaxError;
value = std.unicode.utf8Decode(escaped_text[0..utf8_len]) catch return self.emitDiagnostics("Invalid utf8 sequence: `{s}`!", .{escaped_text});
}
return ast.Expression{
.location = token.location,
.type = .{
.number_literal = @as(f64, @floatFromInt(value)),
},
};
},
.identifier => return ast.Expression{
.location = token.location,
.type = .{
.variable_expr = token.text,
},
},
else => unreachable,
}
}
};
var parser = Parser{
.allocator = arena.allocator(),
.sequence = sequence,
.diagnostics = diagnostics,
};
while (parser.index < parser.sequence.len) {
const state = parser.saveState();
// look-ahead one token and try accepting a "function" keyword,
// use that to select between parsing a function or a statement.
if (parser.accept(Parser.is(.function))) |_| {
// we need to unaccept the function token
parser.restoreState(state);
const fun = try parser.acceptFunction();
try functions.append(alloc, fun);
} else |_| {
// no need to unaccept here as we didn't accept in the first place
const stmt = parser.acceptStatement() catch |err| switch (err) {
error.SyntaxError => {
// Do some recovery here:
try diagnostics.emit(.@"error", parser.getCurrentLocation(), "syntax error!", .{});
while (parser.index < parser.sequence.len) {
const recovery_state = parser.saveState();
const tok = try parser.accept(Parser.any);
if (tok.type == .@";")
break;
// We want to be able to parse the next function properly
// even if we have syntax errors.
if (tok.type == .function) {
parser.restoreState(recovery_state);
break;
}
}
continue;
},
else => |e| return e,
};
try root_script.append(alloc, stmt);
}
}
return ast.Program{
.arena = arena,
.root_script = try root_script.toOwnedSlice(alloc),
.functions = try functions.toOwnedSlice(alloc),
};
}
fn testTokenize(str: []const u8) ![]lexer.Token {
var result = std.ArrayList(lexer.Token).empty;
var tokenizer = lexer.Tokenizer.init("testsrc", str);
while (true) {
switch (tokenizer.next()) {
.end_of_file => return result.toOwnedSlice(std.testing.allocator),
.invalid_sequence => unreachable, // we don't do that here
.token => |token| try result.append(std.testing.allocator, token),
}
}
}
fn expectEqual(expected: anytype, actual: anytype) !void {
const T = @TypeOf(expected);
return try std.testing.expectEqual(expected, @as(T, actual));
}
const expectEqualStrings = std.testing.expectEqualStrings;
test "empty file parsing" {
var diagnostics = diag.Diagnostics.init(std.testing.allocator);
defer diagnostics.deinit();
var pgm = try parse(std.testing.allocator, &diagnostics, &[_]lexer.Token{});
defer pgm.deinit();
// assert that an empty file results in a empty AST
try expectEqual(@as(usize, 0), pgm.root_script.len);
try expectEqual(@as(usize, 0), pgm.functions.len);
// assert that we didn't encounter syntax errors
try expectEqual(@as(usize, 0), diagnostics.messages.items.len);
}
fn parseTest(string: []const u8) !ast.Program {
const seq = try testTokenize(string);
defer std.testing.allocator.free(seq);
var diagnostics = diag.Diagnostics.init(std.testing.allocator);
defer diagnostics.deinit();
return try parse(std.testing.allocator, &diagnostics, seq);
}
test "parse single top level statement" {
// test with the simplest of all statements:
// the empty one
var pgm = try parseTest(";");
defer pgm.deinit();
try expectEqual(@as(usize, 0), pgm.functions.len);
try expectEqual(@as(usize, 1), pgm.root_script.len);
try expectEqual(ast.Statement.Type.empty, pgm.root_script[0].type);
}
test "parse single empty function" {
// 0 params
{
var pgm = try parseTest("function empty(){}");
defer pgm.deinit();
try expectEqual(@as(usize, 1), pgm.functions.len);
try expectEqual(@as(usize, 0), pgm.root_script.len);
const fun = pgm.functions[0];
try std.testing.expectEqualStrings("empty", fun.name);
try expectEqual(ast.Statement.Type.block, fun.body.type);
try expectEqual(@as(usize, 0), fun.body.type.block.len);
try expectEqual(@as(usize, 0), fun.parameters.len);
}
// 1 param
{