-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
parse.zig
1937 lines (1730 loc) · 58.5 KB
/
parse.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 Allocator = std.mem.Allocator;
const zua = @import("zua.zig");
const Lexer = @import("lex.zig").Lexer;
const LexErrorContext = zua.lex.LexErrorContext;
const Token = @import("lex.zig").Token;
const Node = @import("ast.zig").Node;
const Tree = @import("ast.zig").Tree;
const AutoComptimeLookup = @import("comptime_lookup.zig").AutoComptimeLookup;
// Notes:
//
// Lua parser always parses into a function (called the 'main' function) which
// is always varargs (the values in the varargs differs depending on Lua version)
//
// Lua parses directly into bytecode with no AST step in between. This implementation
// will generate an AST, though, so it won't be a 1:1 port of the Lua parser.
//
// The functions in Parser are currently named the same as their Lua C
// counterparts, but that will/should probably change.
/// SHRT_MAX, only used when checking the local var vector size
pub const max_local_vars = std.math.maxInt(i16);
/// LUAI_MAXVARS in luaconf.h
pub const max_local_vars_per_func = 200;
/// LUAI_MAXCCALLS in luaconf.h
pub const max_syntax_levels = 200;
/// From llimits.h
pub const max_stack_size = 250;
pub const ParseError = error{
FunctionArgumentsExpected,
ExpectedEqualsOrIn,
ExpectedNameOrVarArg,
UnexpectedSymbol,
SyntaxError,
ExpectedDifferentToken, // error_expected in lparser.c
TooManyLocalVariables,
NoLoopToBreak,
TooManySyntaxLevels,
AmbiguousSyntax,
VarArgOutsideVarArgFunction,
};
/// error -> msg lookup for parse errors
pub const parse_error_strings = AutoComptimeLookup(ParseError, []const u8, .{
.{ ParseError.FunctionArgumentsExpected, "function arguments expected" },
.{ ParseError.ExpectedEqualsOrIn, "'=' or 'in' expected" },
.{ ParseError.ExpectedNameOrVarArg, "<name> or '...' expected" },
.{ ParseError.UnexpectedSymbol, "unexpected symbol" },
.{ ParseError.SyntaxError, "syntax error" },
//.{ ParseError.ExpectedDifferentToken, ... }, this is context-specific
.{ ParseError.TooManyLocalVariables, "too many local variables" },
.{ ParseError.NoLoopToBreak, "no loop to break" },
.{ ParseError.TooManySyntaxLevels, "chunk has too many syntax levels" },
.{ ParseError.AmbiguousSyntax, "ambiguous syntax (function call x new statement)" },
.{ ParseError.VarArgOutsideVarArgFunction, "cannot use '...' outside a vararg function" },
});
// TODO this is duplcated from lex.zig, should be combined in the future
pub const ParseErrorContext = struct {
token: Token,
expected: ?Token = null,
expected_match: ?Token = null,
// TODO this is kinda weird, doesn't seem like it needs to be stored (maybe passed to render instead?)
err: ParseError,
pub fn renderAlloc(self: *ParseErrorContext, allocator: Allocator, parser: *Parser) ![]const u8 {
var buffer = std.ArrayList(u8).init(allocator);
errdefer buffer.deinit();
var msg_buf: [256]u8 = undefined;
const msg = msg: {
if (self.err == ParseError.ExpectedDifferentToken) {
var msg_fbs = std.io.fixedBufferStream(&msg_buf);
const msg_writer = msg_fbs.writer();
msg_writer.print("'{s}' expected", .{self.expected.?.nameForDisplay()}) catch unreachable;
if (self.expected_match != null and self.expected_match.?.line_number != self.token.line_number) {
msg_writer.print(" (to close '{s}' at line {d})", .{
self.expected_match.?.nameForDisplay(),
self.expected_match.?.line_number,
}) catch unreachable;
}
break :msg msg_fbs.getWritten();
} else {
break :msg parse_error_strings.get(self.err).?;
}
};
const error_writer = buffer.writer();
const MAXSRC = 80; // see MAXSRC in llex.c
var chunk_id_buf: [MAXSRC]u8 = undefined;
const chunk_id = zua.object.getChunkId(parser.lexer.chunk_name, &chunk_id_buf);
try error_writer.print("{s}:{d}: {s}", .{ chunk_id, self.token.line_number, msg });
// special case for 1:1 compatibility with Lua's errors
if (!self.token.isChar(0) and self.err != ParseError.TooManySyntaxLevels) {
try error_writer.print(" near '{s}'", .{self.token.nameForErrorDisplay(parser.lexer.buffer)});
}
return buffer.toOwnedSlice();
}
};
pub const Parser = struct {
const Self = @This();
lexer: *Lexer,
error_context: ?ParseErrorContext = null,
/// values that need to be initialized per-parse
state: Parser.State = undefined,
pub const Error = ParseError || Lexer.Error || Allocator.Error;
pub fn init(lexer: *Lexer) Parser {
return Parser{
.lexer = lexer,
};
}
pub const State = struct {
token: Token,
allocator: Allocator,
arena: Allocator,
in_loop: bool = false,
in_vararg_func: bool = true, // main chunk is always vararg
syntax_level: usize = 0,
};
pub fn parse(self: *Self, allocator: Allocator) Error!*Tree {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
self.state = Parser.State{
.token = try self.lexer.next(),
.allocator = allocator,
.arena = arena.allocator(),
};
const parsed_chunk = try self.chunk();
const tree = try self.state.arena.create(Tree);
tree.* = .{
.node = parsed_chunk,
.source = self.lexer.buffer,
.arena = arena.state,
.allocator = allocator,
};
return tree;
}
pub const PossibleLValueExpression = struct {
node: *Node,
can_be_assigned_to: bool = true,
};
/// chunk -> { stat [`;'] }
fn chunk(self: *Self) Error!*Node {
var statements = std.ArrayList(*Node).init(self.state.allocator);
defer statements.deinit();
try self.block(&statements);
try self.check(.eof);
const node = try self.state.arena.create(Node.Chunk);
node.* = .{
.body = try self.state.arena.dupe(*Node, statements.items),
};
return &node.base;
}
fn statement(self: *Self) Error!*Node {
switch (self.state.token.id) {
.keyword_if => return self.ifstat(),
.keyword_local => {
try self.nextToken();
const possible_function_token = self.state.token;
if (try self.testnext(.keyword_function)) {
return self.localfunc(possible_function_token);
} else {
return self.localstat();
}
},
.keyword_return => return self.retstat(),
.keyword_while => return self.whilestat(),
.keyword_do => return self.dostat(),
.keyword_repeat => return self.repeatstat(),
.keyword_break => return self.breakstat(),
.keyword_for => return self.forstat(),
.keyword_function => return self.funcstat(),
else => return self.exprstat(),
}
}
fn block(self: *Self, list: *std.ArrayList(*Node)) Error!void {
try self.enterlevel();
while (!blockFollow(self.state.token)) {
const stat = try self.statement();
try list.append(stat);
_ = try self.testcharnext(';');
const must_be_last_statement = stat.id == .return_statement or stat.id == .break_statement;
if (must_be_last_statement) {
break;
}
}
self.leavelevel();
}
/// parlist -> [ param { `,' param } ]
/// Returns true if vararg was found in the parameter list
fn parlist(self: *Self, list: *std.ArrayList(Token)) Error!bool {
// no params
if (self.state.token.isChar(')')) return false;
var found_vararg = false;
while (true) {
switch (self.state.token.id) {
.name => {},
.ellipsis => {
found_vararg = true;
},
else => return self.reportParseError(ParseError.ExpectedNameOrVarArg),
}
try list.append(self.state.token);
try self.nextToken();
if (found_vararg or !try self.testcharnext(',')) {
break;
}
}
return found_vararg;
}
/// body -> `(' parlist `)' chunk END
fn funcbody(self: *Self, function_token: Token, name: ?*Node, is_local: bool) Error!*Node {
try self.checkcharnext('(');
var params = std.ArrayList(Token).init(self.state.allocator);
defer params.deinit();
const vararg_found = try self.parlist(¶ms);
try self.checkcharnext(')');
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_vararg_func_prev = self.state.in_vararg_func;
self.state.in_vararg_func = vararg_found;
try self.block(&body);
self.state.in_vararg_func = in_vararg_func_prev;
try self.check_match(.keyword_end, function_token);
const node = try self.state.arena.create(Node.FunctionDeclaration);
node.* = .{
.name = name,
.parameters = try self.state.arena.dupe(Token, params.items),
.body = try self.state.arena.dupe(*Node, body.items),
.is_local = is_local,
};
return &node.base;
}
// funcstat -> FUNCTION funcname body
fn funcstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_function);
const function_token = self.state.token;
try self.nextToken();
const name = try self.funcname();
return self.funcbody(function_token, name, false);
}
// funcname -> NAME {field} [`:' NAME]
fn funcname(self: *Self) Error!*Node {
const name_token = try self.checkname();
var identifier_node = try self.state.arena.create(Node.Identifier);
identifier_node.* = .{
.token = name_token,
};
var node = &identifier_node.base;
while (self.state.token.isChar('.')) {
const separator = self.state.token;
try self.nextToken(); // skip separator
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = node,
.field = field_token,
.separator = separator,
};
node = &new_node.base;
}
if (self.state.token.isChar(':')) {
const separator = self.state.token;
try self.nextToken();
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = node,
.field = field_token,
.separator = separator,
};
node = &new_node.base;
}
return node;
}
/// stat -> RETURN explist
fn retstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_return);
try self.nextToken();
var return_values = std.ArrayList(*Node).init(self.state.allocator);
defer return_values.deinit();
const no_return_values = blockFollow(self.state.token) or (self.state.token.isChar(';'));
if (!no_return_values) {
_ = try self.explist1(&return_values);
}
const node = try self.state.arena.create(Node.ReturnStatement);
node.* = .{
.values = try self.state.arena.dupe(*Node, return_values.items),
};
return &node.base;
}
/// cond -> exp
fn cond(self: *Self) Error!*Node {
return self.expr();
}
/// whilestat -> WHILE cond DO block END
fn whilestat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_while);
const while_token = self.state.token;
try self.nextToken();
const condition = try self.cond();
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
try self.check_match(.keyword_end, while_token);
var while_statement = try self.state.arena.create(Node.WhileStatement);
while_statement.* = .{
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &while_statement.base;
}
fn breakstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_break);
const break_token = self.state.token;
try self.nextToken();
if (!self.state.in_loop) {
return self.reportParseError(ParseError.NoLoopToBreak);
}
var break_statement = try self.state.arena.create(Node.BreakStatement);
break_statement.* = .{
.token = break_token,
};
return &break_statement.base;
}
fn dostat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_do);
const do_token = self.state.token;
try self.nextToken();
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
try self.block(&body);
try self.check_match(.keyword_end, do_token);
const node = try self.state.arena.create(Node.DoStatement);
node.* = .{
.body = try self.state.arena.dupe(*Node, body.items),
};
return &node.base;
}
/// repeatstat -> REPEAT block UNTIL cond
fn repeatstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_repeat);
const repeat_token = self.state.token;
try self.nextToken();
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
try self.check_match(.keyword_until, repeat_token);
const condition = try self.cond();
const node = try self.state.arena.create(Node.RepeatStatement);
node.* = .{
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &node.base;
}
/// forstat -> FOR (fornum | forlist) END
fn forstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_for);
const for_token = self.state.token;
try self.nextToken();
const name_token = try self.checkname();
var for_node: *Node = undefined;
switch (self.state.token.id) {
.single_char => switch (self.state.token.char.?) {
'=' => for_node = try self.fornum(name_token),
',' => for_node = try self.forlist(name_token),
else => return self.reportParseError(ParseError.ExpectedEqualsOrIn),
},
.keyword_in => for_node = try self.forlist(name_token),
else => return self.reportParseError(ParseError.ExpectedEqualsOrIn),
}
try self.check_match(.keyword_end, for_token);
return for_node;
}
/// fornum -> NAME = exp1,exp1[,exp1] forbody
fn fornum(self: *Self, name_token: Token) Error!*Node {
try self.checkcharnext('=');
const start_expression = try self.expr();
try self.checkcharnext(',');
const end_expression = try self.expr();
var increment_expression: ?*Node = null;
if (try self.testcharnext(',')) {
increment_expression = try self.expr();
}
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
var for_node = try self.state.arena.create(Node.ForStatementNumeric);
for_node.* = .{
.name = name_token,
.start = start_expression,
.end = end_expression,
.increment = increment_expression,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &for_node.base;
}
/// forlist -> NAME {,NAME} IN explist1 forbody
fn forlist(self: *Self, first_name_token: Token) Error!*Node {
var names = try std.ArrayList(Token).initCapacity(self.state.allocator, 1);
defer names.deinit();
names.appendAssumeCapacity(first_name_token);
while (try self.testcharnext(',')) {
const name_token = try self.checkname();
try names.append(name_token);
}
try self.checknext(.keyword_in);
var expressions = std.ArrayList(*Node).init(self.state.allocator);
defer expressions.deinit();
_ = try self.explist1(&expressions);
try self.checknext(.keyword_do);
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
const in_loop_prev = self.state.in_loop;
self.state.in_loop = true;
try self.block(&body);
self.state.in_loop = in_loop_prev;
var for_node = try self.state.arena.create(Node.ForStatementGeneric);
for_node.* = .{
.names = try self.state.arena.dupe(Token, names.items),
.expressions = try self.state.arena.dupe(*Node, expressions.items),
.body = try self.state.arena.dupe(*Node, body.items),
};
return &for_node.base;
}
/// sort of the equivalent of Lua's test_then_block in lparser.c but handles else too
fn ifclause(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_if or self.state.token.id == .keyword_elseif or self.state.token.id == .keyword_else);
const if_token = self.state.token;
var condition: ?*Node = null;
try self.nextToken();
switch (if_token.id) {
.keyword_if, .keyword_elseif => {
condition = try self.cond();
try self.checknext(.keyword_then);
},
.keyword_else => {},
else => unreachable,
}
var body = std.ArrayList(*Node).init(self.state.allocator);
defer body.deinit();
try self.block(&body);
var if_clause = try self.state.arena.create(Node.IfClause);
if_clause.* = .{
.if_token = if_token,
.condition = condition,
.body = try self.state.arena.dupe(*Node, body.items),
};
return &if_clause.base;
}
/// ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END
fn ifstat(self: *Self) Error!*Node {
std.debug.assert(self.state.token.id == .keyword_if);
const if_token = self.state.token;
var clauses = std.ArrayList(*Node).init(self.state.allocator);
defer clauses.deinit();
// if
const if_clause = try self.ifclause();
try clauses.append(if_clause);
// elseif
while (self.state.token.id == .keyword_elseif) {
const elseif_clause = try self.ifclause();
try clauses.append(elseif_clause);
}
// else
if (self.state.token.id == .keyword_else) {
const else_clause = try self.ifclause();
try clauses.append(else_clause);
}
try self.check_match(.keyword_end, if_token);
var if_statement = try self.state.arena.create(Node.IfStatement);
if_statement.* = .{
.clauses = try self.state.arena.dupe(*Node, clauses.items),
};
return &if_statement.base;
}
fn localfunc(self: *Self, function_token: Token) Error!*Node {
const name_token = try self.checkname();
var name = try self.state.arena.create(Node.Identifier);
name.* = .{ .token = name_token };
return self.funcbody(function_token, &name.base, true);
}
/// listfield -> expr
fn listfield(self: *Self) Error!*Node {
const value = try self.expr();
var node = try self.state.arena.create(Node.TableField);
node.* = .{
.key = null,
.value = value,
};
return &node.base;
}
/// recfield -> (NAME | `['exp1`]') = exp1
fn recfield(self: *Self) Error!*Node {
const key: *Node = get_key: {
if (self.state.token.id == .name) {
const name_token = try self.checkname();
// This might be kinda weird, but the name token here is actually used as
// more of a string literal, so create a Literal node instead of Identifier.
// This is a special case.
// TODO revisit this?
var name_node = try self.state.arena.create(Node.Literal);
name_node.* = .{ .token = name_token };
break :get_key &name_node.base;
} else {
std.debug.assert(self.state.token.isChar('['));
try self.nextToken(); // skip the [
const key_expr = try self.expr();
try self.checkcharnext(']');
break :get_key key_expr;
}
};
try self.checkcharnext('=');
const value = try self.expr();
var node = try self.state.arena.create(Node.TableField);
node.* = .{
.key = key,
.value = value,
};
return &node.base;
}
/// constructor -> ??
fn constructor(self: *Self) Error!*Node {
const open_brace_token = self.state.token;
try self.checkcharnext('{');
var fields = std.ArrayList(*Node).init(self.state.allocator);
defer fields.deinit();
while (!self.state.token.isChar('}')) {
const field: *Node = get_field: {
switch (self.state.token.id) {
.name => {
// TODO presumably should catch EOF or errors here and translate them to more appropriate errors
const lookahead_token = self.lexer.lookahead() catch {
break :get_field try self.listfield();
};
if (lookahead_token.isChar('=')) {
break :get_field try self.recfield();
} else {
break :get_field try self.listfield();
}
},
.single_char => switch (self.state.token.char.?) {
'[' => break :get_field try self.recfield(),
else => break :get_field try self.listfield(),
},
else => break :get_field try self.listfield(),
}
};
try fields.append(field);
const has_more = (try self.testcharnext(',')) or (try self.testcharnext(';'));
if (!has_more) break;
}
const close_brace_token = self.state.token;
try self.checkchar_match('}', open_brace_token);
var node = try self.state.arena.create(Node.TableConstructor);
node.* = .{
.fields = try self.state.arena.dupe(*Node, fields.items),
.open_token = open_brace_token,
.close_token = close_brace_token,
};
return &node.base;
}
/// stat -> LOCAL NAME {`,' NAME} [`=' explist1]
fn localstat(self: *Self) Error!*Node {
return try self.assignment(null);
}
/// if first_variable is null, then this is a local assignment
fn assignment(self: *Self, first_variable: ?PossibleLValueExpression) Error!*Node {
const is_local = first_variable == null;
var variables = std.ArrayList(*Node).init(self.state.allocator);
defer variables.deinit();
var values = std.ArrayList(*Node).init(self.state.allocator);
defer values.deinit();
if (is_local) {
while (true) {
const name_token = try self.checkname();
var identifier = try self.state.arena.create(Node.Identifier);
identifier.* = .{ .token = name_token };
try variables.append(&identifier.base);
// TODO this needs work, it doesn't really belong here.
// We need to keep track of *all* local vars in order to function
// like the Lua parser (even local var literals like `self`).
// Might need to be checked at compile-time rather than parse-time.
if (variables.items.len > max_local_vars) {
return self.reportParseError(ParseError.TooManyLocalVariables);
}
if (!try self.testcharnext(',')) break;
}
if (try self.testcharnext('=')) {
_ = try self.explist1(&values);
}
} else {
var variable = first_variable.?;
while (true) {
if (!variable.can_be_assigned_to) {
return self.reportParseError(ParseError.SyntaxError);
}
try variables.append(variable.node);
if (try self.testcharnext(',')) {
variable = try self.primaryexp();
} else {
break;
}
}
try self.checkcharnext('=');
_ = try self.explist1(&values);
}
var local = try self.state.arena.create(Node.AssignmentStatement);
local.* = .{
.variables = try self.state.arena.dupe(*Node, variables.items),
.values = try self.state.arena.dupe(*Node, values.items),
.is_local = is_local,
};
return &local.base;
}
/// stat -> func | assignment
fn exprstat(self: *Self) Error!*Node {
var expression = try self.primaryexp();
if (expression.node.id == .call) {
const call_node = @fieldParentPtr(Node.Call, "base", expression.node);
call_node.is_statement = true;
} else {
// if it's not a call, then it's an assignment
expression.node = try self.assignment(expression);
}
return expression.node;
}
fn explist1(self: *Self, list: *std.ArrayList(*Node)) Error!usize {
const num_expressions: usize = 1;
try list.append(try self.expr());
while (try self.testcharnext(',')) {
try list.append(try self.expr());
}
return num_expressions;
}
/// simpleexp -> NUMBER | STRING | NIL | true | false | ... |
/// constructor | FUNCTION body | primaryexp
fn simpleexp(self: *Self) Error!*Node {
switch (self.state.token.id) {
.string, .number, .keyword_false, .keyword_true, .keyword_nil, .ellipsis => {
if (self.state.token.id == .ellipsis and !self.state.in_vararg_func) {
return self.reportParseError(ParseError.VarArgOutsideVarArgFunction);
}
const node = try self.state.arena.create(Node.Literal);
node.* = .{
.token = self.state.token,
};
try self.nextToken();
return &node.base;
},
.single_char => {
switch (self.state.token.char.?) {
'{' => return self.constructor(),
else => {},
}
},
.keyword_function => {
const function_token = self.state.token;
try self.nextToken(); // skip function
return self.funcbody(function_token, null, false);
},
else => {},
}
const expression = try self.primaryexp();
return expression.node;
}
pub const SubExpr = struct {
node: *Node,
untreated_operator: ?Token,
};
/// subexpr -> (simpleexp | unop subexpr) { binop subexpr }
/// where `binop' is any binary operator with a priority higher than `limit'
fn subexpr(self: *Self, limit: usize) Error!SubExpr {
try self.enterlevel();
var node: *Node = get_node: {
if (isUnaryOperator(self.state.token)) {
const unary_token = self.state.token;
try self.nextToken();
const argument_expr = try self.subexpr(unary_priority);
const unary_node = try self.state.arena.create(Node.UnaryExpression);
unary_node.* = .{
.operator = unary_token,
.argument = argument_expr.node,
};
break :get_node &unary_node.base;
} else {
break :get_node try self.simpleexp();
}
};
var op: ?Token = self.state.token;
while (op != null and isBinaryOperator(op.?)) {
const binary_token = op.?;
const priority = getBinaryPriority(binary_token);
if (priority.left <= limit) break;
try self.nextToken();
const right_expr = try self.subexpr(priority.right);
const new_node = try self.state.arena.create(Node.BinaryExpression);
new_node.* = .{
.operator = binary_token,
.left = node,
.right = right_expr.node,
};
node = &new_node.base;
op = right_expr.untreated_operator;
} else {
op = null;
}
self.leavelevel();
return SubExpr{
.node = node,
.untreated_operator = op,
};
}
fn expr(self: *Self) Error!*Node {
return (try self.subexpr(0)).node;
}
fn primaryexp(self: *Self) Error!PossibleLValueExpression {
var arguments = std.ArrayList(*Node).init(self.state.allocator);
defer arguments.deinit();
var expression = try self.prefixexp();
loop: while (true) {
switch (self.state.token.id) {
.single_char => {
switch (self.state.token.char.?) {
'.' => {
const separator = self.state.token;
try self.nextToken(); // skip the dot
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = expression.node,
.field = field_token,
.separator = separator,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = true;
},
'[' => {
const open_token = self.state.token;
try self.nextToken(); // skip the [
const index = try self.expr();
const close_token = self.state.token;
try self.checkcharnext(']');
var new_node = try self.state.arena.create(Node.IndexAccess);
new_node.* = .{
.prefix = expression.node,
.index = index,
.open_token = open_token,
.close_token = close_token,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = true;
},
':' => {
const separator = self.state.token;
try self.nextToken(); // skip the :
const field_token = try self.checkname();
var new_node = try self.state.arena.create(Node.FieldAccess);
new_node.* = .{
.prefix = expression.node,
.field = field_token,
.separator = separator,
};
expression.node = &new_node.base;
expression.can_be_assigned_to = false;
expression.node = try self.funcargs(expression.node);
},
'(', '{' => {
expression.node = try self.funcargs(expression.node);
expression.can_be_assigned_to = false;
},
else => break :loop,
}
},
.string => {
expression.node = try self.funcargs(expression.node);
expression.can_be_assigned_to = false;
},
else => break :loop,
}
}
return expression;
}
fn funcargs(self: *Self, expression: *Node) Error!*Node {
var arguments = std.ArrayList(*Node).init(self.state.allocator);
defer arguments.deinit();
var open_args_token: ?Token = null;
var close_args_token: ?Token = null;
switch (self.state.token.id) {
.single_char => switch (self.state.token.char.?) {
'(' => {
open_args_token = self.state.token;
const last_token = expression.getLastToken();
if (last_token.line_number != open_args_token.?.line_number) {
return self.reportParseError(ParseError.AmbiguousSyntax);
}
try self.nextToken();
const has_no_arguments = self.state.token.isChar(')');
if (!has_no_arguments) {
_ = try self.explist1(&arguments);
}
close_args_token = self.state.token;
try self.checkchar_match(')', open_args_token.?);
},
'{' => {
const node = try self.constructor();
try arguments.append(node);
},
else => {
return self.reportParseError(ParseError.FunctionArgumentsExpected);
},
},
.string => {
const node = try self.state.arena.create(Node.Literal);
node.* = .{
.token = self.state.token,
};
try arguments.append(&node.base);
try self.nextToken();
},
else => return self.reportParseError(ParseError.FunctionArgumentsExpected),
}
var call = try self.state.arena.create(Node.Call);
call.* = .{
.expression = expression,
.arguments = try self.state.arena.dupe(*Node, arguments.items),
.open_args_token = open_args_token,
.close_args_token = close_args_token,
};
return &call.base;
}
fn prefixexp(self: *Self) Error!PossibleLValueExpression {
switch (self.state.token.id) {
.name => {
const node = try self.state.arena.create(Node.Identifier);
node.* = .{
.token = self.state.token,
};
try self.nextToken();
return PossibleLValueExpression{ .node = &node.base };
},
.single_char => switch (self.state.token.char.?) {
'(' => {
const open_paren_token = self.state.token;