This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.zig
4127 lines (3668 loc) · 127 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 Parser = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const Utf8EncodeError = error{
CodepointTooLarge,
Utf8CannotEncodeSurrogateHalf,
};
const Lexer = @import("lexer.zig");
const Location = @import("location.zig");
const Token = @import("token.zig");
const Keyword = Token.Keyword;
const ast = @import("ast.zig");
const Node = ast.Node;
const Visibiity = ast.Visibility;
const Error = error{SyntaxError} ||
error{ InvalidCharacter, Overflow } ||
Allocator.Error ||
Utf8EncodeError;
const Alias = ast.Alias;
const And = ast.And;
const Annotation = ast.Annotation;
const AnnotationDef = ast.AnnotationDef;
const Arg = ast.Arg;
const ArrayLiteral = ast.ArrayLiteral;
const Asm = ast.Asm;
const AsmOperand = ast.AsmOperand;
const Assign = ast.Assign;
const Block = ast.Block;
const BoolLiteral = ast.BoolLiteral;
const Break = ast.Break;
const CStructOrUnionDef = ast.CStructOrUnionDef;
const Call = ast.Call;
const Case = ast.Case;
const Cast = ast.Cast;
const CharLiteral = ast.CharLiteral;
const ClassDef = ast.ClassDef;
const ClassVar = ast.ClassVar;
const Def = ast.Def;
const DoubleSplat = ast.DoubleSplat;
const EnumDef = ast.EnumDef;
const ExceptionHandler = ast.ExceptionHandler;
const Expressions = ast.Expressions;
const Extend = ast.Extend;
const ExternalVar = ast.ExternalVar;
const FunDef = ast.FunDef;
const Generic = ast.Generic;
const Global = ast.Global;
const HashLiteral = ast.HashLiteral;
const If = ast.If;
const ImplicitObj = ast.ImplicitObj;
const Include = ast.Include;
const InstanceSizeOf = ast.InstanceSizeOf;
const InstanceVar = ast.InstanceVar;
const IsA = ast.IsA;
const LibDef = ast.LibDef;
const Macro = ast.Macro;
const MacroExpression = ast.MacroExpression;
const MacroFor = ast.MacroFor;
const MacroIf = ast.MacroIf;
const MacroLiteral = ast.MacroLiteral;
const MacroVar = ast.MacroVar;
const MacroVerbatim = ast.MacroVerbatim;
const MagicConstant = ast.MagicConstant;
const Metaclass = ast.Metaclass;
const ModuleDef = ast.ModuleDef;
const MultiAssign = ast.MultiAssign;
const NamedArgument = ast.NamedArgument;
const NamedTupleLiteral = ast.NamedTupleLiteral;
const Next = ast.Next;
const Nil = ast.Nil;
const NilableCast = ast.NilableCast;
const Nop = ast.Nop;
const Not = ast.Not;
const NumberLiteral = ast.NumberLiteral;
const OffsetOf = ast.OffsetOf;
const OpAssign = ast.OpAssign;
const Or = ast.Or;
const Out = ast.Out;
const Path = ast.Path;
const PointerOf = ast.PointerOf;
const ProcLiteral = ast.ProcLiteral;
const ProcNotation = ast.ProcNotation;
const ProcPointer = ast.ProcPointer;
const RangeLiteral = ast.RangeLiteral;
const ReadInstanceVar = ast.ReadInstanceVar;
const RegexLiteral = ast.RegexLiteral;
const Require = ast.Require;
const Rescue = ast.Rescue;
const RespondsTo = ast.RespondsTo;
const Return = ast.Return;
const Select = ast.Select;
const Self = ast.Self;
const SizeOf = ast.SizeOf;
const Splat = ast.Splat;
const StringInterpolation = ast.StringInterpolation;
const StringLiteral = ast.StringLiteral;
const SymbolLiteral = ast.SymbolLiteral;
const TupleLiteral = ast.TupleLiteral;
const TypeDeclaration = ast.TypeDeclaration;
const TypeDef = ast.TypeDef;
const TypeOf = ast.TypeOf;
const Underscore = ast.Underscore;
const UninitializedVar = ast.UninitializedVar;
const Union = ast.Union;
const Unless = ast.Unless;
const Until = ast.Until;
const Var = ast.Var;
const VisibilityModifier = ast.VisibilityModifier;
const When = ast.When;
const While = ast.While;
const Yield = ast.Yield;
const Unclosed = struct {
name: []const u8,
location: Location,
fn init(name: []const u8, location: Location) Unclosed {
return .{ .name = name, .location = location };
}
};
lexer: Lexer,
visibility: ?Visibiity = null,
block_arg_name: ?[]const u8 = null,
var_scopes: ArrayList(StringHashMap(void)),
unclosed_stack: ArrayList(Unclosed),
calls_super: bool = false,
calls_initialize: bool = false,
calls_previous_def: bool = false,
uses_block_arg: bool = false,
is_macro_def: bool = false,
assigns_special_var: bool = false,
def_nest: usize = 0,
fun_nest: usize = 0,
type_nest: usize = 0,
is_constant_assignment: bool = false,
call_args_start_locations: ArrayList(Location),
temp_arg_count: usize = 0,
in_macro_expression: bool = false,
stop_on_yield: usize = 0,
inside_c_struct: bool = false,
wants_doc: bool = false,
doc_enabeld: bool = false,
no_type_declaration: usize = 0,
inside_interpolation: bool = false,
stop_on_do: bool = false,
assigned_vars: StringHashMap(void),
fn new(string: []const u8) !Parser {
const allocator = std.heap.page_allocator; // TODO: use ArenaAllocator
return init(allocator, string);
}
pub fn init(allocator: Allocator, string: []const u8) !Parser {
var parser = Parser{
.lexer = Lexer.init(allocator, string),
.var_scopes = ArrayList(StringHashMap(void)).init(allocator),
.unclosed_stack = ArrayList(Unclosed).init(allocator),
.call_args_start_locations = ArrayList(Location).init(allocator),
.assigned_vars = StringHashMap(void).init(allocator),
};
try parser.pushIsolatedVarScope();
return parser;
}
pub fn parse(parser: *Parser) !Node {
const lexer = &parser.lexer;
try lexer.skipTokenAndStatementEnd();
const node = try parser.parseExpressions();
try parser.check(.eof);
return node;
}
// parse(mode: ParseMode)
pub fn parseExpressions(parser: *Parser) !Node {
const old_stop_on_do = parser.replaceStopOnDo(false);
defer parser.stop_on_do = old_stop_on_do;
return parser.parseExpressionsInternal();
}
pub fn parseExpressionsInternal(parser: *Parser) !Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
if (parser.atEndToken()) {
return Nop.node(allocator, .{});
}
const exp = try parser.parseMultiAssign();
lexer.slash_is_regex = true;
try lexer.skipStatementEnd();
if (parser.atEndToken()) {
return exp;
}
var exps = ArrayList(Node).init(allocator);
try exps.append(exp);
while (true) {
try exps.append(try parser.parseMultiAssign());
try lexer.skipStatementEnd();
if (parser.atEndToken()) break;
}
return Expressions.from(allocator, exps);
}
pub fn parseMultiAssign(parser: *Parser) !Node {
// TODO: implement
return parser.parseExpression();
}
// pub fn parseMultiAssign(parser: *Parser) !Node {
// const lexer = &parser.lexer;
// const allocator = lexer.allocator;
// const location = lexer.token.location();
//
// var lhs_splat_index: ?usize = null;
// if (lexer.token.type == .op_star) {
// lhs_splat_index = 0;
// try lexer.skipTokenAndSpace();
// }
//
// var last = try parser.parseExpression();
// try lexer.skipSpace();
//
// const last_is_target = isMultiAssignTarget(last);
//
// switch (lexer.token.type) {
// .op_comma => {
// _ = last_is_target;
// return error.Unimplemented;
// },
// .newline, .op_semicolon => {
// return error.Unimplemented;
// },
// else => {
// return error.Unimplemented;
// },
// }
//
// var exps = ArrayList(Node).init(allocator);
// try exps.append(last);
//
// var i: usize = 0;
// var possible_assign_index: ?usize = null;
//
// while (lexer.token.type == .op_comma) {
// return error.Unimplemented;
// }
//
// if (possible_assign_index == null and isMultiAssignMiddle(last)) {
// possible_assign_index = i;
// }
//
// if (possible_assign_index) |assign_index| {
// var targets = ArrayList(Node).initCapacity(allocator, assign_index);
// var target_index: usize = 0;
// while (target_index < assign_index) : (target_index += 1) {
// const exp = exps.items[target_index];
// targets.append(parser.multiassignLeftHand(exp));
// }
//
// var assign_exp = exps.items[assign_index];
// var values = ArrayList(Node).init(allocator);
//
// switch (assign_exp) {
// .assign => |assign| {
// targets.append(parser.multiassignLeftHand(assign.target));
// values.append(assign.value);
// },
// .call => |*call| {
// call.name = call.name[0 .. call.name.len - 1];
// targets.append(assign_exp);
// values.append(call.args.pop());
// },
// else => {
// return lexer.raise("BUG: multiassign index expression can only be Assign or Call");
// },
// }
//
// values.appendSlice(exps.items[assign_index + 1 ..]);
// if (values.items.len != 1) {
// if (lhs_splat_index) {
// if (targets.items.len - 1 > values.items.len) {
// return lexer.raiseLoc("Multiple assignment count mismatch", location);
// }
// } else {
// if (targets.items.len != values.items.len) {
// return lexer.raiseLoc("Multiple assignment count mismatch", location);
// }
// }
// }
//
// const multi = try MultiAssign.node(allocator, .{
// .targets = targets,
// .values = values,
// .location = location,
// });
// return error.Unimplemented;
// } else {
// return parser.unexpectedToken(.{});
// }
// }
// pub fn isMultiAssignTarget(exp: Node) bool {
// switch (exp) {
// .underscore, .@"var", .instance_var, .class_var, .global, .assign => {
// return true;
// },
// .call => |call| {
// if (call.has_parentheses) {
// return false;
// }
// return (call.args.items.len == 0 and call.named_args == null) or
// Lexer.isSetter(call.name) or
// std.mem.eql(u8, "[]", call.name) or
// std.mem.eql(u8, "[]=", call.name);
// },
// else => {
// return false;
// },
// }
// }
// pub fn isMultiAssignMiddle(exp: Node) bool {
// return switch (exp) {
// .assign => true,
// .call => |call| call.name[call.name.len - 1] == '=',
// else => false,
// };
// }
// pub fn multiassignLeftHand(parser: *Parser, exp: Node) Node {
// const lexer = &parser.lexer;
// const allocator = lexer.allocator;
// var lhs = exp;
// switch (exp) {
// .path => |path| {
// return lexer.raiseLoc("can't assign to constant in multiple assignment", path.location.?);
// },
// .call => |call| {
// if (call.obj == null and call.args.items.len == 0) {
// var v = try Var.node(allocator, .{
// .name = call.name,
// });
// v.copyLocation(lhs);
// lhs = v;
// }
// },
// }
// switch (lhs) {
// .@"var" => |v| {
// if (std.mem.eql(u8, v.name, "self")) {
// return lexer.raiseLoc("can't change the value of self", v.location.?);
// }
// parser.pushVar(v);
// },
// }
// return lhs;
// }
pub fn parseExpression(parser: *Parser) !Node {
// TODO: implement
return parser.parseOpAssign(.{});
}
// parseExpressionSuffix
// parseExpressionSuffix
pub fn parseOpAssignNoControl(parser: *Parser, options: anytype) !Node {
try parser.checkVoidExpressionKeyword();
return parser.parseOpAssign(options);
}
pub fn parseOpAssign(
parser: *Parser,
options: struct {
allow_ops: bool = true,
allow_suffix: bool = true,
},
) Error!Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
const doc = lexer.token.doc();
const location = lexer.token.location();
const start_token = lexer.token;
var atomic = try parser.parseQuestionColon();
var allow_ops = options.allow_ops;
while (true) {
const name_location = lexer.token.location();
switch (lexer.token.type) {
.space => {
try lexer.skipToken();
continue;
},
.ident => {
if (!options.allow_suffix)
return parser.unexpectedToken(.{});
break;
},
.op_eq => {
lexer.slash_is_regex = true;
if (atomic == .call and
std.mem.eql(u8, atomic.call.name, "[]"))
{
// TODO: implement
return parser.unexpectedToken(.{ .msg = "unimplemented" });
} else {
if (!canBeAssigned(atomic)) break;
if (atomic == .path and
(parser.insideDef() or
parser.insideFun() or
parser.is_constant_assignment))
{
return lexer.raise("dynamic constant assignment. Constants can only be declared at the top level or inside other types.");
}
if (atomic == .path)
parser.is_constant_assignment = true;
if (atomic == .@"var" and
std.mem.eql(u8, atomic.@"var".name, "self"))
{
return lexer.raiseLoc(
"can't change the value of self",
location,
);
}
if (atomic == .call and
(std.mem.endsWith(u8, atomic.call.name, "?") or
std.mem.endsWith(u8, atomic.call.name, "!")))
{
return parser.unexpectedToken(.{ .token = start_token });
}
if (atomic == .call) {
const v = try Var.node(allocator, .{
.name = atomic.call.name,
});
v.copyLocation(atomic);
atomic = v;
}
try lexer.skipTokenAndSpaceOrNewline();
var needs_new_scope = false;
switch (atomic) {
.path => {
needs_new_scope = true;
},
.instance_var => {
needs_new_scope = parser.def_nest == 0;
},
.class_var => {
needs_new_scope = parser.def_nest == 0;
},
.@"var" => |v| {
if (v.isSpecialVar())
parser.assigns_special_var = true;
},
else => {
needs_new_scope = false;
},
}
const atomic_value = blk: {
if (needs_new_scope) try parser.pushIsolatedVarScope();
defer if (needs_new_scope) parser.popVarScope();
if (lexer.token.isKeyword(.uninitialized) and
(atomic == .@"var" or
atomic == .instance_var or
atomic == .class_var or
atomic == .global))
{
// TODO: implement
return parser.unexpectedToken(.{ .msg = "unimplemented" });
} else {
if (atomic == .@"var" and
!parser.isVar(atomic.@"var".name))
{
const name = atomic.@"var".name;
const already_assigned = parser.assigned_vars.contains(name);
if (!already_assigned)
try parser.assigned_vars.put(name, {});
defer {
if (!already_assigned)
_ = parser.assigned_vars.remove(name);
}
break :blk try parser.parseOpAssignNoControl(.{});
} else {
break :blk try parser.parseOpAssignNoControl(.{});
}
}
};
if (atomic == .path)
parser.is_constant_assignment = false;
try parser.pushVar(atomic);
return Assign.node(allocator, .{
.target = atomic,
.value = atomic_value,
.location = location,
.doc = doc,
});
}
},
else => |token_type| {
if (token_type.isAssignmentOperator()) {
// TODO: implement
_ = name_location;
return parser.unexpectedToken(.{ .msg = "unimplemented" });
} else {
break;
}
},
}
allow_ops = true;
}
return atomic;
}
pub fn parseQuestionColon(parser: *Parser) !Node {
// TODO: implement
return parser.parseRange();
}
pub fn parseRange(parser: *Parser) !Node {
// TODO: implement
return parser.parseOr();
}
// newRange
inline fn parseOperator(
parser: *Parser,
comptime options: struct {
node_type: type,
operators: []const Token.Kind,
next_operator: []const u8,
right_associative: ?[]const u8 = null,
},
) !Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
const location = lexer.token.location();
const parseLeft = @field(Parser, options.next_operator);
const parseRight = @field(
Parser,
options.right_associative orelse options.next_operator,
);
var left = try parseLeft(parser);
next_exp: while (true) {
if (lexer.token.type == .space) {
try lexer.skipToken();
continue;
}
inline for (options.operators) |op| {
if (lexer.token.type == op) {
try parser.checkVoidValue(left, location);
const method = op.toString();
const name_location = lexer.token.location();
lexer.slash_is_regex = true;
try lexer.skipTokenAndSpaceOrNewline();
const right = try parseRight(parser);
if (options.node_type == Call) {
var args = ArrayList(Node).init(allocator);
try args.append(right);
left = try Call.node(allocator, .{
.obj = left,
.name = method,
.args = args,
.name_location = name_location,
});
} else {
left = try options.node_type.node(allocator, .{
.left = left,
.right = right,
});
}
left.setLocation(location);
left.copyEndLocation(right);
continue :next_exp;
}
}
return left;
}
}
pub fn parseOr(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseAnd",
.node_type = Or,
.operators = &.{.op_bar_bar},
});
}
pub fn parseAnd(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseEquality",
.node_type = And,
.operators = &.{.op_amp_amp},
});
}
pub fn parseEquality(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseCmp",
.node_type = Call,
.operators = &.{ .op_lt, .op_lt_eq, .op_gt, .op_gt_eq, .op_lt_eq_gt },
});
}
pub fn parseCmp(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseLogicalOr",
.node_type = Call,
.operators = &.{ .op_eq_eq, .op_bang_eq, .op_eq_tilde, .op_bang_tilde, .op_eq_eq_eq },
});
}
pub fn parseLogicalOr(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseLogicalAnd",
.node_type = Call,
.operators = &.{ .op_bar, .op_caret },
});
}
pub fn parseLogicalAnd(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseShift",
.node_type = Call,
.operators = &.{.op_amp},
});
}
pub fn parseShift(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parseAddOrSub",
.node_type = Call,
.operators = &.{ .op_lt_lt, .op_gt_gt },
});
}
pub fn parseAddOrSub(parser: *Parser) !Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
const location = lexer.token.location();
var left = try parser.parseMulOrDiv();
while (true) {
switch (lexer.token.type) {
.space => {
try lexer.skipToken();
},
.op_plus, .op_minus, .op_amp_plus, .op_amp_minus => |op| {
try parser.checkVoidValue(left, location);
const method = op.toString();
const name_location = lexer.token.location();
// TODO: slash is never regex?
try lexer.skipTokenAndSpaceOrNewline();
const right = try parser.parseMulOrDiv();
var args = ArrayList(Node).init(allocator);
try args.append(right);
left = try Call.node(allocator, .{
.obj = left,
.name = method,
.args = args,
.location = location,
.end_location = right.endLocation(),
.name_location = name_location,
});
},
.number => {
switch (lexer.token.value.string[0]) {
'+', '-' => {
const method = lexer.token.value.string[0..1];
const name_location = lexer.token.location();
// Go back to the +/-, advance one char and continue from there
lexer.current_pos = lexer.token.start + 1;
try lexer.skipToken();
const right = try parser.parseMulOrDiv();
var args = ArrayList(Node).init(allocator);
try args.append(right);
left = try Call.node(allocator, .{
.obj = left,
.name = method,
.args = args,
.location = location,
.end_location = right.endLocation(),
.name_location = name_location,
});
},
else => {
return left;
},
}
},
else => {
return left;
},
}
}
}
pub fn parseMulOrDiv(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parsePow",
.node_type = Call,
.operators = &.{ .op_star, .op_slash, .op_slash_slash, .op_percent, .op_amp_star },
});
}
pub fn parsePow(parser: *Parser) !Node {
return parser.parseOperator(.{
.next_operator = "parsePrefix",
.node_type = Call,
.operators = &.{ .op_star_star, .op_amp_star_star },
.right_associative = "parsePow",
});
}
pub fn parsePrefix(parser: *Parser) !Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
// TODO: redundant variable?
const name_location = lexer.token.location();
switch (lexer.token.type) {
.op_bang, .op_plus, .op_minus, .op_tilde, .op_amp_plus, .op_amp_minus => |token_type| {
const location = lexer.token.location();
try lexer.skipTokenAndSpaceOrNewline();
try parser.checkVoidExpressionKeyword();
const obj = try parser.parsePrefix();
if (token_type == .op_bang) {
return Not.node(allocator, .{
.exp = obj,
.location = location,
.end_location = obj.endLocation(),
});
} else {
return Call.node(allocator, .{
.obj = obj,
.name = token_type.toString(),
.args = ArrayList(Node).init(allocator),
.location = location,
.end_location = obj.endLocation(),
.name_location = name_location,
});
}
},
else => {
return parser.parseAtomicWithMethod();
},
}
}
// AtomicWithMethodCheck
pub fn parseAtomicWithMethod(parser: *Parser) !Node {
// TODO: implement
return parser.parseAtomic();
}
// parseAtomicMethodSuffix
// parseAtomicMethodSuffixSpecial
// parseSingleArg
// parseIsA
// parseAs
// parseAsQuestion
// parseRespondsTo
pub fn parseRespondsToName(parser: *Parser) ![]const u8 {
const lexer = &parser.lexer;
if (lexer.token.type != .symbol) {
return parser.unexpectedToken(.{ .msg = "expected symbol" });
}
return lexer.token.value.string;
}
// parseNilQuestion
// parseNegationSuffix
pub fn parseAtomic(parser: *Parser) !Node {
const lexer = &parser.lexer;
const location = lexer.token.location();
const atomic = try parser.parseAtomicWithoutLocation();
if (atomic.location() == null)
atomic.setLocation(location);
return atomic;
}
pub fn parseAtomicWithoutLocation(parser: *Parser) !Node {
const lexer = &parser.lexer;
const allocator = lexer.allocator;
switch (lexer.token.type) {
.op_lparen => {
return parser.parseParenthesizedExpression();
},
.op_lsquare_rsquare => {
return parser.parseEmptyArrayLiteral();
},
.op_lsquare => {
return parser.parseArrayLiteral();
},
.op_lcurly => {
return parser.parseHashOrTupleLiteral(.{});
},
.op_lcurly_lcurly => {
// TODO: implement parsePercentMacroExpression
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.op_lcurly_percent => {
// TODO: implement parsePercentMacroControl
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.op_colon_colon => {
// TODO: implement parseGenericOrGlobalCall
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.op_minus_gt => {
// TODO: implement parseFunLiteral
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.op_at_lsquare => {
// TODO: implement parseAnnotation
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.number => {
lexer.wants_regex = false;
const node = try NumberLiteral.node(allocator, .{
.value = lexer.token.value.string,
.kind = lexer.token.number_kind,
});
try parser.skipNodeToken(node);
return node;
},
.char => {
const node = try CharLiteral.node(allocator, .{
.value = lexer.token.value.char,
});
try parser.skipNodeToken(node);
return node;
},
.string => {
// TODO: is it ever possible to have .string here?
unreachable;
},
.delimiter_start => {
return parser.parseDelimiter(.{});
},
.string_array_start => {
return parser.parseStringArray();
},
.symbol_array_start => {
return parser.parseSymbolArray();
},
.symbol => {
const node = try SymbolLiteral.node(allocator, .{
.value = lexer.token.value.string,
});
try parser.skipNodeToken(node);
return node;
},
.global => {
return lexer.raise("$global_variables are not supported, use @@class_variables instead");
},
.op_dollar_tilde, .op_dollar_question => |token_type| {
const location = lexer.token.location();
// TODO: backport to Crystal
const name = token_type.toString();
if (blk: {
lexer.startPeekAhead();
defer lexer.endPeekAhead();
try lexer.skipTokenAndSpace();
break :blk lexer.token.type == .op_eq;
}) {
const v = try Var.node(allocator, .{
.name = name,
.location = location,
});
try parser.pushVar(v);
try parser.skipNodeToken(v);
return v;
} else {
return Global.node(allocator, .{
.name = name,
.location = location,
});
}
},
.global_match_data_index => {
if (blk: {
lexer.startPeekAhead();
defer lexer.endPeekAhead();
try lexer.skipTokenAndSpace();
break :blk lexer.token.type == .op_eq;
}) {
return lexer.raise("global match data cannot be assigned to");
}
var method: []const u8 = "[]";
var value = lexer.token.value.string;
if (value[value.len - 1] == '?') {
method = "[]?";
value = value[0 .. value.len - 1];
}
const location = lexer.token.location();
// TODO: slightly inefficient
const index = std.fmt.parseInt(i32, value, 10) catch |err| {
switch (err) {
error.Overflow => {
return lexer.raise(try std.fmt.allocPrint(
allocator,
"Index ${s} doesn't fit in an Int32",
.{value},
));
},
error.InvalidCharacter => return err,
}
};
var args = ArrayList(Node).init(allocator);
try args.append(try NumberLiteral.fromNumber(allocator, index));
const node = try Call.node(allocator, .{
.obj = try Global.node(allocator, .{
.name = "$~",
.location = location,
}),
.name = method,
.args = args,
});
try parser.skipNodeToken(node);
return node;
},
.magic_line => {
const node = try MagicConstant.expandLineNode(allocator, lexer.token.location());
try parser.skipNodeToken(node);
return node;
},
.magic_end_line => {
return lexer.raiseFor("__END_LINE__ can only be used in default parameter value", lexer.token);
},
.magic_file => {
// TODO: implement
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.magic_dir => {
// TODO: implement
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.ident => {
switch (lexer.token.value) {
.keyword => |keyword| {
switch (keyword) {
.begin => {
// TODO: implement parseBegin
return parser.unexpectedToken(.{ .msg = "unexpected" });
},
.nil => {
// TODO: implement