-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.zig
2260 lines (1987 loc) · 85.3 KB
/
parser.zig
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("lexer.zig").Lexer;
const Token = @import("token.zig").Token;
const Expr = @import("expr.zig").Expr;
const Pattern = @import("pattern.zig").Pattern;
const Instr = @import("instr.zig").Instr;
pub fn parse(allocator: std.mem.Allocator, content: []const u8) Parser.Error!Expr {
var parser = Parser.init(allocator, content);
return try parser.parseModule();
}
pub fn internal_parse(allocator: std.mem.Allocator, content: []const u8) Parser.Error!Expr {
var parser = Parser.init(allocator, content);
parser.lexer.internal = true;
const body = try parser.parseBody(&.{.eof});
return body.expr;
}
pub const Parser = struct {
allocator: std.mem.Allocator,
lexer: Lexer,
token: ?Token = null,
expected: std.EnumSet(Token.Type) = undefined,
last_index: usize = 0,
skip_newlines: bool = false,
is_gen: bool = false,
error_reason: enum { unexpected_token, invalid_float, duplicate_fn_name } = undefined,
pub const Error = std.mem.Allocator.Error || error{ParseError};
pub fn init(allocator: std.mem.Allocator, content: []const u8) Parser {
return .{
.allocator = allocator,
.lexer = Lexer.init(content),
};
}
pub fn parseModule(self: *Parser) Error!Expr {
const start = self.getStart();
var fn_names = std.StringHashMap(void).init(self.allocator);
defer fn_names.deinit();
var stmts = std.ArrayList(Expr.Stmt).init(self.allocator);
defer {
for (stmts.items) |stmt| stmt.deinit(self.allocator);
stmts.deinit();
}
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = false;
while (true) {
while (self.skip(&.{.newline}) != null) {}
if (self.skip(&.{.eof}) != null) break;
var stmt: Expr.Stmt = undefined;
stmt.is_pub = self.skip(&.{.@"pub"}) != null;
if (self.skip(&.{.@"fn"}) != null) {
const token = try self.expect(&.{.name});
const result = try fn_names.getOrPut(token.content);
if (result.found_existing) {
self.token = token;
self.error_reason = .duplicate_fn_name;
return error.ParseError;
}
stmt.fn_name = token.content;
stmt.pattern = try self.parseCol(.list, .pattern, .lpar, .rpar);
errdefer stmt.pattern.deinit(self.allocator);
stmt.subject = try self.parseExpr(.expr);
} else if (stmt.is_pub) {
stmt.fn_name = null;
stmt.pattern = try self.parseGuard(.pattern);
errdefer stmt.pattern.deinit(self.allocator);
_ = try self.expect(&.{.assign});
stmt.subject = try self.parseExpr(.expr);
} else {
stmt.fn_name = null;
const result = try self.parseGuard(.both);
const assign = switch (result.data) {
.expr => false,
.pattern => assign: {
errdefer result.deinit(self.allocator);
_ = try self.expect(&.{.assign});
break :assign true;
},
.both => self.skip(&.{.assign}) != null,
};
if (assign) {
stmt.pattern = ParseType.both.toPattern(self.allocator, result);
errdefer stmt.pattern.deinit(self.allocator);
stmt.subject = try self.parseExpr(.expr);
} else {
stmt.pattern = .{ .data = .ignore, .location = .{} };
stmt.subject = ParseType.both.toExpr(self.allocator, result);
}
}
errdefer stmt.deinit(self.allocator);
if (!self.peek(&.{.eof})) _ = try self.expect(&.{.newline});
try stmts.append(stmt);
}
const location = self.getLocation(start);
return .{
.data = .{ .module = try stmts.toOwnedSlice() },
.location = location,
};
}
fn parseBody(self: *Parser, ends: []const Token.Type) Error!Body {
var lets = std.ArrayList(Let).init(self.allocator);
var last_expr: ?Expr = null;
var last_start: usize = undefined;
defer {
for (lets.items) |let| let.deinit(self.allocator);
lets.deinit();
if (last_expr) |expr| expr.deinit(self.allocator);
}
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = false;
const end = while (true) {
while (self.skip(&.{.newline}) != null) {}
if (self.skip(ends)) |end| break end;
if (last_expr) |expr| {
try lets.append(.{
.pattern = .{ .data = .ignore, .location = .{} },
.expr = expr,
.default = null,
.start = last_start,
});
last_expr = null;
}
const start = self.getStart();
const result = try self.parseGuard(.both);
const assign = switch (result.data) {
.expr => false,
.pattern => assign: {
errdefer result.deinit(self.allocator);
_ = try self.expect(&.{.assign});
break :assign true;
},
.both => self.skip(&.{.assign}) != null,
};
if (assign) {
const pattern = ParseType.both.toPattern(self.allocator, result);
errdefer pattern.deinit(self.allocator);
const expr = try self.parseExpr(.expr);
errdefer expr.deinit(self.allocator);
var default: ?Expr = undefined;
if (self.skip(&.{.@"else"}) == null) {
default = null;
} else {
_ = try self.expect(&.{.@"return"});
default = try self.parseExpr(.expr);
}
errdefer if (default) |default_| default_.deinit(self.allocator);
try lets.append(.{
.pattern = pattern,
.expr = expr,
.default = default,
.start = start,
});
} else {
last_expr = ParseType.both.toExpr(self.allocator, result);
last_start = start;
}
if (!self.peek(ends)) _ = try self.expect(&.{.newline});
};
var expr = last_expr orelse Expr{ .data = .null, .location = .{} };
last_expr = null;
errdefer expr.deinit(self.allocator);
while (lets.popOrNull()) |let| {
errdefer let.deinit(self.allocator);
const matchers = try self.allocator.alloc(Expr.Matcher, if (let.default == null) 1 else 2);
errdefer self.allocator.free(matchers);
matchers[0] = .{ .pattern = let.pattern, .expr = expr };
if (let.default) |default| matchers[1] = .{
.pattern = .{ .data = .ignore, .location = .{} },
.expr = default,
};
const match = try self.allocator.create(Expr.Match);
match.* = .{ .subject = let.expr, .matchers = matchers };
const location = self.getLocation(let.start);
expr = .{ .data = .{ .match = match }, .location = location };
}
return .{ .expr = expr, .end = end };
}
fn parseGuard(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseExpr(parse_type);
if (!parse_type.isPattern(result) or self.skip(&.{.@"if"}) == null) return result;
const pattern = parse_type.toPattern(self.allocator, result);
errdefer pattern.deinit(self.allocator);
const cond = try self.parseExpr(.expr);
errdefer cond.deinit(self.allocator);
const guard = try self.allocator.create(Pattern.Guard);
guard.* = .{ .pattern = pattern, .cond = cond };
const location = self.getLocation(start);
return parse_type.fromPattern(.{
.data = .{ .guard = guard },
.location = location,
});
}
pub fn parseExpr(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
return self.parseOr(parse_type);
}
fn parseOr(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseAnd(parse_type);
if (!parse_type.isExpr(result) or self.skip(&.{.@"or"}) == null) return result;
const lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
const rhs = try self.parseOr(.expr);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
return parse_type.fromExpr(.{ .data = .{ .@"or" = bin }, .location = location });
}
fn parseAnd(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseNot(parse_type);
if (!parse_type.isExpr(result) or self.skip(&.{.@"and"}) == null) return result;
const lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
const rhs = try self.parseAnd(.expr);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
return parse_type.fromExpr(.{ .data = .{ .@"and" = bin }, .location = location });
}
fn parseNot(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
if (parse_type == .pattern) return try self.parseCmp(parse_type);
if (self.skip(&.{.not}) == null) return try self.parseCmp(parse_type);
const expr = try self.allocator.create(Expr);
errdefer self.allocator.destroy(expr);
expr.* = try self.parseNot(.expr);
const location = self.getLocation(start);
return parse_type.fromExpr(.{ .data = .{ .not = expr }, .location = location });
}
fn parseCmp(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseAdd(parse_type);
if (!parse_type.isExpr(result)) return result;
const token = self.skip(&.{ .eq, .ne, .lt, .le, .gt, .ge, .in }) orelse return result;
const lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
var last_op = switch (token.type) {
inline .eq, .ne, .lt, .le, .gt, .ge, .in => |tag| @field(Expr.Cmp.Op, @tagName(tag)),
else => unreachable,
};
var last_rhs = try self.parseAdd(.expr);
errdefer last_rhs.deinit(self.allocator);
var cmps = std.ArrayList(Expr.Cmp).init(self.allocator);
defer {
for (cmps.items) |op| op.deinit(self.allocator);
cmps.deinit();
}
while (self.skip(&.{ .eq, .ne, .lt, .le, .gt, .ge, .in })) |token_| {
const op = switch (token_.type) {
inline .eq, .ne, .lt, .le, .gt, .ge, .in => |tag| @field(Expr.Cmp.Op, @tagName(tag)),
else => unreachable,
};
const rhs = try self.parseAdd(.expr);
errdefer rhs.deinit(self.allocator);
try cmps.append(.{ .op = last_op, .rhs = last_rhs });
last_op = op;
last_rhs = rhs;
}
const cmp_root = try self.allocator.create(Expr.CmpRoot);
errdefer self.allocator.destroy(cmp_root);
cmp_root.* = .{
.lhs = lhs,
.cmps = try cmps.toOwnedSlice(),
.last_op = last_op,
.last_rhs = last_rhs,
};
const location = self.getLocation(start);
return parse_type.fromExpr(.{ .data = .{ .cmp = cmp_root }, .location = location });
}
fn parseAdd(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseMul(parse_type);
if (!parse_type.isExpr(result) or !self.peek(&.{ .add, .sub })) return result;
var lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
while (self.skip(&.{ .add, .sub })) |op| {
const rhs = try self.parseMul(.expr);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
lhs = .{
.data = switch (op.type) {
inline .add, .sub => |tag| @unionInit(Expr.Data, @tagName(tag), bin),
else => unreachable,
},
.location = location,
};
}
return parse_type.fromExpr(lhs);
}
fn parseMul(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseNeg(parse_type);
if (!parse_type.isExpr(result) or !self.peek(&.{ .mul, .div })) return result;
var lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
while (self.skip(&.{ .mul, .div })) |op| {
const rhs = try self.parseNeg(.expr);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
lhs = .{
.data = switch (op.type) {
inline .mul, .div => |tag| @unionInit(Expr.Data, @tagName(tag), bin),
else => unreachable,
},
.location = location,
};
}
return parse_type.fromExpr(lhs);
}
fn parseNeg(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
if (parse_type == .pattern) return try self.parsePow(parse_type);
const op = self.skip(&.{ .add, .sub }) orelse return try self.parsePow(parse_type);
const expr = try self.allocator.create(Expr);
errdefer self.allocator.destroy(expr);
expr.* = try self.parseNeg(.expr);
const location = self.getLocation(start);
return parse_type.fromExpr(.{
.data = switch (op.type) {
.add => .{ .pos = expr },
.sub => .{ .neg = expr },
else => unreachable,
},
.location = location,
});
}
fn parsePow(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseCall(parse_type, false);
if (!parse_type.isExpr(result) or self.skip(&.{.pow}) == null) return result;
const lhs = parse_type.toExpr(self.allocator, result);
errdefer lhs.deinit(self.allocator);
const rhs = try self.parseNeg(.expr);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
return parse_type.fromExpr(.{ .data = .{ .pow = bin }, .location = location });
}
fn parseCall(self: *Parser, comptime parse_type: ParseType, get_only: bool) Error!parse_type.Result() {
const start = self.getStart();
const result = try self.parseLit(parse_type);
if (!parse_type.isExpr(result) or !self.peek(if (get_only) &.{ .dot, .llist } else &.{ .lpar, .pipe, .dot, .llist })) return result;
var lhs = parse_type.toExpr(self.allocator, result);
while (true) {
if (!get_only and self.peek(&.{.lpar})) {
errdefer lhs.deinit(self.allocator);
const rhs = try self.parseCol(.list, .expr, .lpar, .rpar);
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
lhs = .{ .data = .{ .call = bin }, .location = location };
} else if (!get_only and self.skip(&.{.pipe}) != null) {
var owner = true;
errdefer if (owner) lhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
errdefer self.allocator.destroy(bin);
bin.lhs = try self.parseCall(.expr, true);
errdefer bin.lhs.deinit(self.allocator);
const col_start = self.getStart();
_ = try self.expect(&.{.lpar});
const items_start = self.getStart();
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
var state = ColState(.list, .expr).init(self.allocator);
defer state.deinit();
try state.append(null, undefined, lhs);
owner = false;
bin.rhs = try self.parseColTail(.list, .expr, &state, col_start, items_start, .rpar);
const location = self.getLocation(start);
lhs = .{ .data = .{ .call = bin }, .location = location };
} else if (self.skip(&.{.dot}) != null) {
errdefer lhs.deinit(self.allocator);
const key_start = self.getStart();
const name = try self.expect(&.{.name});
const key_location = self.getLocation(key_start);
const rhs = Expr{
.data = .{ .str = try self.allocator.dupe(u8, name.content) },
.location = key_location,
};
errdefer rhs.deinit(self.allocator);
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = rhs };
const location = self.getLocation(start);
lhs = .{ .data = .{ .get = bin }, .location = location };
} else if (self.skip(&.{.llist}) != null) {
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
errdefer lhs.deinit(self.allocator);
const mhs = try self.parseExpr(.expr);
errdefer mhs.deinit(self.allocator);
if (self.skip(&.{.slice}) != null) {
const rhs = try self.parseExpr(.expr);
errdefer rhs.deinit(self.allocator);
_ = try self.expect(&.{.rlist});
const tri = try self.allocator.create(Expr.Tri);
tri.* = .{ .lhs = lhs, .mhs = mhs, .rhs = rhs };
const location = self.getLocation(start);
lhs = .{ .data = .{ .slice = tri }, .location = location };
} else {
_ = try self.expect(&.{.rlist});
const bin = try self.allocator.create(Expr.Bin);
bin.* = .{ .lhs = lhs, .rhs = mhs };
const location = self.getLocation(start);
lhs = .{ .data = .{ .get = bin }, .location = location };
}
} else {
break;
}
}
return parse_type.fromExpr(lhs);
}
fn parseLit(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
if (self.peek(&.{.name})) {
return try self.parseName(parse_type);
} else if (self.peek(&.{.num})) {
return try parse_type.fromLit(self.allocator, try self.parseNum());
} else if (self.peek(&.{.bool})) {
return try parse_type.fromLit(self.allocator, try self.parseBool());
} else if (self.peek(&.{.null})) {
return try parse_type.fromLit(self.allocator, try self.parseNull());
} else if (self.peek(&.{.str})) {
return try self.parseStr(parse_type);
} else if (parse_type != .expr and self.peek(&.{.ignore})) {
return parse_type.fromPattern(try self.parseIgnore());
} else if (self.peek(&.{.llist})) {
return try self.parseCol(.list, parse_type, .llist, .rlist);
} else if (self.peek(&.{.ldict})) {
return try self.parseCol(.dict, parse_type, .ldict, .rdict);
} else if (parse_type != .pattern and self.peek(&.{.lambda})) {
return parse_type.fromExpr(try self.parseLambda());
} else if (self.peek(&.{.lpar})) {
return try parse_type.fromLit(self.allocator, try self.parsePar());
} else if (parse_type != .pattern and self.peek(&.{.do})) {
return parse_type.fromExpr(try self.parseDo());
} else if (parse_type != .pattern and self.peek(&.{.match})) {
return parse_type.fromExpr(try self.parseMatch());
} else if (parse_type != .pattern and self.peek(&.{.@"if"})) {
return parse_type.fromExpr(try self.parseIf());
} else if (parse_type != .pattern and self.peek(&.{.@"for"})) {
return parse_type.fromExpr(try self.parseFor());
} else if (parse_type != .pattern and self.is_gen and self.peek(&.{.yield})) {
return parse_type.fromExpr(try self.parseYield());
} else if (parse_type != .pattern and self.peek(&.{.@"return"})) {
return parse_type.fromExpr(try self.parseReturn());
} else if (parse_type != .pattern and self.peek(&.{.assert})) {
return parse_type.fromExpr(try self.parseAssert());
} else if (parse_type != .pattern and self.peek(&.{.@"try"})) {
return parse_type.fromExpr(try self.parseTry());
} else {
_ = try self.expect(&.{});
unreachable;
}
}
fn parseName(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
const token = try self.expect(&.{.name});
const location = self.getLocation(start);
return .{
.data = switch (parse_type) {
.expr, .pattern => .{ .name = token.content },
.both => .{ .both = .{
.expr = .{ .name = token.content },
.pattern = .{ .name = token.content },
} },
},
.location = location,
};
}
fn parseNum(self: *Parser) Error!Expr {
const start = self.getStart();
const token = try self.expect(&.{.num});
const value = std.fmt.parseFloat(f64, token.content) catch {
self.error_reason = .invalid_float;
return error.ParseError;
};
const location = self.getLocation(start);
return .{ .data = .{ .num = value }, .location = location };
}
fn parseBool(self: *Parser) Error!Expr {
const start = self.getStart();
const token = try self.expect(&.{.bool});
const value = std.mem.eql(u8, token.content, "true");
const location = self.getLocation(start);
return .{ .data = .{ .bool = value }, .location = location };
}
fn parseNull(self: *Parser) Error!Expr {
const start = self.getStart();
_ = try self.expect(&.{.null});
const location = self.getLocation(start);
return .{ .data = .null, .location = location };
}
fn parseStr(self: *Parser, comptime parse_type: ParseType) Error!parse_type.Result() {
const start = self.getStart();
_ = try self.expect(&.{.str});
var state = StrState(parse_type).init(self.allocator);
defer state.deinit();
return try self.parseStrTail(parse_type, &state, start);
}
fn parseStrTail(self: *Parser, comptime parse_type: ParseType, state: *StrState(parse_type), start: usize) Error!parse_type.Result() {
while (true) {
const chunk_start = self.lexer.index;
const chunk = try self.lexer.strChunk(self.allocator);
const chunk_end = self.lexer.index - @as(usize, if (chunk.expr) 2 else 1);
const chunk_location = Instr.Location{
.index = @truncate(chunk_start),
.len = @truncate(chunk_end - chunk_start),
};
self.last_index = self.lexer.index;
if (chunk.expr) {
const result: parse_type.Result() = result: {
errdefer self.allocator.free(chunk.content);
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
const result = try self.parseExpr(parse_type);
errdefer result.deinit(self.allocator);
_ = try self.expect(&.{.rdict});
break :result result;
};
switch (parse_type) {
.expr, .pattern => try state.append(chunk.content, chunk_location, result),
.both => switch (result.detail()) {
.expr => |expr| {
var expr_state = state.toExpr();
try expr_state.append(chunk.content, chunk_location, expr);
return parse_type.fromExpr(try self.parseStrTail(.expr, &expr_state, start));
},
.pattern => |pattern| {
var pattern_state = state.toPattern();
try pattern_state.append(chunk.content, chunk_location, pattern);
return parse_type.fromPattern(try self.parseStrTail(.pattern, &pattern_state, start));
},
.both => |both| try state.append(chunk.content, chunk_location, both),
},
}
} else if (state.isEmpty()) {
const location = self.getLocation(start);
const expr = .{
.data = .{ .str = chunk.content },
.location = location,
};
return try parse_type.fromLit(self.allocator, expr);
} else {
const location = self.getLocation(start);
return .{
.data = try state.toResult(chunk.content, chunk_location),
.location = location,
};
}
}
}
fn parseIgnore(self: *Parser) Error!Pattern {
const start = self.getStart();
_ = try self.expect(&.{.ignore});
const location = self.getLocation(start);
return .{ .data = .ignore, .location = location };
}
fn parseCol(
self: *Parser,
comptime col_type: ColType,
comptime parse_type: ParseType,
start: Token.Type,
end: Token.Type,
) Error!parse_type.Result() {
const col_start = self.getStart();
_ = try self.expect(&.{start});
const items_start = self.getStart();
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
var state = ColState(col_type, parse_type).init(self.allocator);
defer state.deinit();
return try self.parseColTail(col_type, parse_type, &state, col_start, items_start, end);
}
fn parseColTail(
self: *Parser,
comptime col_type: ColType,
comptime parse_type: ParseType,
state: *ColState(col_type, parse_type),
start: usize,
init_items_start: usize,
end: Token.Type,
) Error!parse_type.Result() {
var items_start = init_items_start;
const items_location = while (true) {
var items_location: ?Instr.Location = self.getLocation(start);
if (self.skip(&.{end}) != null) break items_location.?;
if (self.skip(&.{.mul}) == null) items_location = null;
var owner = true;
var key: Expr = undefined;
var item: parse_type.Result() = undefined;
if (col_type != .dict or items_location != null) {
item = try self.parseExpr(parse_type);
} else if (self.peek(&.{.name}) and self.peekAhead(1, &.{ .comma, end })) {
const key_start = self.getStart();
const token = try self.expect(&.{.name});
const location = self.getLocation(key_start);
key = .{
.data = .{ .str = try self.allocator.dupe(u8, token.content) },
.location = location,
};
item = .{
.data = switch (parse_type) {
.expr, .pattern => .{ .name = token.content },
.both => .{ .both = .{
.expr = .{ .name = token.content },
.pattern = .{ .name = token.content },
} },
},
.location = location,
};
} else {
key = try self.parseExpr(.expr);
errdefer key.deinit(self.allocator);
_ = try self.expect(&.{.assign});
item = try self.parseExpr(parse_type);
}
errdefer if (owner) {
if (col_type == .dict and items_location == null) key.deinit(self.allocator);
item.deinit(self.allocator);
};
if (!self.peek(&.{end})) _ = try self.expect(&.{.comma});
if (items_location != null) items_start = self.getStart();
switch (parse_type) {
.expr, .pattern => {
try state.append(items_location, key, item);
},
.both => switch (item.detail()) {
.expr => |expr| {
var expr_state = try state.toExpr();
defer expr_state.deinit();
try expr_state.append(items_location, key, expr);
owner = false;
return parse_type.fromExpr(try self.parseColTail(col_type, .expr, &expr_state, start, items_start, end));
},
.pattern => |pattern| {
var pattern_state = try state.toPattern();
defer pattern_state.deinit();
try pattern_state.append(items_location, key, pattern);
owner = false;
return parse_type.fromPattern(try self.parseColTail(col_type, .pattern, &pattern_state, start, items_start, end));
},
.both => |both| {
try state.append(items_location, key, both);
},
},
}
};
return .{
.data = try state.toResult(items_location),
.location = self.getLocation(start),
};
}
fn parseLambda(self: *Parser) Error!Expr {
const old_is_gen = self.is_gen;
defer self.is_gen = old_is_gen;
self.is_gen = false;
const start = self.getStart();
const matcher = try self.allocator.create(Expr.Matcher);
errdefer self.allocator.destroy(matcher);
matcher.pattern = try self.parseCol(.list, .pattern, .lambda, .lambda);
errdefer matcher.pattern.deinit(self.allocator);
matcher.expr = try self.parseExpr(.expr);
const location = self.getLocation(start);
return .{ .data = .{ .lambda = matcher }, .location = location };
}
fn parsePar(self: *Parser) Error!Expr {
_ = try self.expect(&.{.lpar});
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
const expr = try self.parseExpr(.expr);
errdefer expr.deinit(self.allocator);
_ = try self.expect(&.{.rpar});
return expr;
}
fn parseDo(self: *Parser) Error!Expr {
const start = self.getStart();
_ = try self.expect(&.{.do});
const is_gen = self.skip(&.{.mul}) != null;
const old_is_gen = self.is_gen;
defer self.is_gen = old_is_gen;
if (is_gen) self.is_gen = true;
const body = try self.parseBody(&.{.end});
if (!is_gen) return body.expr;
errdefer body.expr.deinit(self.allocator);
const expr_ptr = try self.allocator.create(Expr);
expr_ptr.* = body.expr;
const location = self.getLocation(start);
return .{ .data = .{ .gen = expr_ptr }, .location = location };
}
fn parseMatch(self: *Parser) Error!Expr {
const start = self.getStart();
_ = try self.expect(&.{.match});
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
const subject = try self.parseExpr(.expr);
errdefer subject.deinit(self.allocator);
_ = try self.expect(&.{.do});
self.skip_newlines = false;
var matchers = std.ArrayList(Expr.Matcher).init(self.allocator);
defer {
for (matchers.items) |matcher| matcher.deinit(self.allocator);
matchers.deinit();
}
while (true) {
while (self.skip(&.{.newline}) != null) {}
if (self.skip(&.{.end}) != null) break;
const pattern = try self.parseGuard(.pattern);
errdefer pattern.deinit(self.allocator);
_ = try self.expect(&.{.assign});
const expr = try self.parseExpr(.expr);
errdefer expr.deinit(self.allocator);
if (!self.peek(&.{.end})) _ = try self.expect(&.{.newline});
try matchers.append(.{ .pattern = pattern, .expr = expr });
}
const match = try self.allocator.create(Expr.Match);
errdefer self.allocator.destroy(match);
match.* = .{
.subject = subject,
.matchers = try matchers.toOwnedSlice(),
};
const location = self.getLocation(start);
return .{ .data = .{ .match = match }, .location = location };
}
fn parseIf(self: *Parser) Error!Expr {
var start = self.getStart();
_ = try self.expect(&.{.@"if"});
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
var branches = std.ArrayList(IfBranch).init(self.allocator);
defer {
for (branches.items) |branch| branch.deinit(self.allocator);
branches.deinit();
}
const has_else = while (true) {
const result = try self.parseGuard(.both);
const assign = switch (result.data) {
.expr => false,
.pattern => assign: {
errdefer result.deinit(self.allocator);
_ = try self.expect(&.{.assign});
break :assign true;
},
.both => self.skip(&.{.assign}) != null,
};
var cond: IfCond = undefined;
if (assign) {
const pattern = ParseType.both.toPattern(self.allocator, result);
errdefer pattern.deinit(self.allocator);
const expr = try self.parseExpr(.expr);
cond = .{ .match = .{ .pattern = pattern, .expr = expr } };
} else {
cond = .{ .@"if" = ParseType.both.toExpr(self.allocator, result) };
}
errdefer cond.deinit(self.allocator);
_ = try self.expect(&.{.do});
const body = try self.parseBody(&.{ .elif, .@"else", .end });
errdefer body.expr.deinit(self.allocator);
try branches.append(.{ .cond = cond, .then = body.expr, .start = start });
start = self.lexer.getIndex(body.end);
switch (body.end.type) {
.elif => {},
.@"else" => break true,
.end => break false,
else => unreachable,
}
};
var expr: Expr = undefined;
if (has_else) {
const body = try self.parseBody(&.{.end});
expr = body.expr;
} else {
expr = .{ .data = .null, .location = self.getLocation(start) };
}
errdefer expr.deinit(self.allocator);
while (branches.popOrNull()) |branch| {
errdefer branch.deinit(self.allocator);
expr = .{
.data = switch (branch.cond) {
.@"if" => |cond| data: {
const if_ = try self.allocator.create(Expr.Tri);
if_.* = .{ .lhs = cond, .mhs = branch.then, .rhs = expr };
break :data .{ .@"if" = if_ };
},
.match => |cond| data: {
const matchers = try self.allocator.alloc(Expr.Matcher, 2);
errdefer self.allocator.free(matchers);
matchers[0] = .{ .pattern = cond.pattern, .expr = branch.then };
matchers[1] = .{ .pattern = .{ .data = .ignore, .location = .{} }, .expr = expr };
const match = try self.allocator.create(Expr.Match);
match.* = .{ .subject = cond.expr, .matchers = matchers };
break :data .{ .match = match };
},
},
.location = self.getLocation(branch.start),
};
}
return expr;
}
fn parseFor(self: *Parser) Error!Expr {
_ = try self.expect(&.{.@"for"});
const old_skip = self.skip_newlines;
defer self.skip_newlines = old_skip;
self.skip_newlines = true;
const pattern = try self.parseExpr(.pattern);
errdefer pattern.deinit(self.allocator);
_ = try self.expect(&.{.in});
const start = self.getStart();
const subject = try self.parseExpr(.expr);
const location = self.getLocation(start);
errdefer subject.deinit(self.allocator);
_ = try self.expect(&.{.do});
const body = try self.parseBody(&.{.end});
errdefer body.expr.deinit(self.allocator);
const for_ = try self.allocator.create(Expr.For);
for_.* = .{
.subject = subject,
.matcher = .{ .pattern = pattern, .expr = body.expr },
};
return .{ .data = .{ .@"for" = for_ }, .location = location };
}
fn parseYield(self: *Parser) Error!Expr {
std.debug.assert(self.is_gen);
const start = self.getStart();
_ = try self.expect(&.{.yield});