-
-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathParser.zig
More file actions
6216 lines (5856 loc) · 279 KB
/
Copy pathParser.zig
File metadata and controls
6216 lines (5856 loc) · 279 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Parser for converting tokenized Roc source code into an Abstract Syntax Tree.
//!
//! This module provides the Parser struct which takes a buffer of tokens and
//! transforms them into an AST representation. The parser handles syntax errors
//! gracefully by inserting malformed placeholders and continuing compilation,
//! following the "Inform Don't Block" philosophy.
const std = @import("std");
const Allocator = std.mem.Allocator;
const base = @import("base");
const tracy = @import("tracy");
const AST = @import("AST.zig");
const Node = @import("Node.zig");
const NodeStore = @import("NodeStore.zig");
const DeclIndex = @import("DeclIndex.zig");
const NumericLiteral = @import("NumericLiteral.zig");
const TokenizedBuffer = tokenize.TokenizedBuffer;
const Token = tokenize.Token;
const TokenIdx = Token.Idx;
const tokenize = @import("tokenize.zig");
const MAX_PARSE_DIAGNOSTICS: usize = 1_000;
/// A parser which tokenizes and parses source code into an abstract syntax tree.
pub const Parser = @This();
gpa: std.mem.Allocator,
pos: TokenIdx,
tok_buf: TokenizedBuffer,
store: NodeStore,
decl_index: DeclIndex,
scope_pending_annos: std.ArrayList(?DeclIndex.DeclIdx),
type_path_stack: std.ArrayList(DeclIndex.TypePathIdx),
type_path_stack_visible_start: usize,
collect_type_dependencies: bool,
scratch_idents: base.Scratch(base.Ident.Idx),
scratch_nodes: std.ArrayList(Node.Idx),
diagnostics: std.ArrayList(AST.Diagnostic),
cached_malformed_node: ?Node.Idx,
expr_kernel_scratch: ParserKernelScratch,
/// init the parser from a buffer of tokens
pub fn init(tokens: TokenizedBuffer, gpa: std.mem.Allocator) std.mem.Allocator.Error!Parser {
const estimated_node_count = tokens.tokens.len;
var store = try NodeStore.initCapacity(gpa, estimated_node_count);
errdefer store.deinit();
var scratch_idents = try base.Scratch(base.Ident.Idx).init(gpa);
errdefer scratch_idents.deinit();
return Parser{
.gpa = gpa,
.pos = 0,
.tok_buf = tokens,
.store = store,
.decl_index = DeclIndex.init(gpa),
.scope_pending_annos = .empty,
.type_path_stack = .empty,
.type_path_stack_visible_start = 0,
.collect_type_dependencies = false,
.scratch_idents = scratch_idents,
.scratch_nodes = .empty,
.diagnostics = .empty,
.cached_malformed_node = null,
.expr_kernel_scratch = .{},
};
}
/// Deinit the parser. The buffer of tokens and the store are still owned by the caller.
pub fn deinit(parser: *Parser) void {
parser.scratch_idents.deinit();
parser.scratch_nodes.deinit(parser.gpa);
parser.scope_pending_annos.deinit(parser.gpa);
parser.type_path_stack.deinit(parser.gpa);
parser.expr_kernel_scratch.deinit(parser.gpa);
// diagnostics will be kept and passed to the following compiler stage
// to be deinitialized by the caller when no longer required
}
/// helper to advance the parser by one token
pub fn advance(self: *Parser) void {
self.pos += 1;
// We have an EndOfFile token that we never expect to advance past
std.debug.assert(self.pos < self.tok_buf.tokens.len);
}
/// look ahead at the next token and return an error if it does not have the expected tag
pub fn expect(self: *Parser, expected: Token.Tag) error{ExpectedNotFound}!void {
if (self.peek() != expected) {
return error.ExpectedNotFound;
}
self.advance();
}
inline fn consumeComma(self: *Parser) bool {
if (self.peek() != .Comma) return false;
self.advance();
return true;
}
/// Peek at the token at the current position
///
/// **note** caller is responsible to ensure this isn't the last token
pub fn peek(self: *Parser) Token.Tag {
std.debug.assert(self.pos < self.tok_buf.tokens.len);
return self.tok_buf.tokens.items(.tag)[self.pos];
}
/// Peek at the next token
pub fn peekNext(self: *Parser) Token.Tag {
const next = self.pos + 1;
if (next >= self.tok_buf.tokens.len) {
return .EndOfFile;
}
return self.tok_buf.tokens.items(.tag)[next];
}
/// Peek at `n` tokens forward
pub fn peekN(self: *Parser, n: u32) Token.Tag {
if (n == 0) {
return self.peek();
}
const next = self.pos + n;
if (next >= self.tok_buf.tokens.len) {
return .EndOfFile;
}
return self.tok_buf.tokens.items(.tag)[next];
}
/// Check if the token at the given position is a var identifier (starts with '$')
fn isVarIdent(self: *Parser, token: Token.Idx) bool {
if (self.tok_buf.resolveIdentifier(token)) |ident| {
return ident.attributes.reassignable;
}
return false;
}
/// Check if the current position looks like a type declaration with a valid type following.
/// This peeks ahead without consuming tokens to determine if we have:
/// - `Name :` followed by a valid type start token
/// - `Name :=` followed by a valid type start token
/// - `Name ::` followed by a valid type start token
/// - `Name(a, b) :` etc. (with parenthesized type params)
///
/// The key insight is that after the `:` (or `:=` or `::`), we must see a token that
/// can start a type annotation. If we see a string literal or other expression token,
/// this is NOT a type declaration - it's likely a malformed expression.
fn looksLikeTypeDecl(self: *Parser) bool {
std.debug.assert(self.peek() == .UpperIdent);
var lookahead: u32 = 1;
const next_tok = self.peekN(lookahead);
// Check for parenthesized type params: Name(a, b) :
if (next_tok == .OpenRound or next_tok == .NoSpaceOpenRound) {
// Skip to matching close paren, counting nesting
lookahead += 1;
var depth: u32 = 1;
while (depth > 0) {
const tok = self.peekN(lookahead);
switch (tok) {
.OpenRound, .NoSpaceOpenRound => depth += 1,
.CloseRound => depth -= 1,
.EndOfFile => return false,
else => {},
}
lookahead += 1;
}
}
// Note: We do NOT support the old `Name a b :` syntax with space-separated type params.
// Only `Name(a, b) :` with parenthesized type params is supported.
// Now check for : or := or ::
const op_tok = self.peekN(lookahead);
if (op_tok != .OpColon and op_tok != .OpColonEqual and op_tok != .OpDoubleColon) {
return false;
}
lookahead += 1;
// Check if what follows is a valid type annotation start
const after_colon = self.peekN(lookahead);
return switch (after_colon) {
// Valid type annotation starts
.UpperIdent, // Type name: Str, List, etc.
.LowerIdent, // Type variable: a, b, etc.
.OpenRound, // Tuple or grouping: (a, b)
.NoSpaceOpenRound, // Tuple or grouping without space
.OpenSquare, // Tag union: [Ok(a), Err(e)]
.OpenCurly, // Record type: { name: Str }
.Underscore, // Wildcard type: _
.NamedUnderscore, // Named wildcard: _foo
=> true,
// NOT valid type starts - this is probably a malformed expression
else => false,
};
}
fn looksLikeAppliedTagDestructure(self: *Parser) bool {
std.debug.assert(self.peek() == .UpperIdent);
var lookahead: u32 = 1;
while (self.peekN(lookahead) == .NoSpaceDotUpperIdent) {
lookahead += 1;
}
if (self.peekN(lookahead) != .NoSpaceOpenRound) {
return false;
}
lookahead += 1;
var depth: u32 = 1;
var closing_tok = Token.Tag.EndOfFile;
while (depth > 0) {
const tok = self.peekN(lookahead);
switch (tok) {
.OpenRound, .NoSpaceOpenRound, .OpenSquare, .OpenCurly => depth += 1,
.CloseRound, .CloseSquare, .CloseCurly => {
closing_tok = tok;
depth -= 1;
},
.EndOfFile => return false,
else => {},
}
lookahead += 1;
}
if (closing_tok != .CloseRound) {
return false;
}
return self.peekN(lookahead) == .OpAssign;
}
/// The error set that methods of the Parser return
pub const Error = std.mem.Allocator.Error;
const ExprParentKind = enum(u16) {
statement_expr_body = 0x012d,
statement_decl_body = 0x7b91,
statement_var_body = 0x3e07,
statement_expect_body = 0xc5a3,
statement_for_expr = 0x56f9,
statement_for_body = 0x9a4b,
statement_while_cond = 0x21d6,
statement_while_body = 0xef35,
statement_crash_body = 0x6c82,
statement_dbg_body = 0xb04d,
statement_return_body = 0x18f7,
expr_unary = 0xd291,
expr_binary_rhs = 0x4b3c,
expr_collection_item = 0x8375,
expr_arrow_inner = 0x2edb,
expr_record_ext = 0xf61a,
expr_record_field = 0x705e,
expr_string = 0xad09,
expr_if = 0x39c4,
expr_if_then = 0xc817,
expr_if_else = 0x5a2e,
expr_match = 0x96d3,
expr_match_guard = 0x0f6b,
expr_match_body = 0xe148,
expr_dbg = 0x68b5,
expr_for_list = 0xb739,
expr_for_body = 0x247c,
expr_lambda_body = 0xdca0,
pattern_string = 0x43ef,
};
const PatternParentKind = enum(u16) {
statement_for_pattern = 0x19a4,
statement_destructure_pattern = 0xe03b,
expr_for_pattern = 0x4771,
expr_lambda_args = 0x8c26,
expr_match_pattern = 0x2fb8,
pattern_root = 0xb55d,
pattern_tag_args = 0x60e2,
pattern_list = 0xd914,
pattern_tuple = 0x0a7f,
pattern_record_field = 0x93c8,
};
const TypeParentKind = enum(u16) {
statement_type_after_anno = 0x34c9,
statement_type_decl_anno = 0xae12,
where_clause_type = 0x057d,
type_apply = 0xc6e0,
type_paren_item = 0x718b,
type_paren_fn_ret = 0x2d44,
type_zero_arg_fn_ret = 0xf93a,
type_record_ext = 0x8b07,
type_record_field = 0x105e,
type_tag_union_ext = 0xdb95,
type_tag_union_item = 0x4fa1,
type_fn_arg = 0x670c,
type_fn_ret = 0xb2f6,
};
const WhereParentKind = enum(u16) {
where_statement_type_anno = 0x3b6d,
where_statement_type_decl = 0xc028,
};
const StatementParentKind = enum(u16) {
statement_type_associated_statement = 0x72a9,
};
const AssociatedParentKind = enum(u16) {
statement_type_decl_associated = 0x4d31,
};
fn enterDeclScope(
self: *Parser,
kind: DeclIndex.ScopeKind,
owner: DeclIndex.ScopeOwner,
region: AST.TokenizedRegion,
) Error!DeclIndex.ScopeIdx {
const scope_idx = try self.decl_index.enterScope(kind, owner, .{
.start = region.start,
.end = region.end,
});
switch (kind) {
.associated => self.decl_index.setScopeOwnerTypePath(scope_idx, self.currentTypePath()),
else => {},
}
while (self.scope_pending_annos.items.len <= @intFromEnum(scope_idx)) {
try self.scope_pending_annos.append(self.gpa, null);
}
return scope_idx;
}
fn exitDeclScope(
self: *Parser,
scope_idx: DeclIndex.ScopeIdx,
region: AST.TokenizedRegion,
) Error!void {
self.scope_pending_annos.items[@intFromEnum(scope_idx)] = null;
try self.decl_index.exitScope(scope_idx, .{
.start = region.start,
.end = region.end,
});
}
fn currentPendingAnno(self: *Parser) ?*?DeclIndex.DeclIdx {
const scope_idx = self.decl_index.currentScope() orelse return null;
return &self.scope_pending_annos.items[@intFromEnum(scope_idx)];
}
fn currentTypePath(self: *const Parser) ?DeclIndex.TypePathIdx {
if (self.type_path_stack.items.len <= self.type_path_stack_visible_start) return null;
return self.type_path_stack.items[self.type_path_stack.items.len - 1];
}
fn currentAssociatedOwnerPath(self: *const Parser) ?DeclIndex.TypePathIdx {
const scope_idx = self.decl_index.currentScope() orelse return null;
const scope = self.decl_index.scopes.items[@intFromEnum(scope_idx)];
if (scope.kind != .associated) return null;
return scope.owner_type_path;
}
fn tokenIdentsEqual(self: *Parser, a: ?Token.Idx, b: ?Token.Idx) bool {
const a_tok = a orelse return false;
const b_tok = b orelse return false;
const a_ident = self.tok_buf.resolveIdentifier(a_tok) orelse return false;
const b_ident = self.tok_buf.resolveIdentifier(b_tok) orelse return false;
return a_ident.eql(b_ident);
}
fn recordStatementDecl(
self: *Parser,
statement_idx: AST.Statement.Idx,
statement: AST.Statement,
type_dependencies: DeclIndex.Span,
type_path: ?DeclIndex.TypePathIdx,
) Error!void {
const scope_idx = self.decl_index.currentScope() orelse return;
const owner_type_path = self.currentAssociatedOwnerPath();
var record = switch (statement) {
.decl => |decl| blk: {
const pattern = self.store.getPattern(decl.pattern);
const name_tok: ?Token.Idx = if (pattern == .ident)
pattern.ident.ident_tok
else
null;
const body = self.store.getExpr(decl.body);
const value_form: DeclIndex.ValueDeclForm, const value_arity: u32 = switch (body) {
.lambda => |lambda| .{
.lambda,
@intCast(self.store.patternSlice(lambda.args).len),
},
else => .{ .none, 0 },
};
break :blk DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = .value,
.value_form = value_form,
.value_arity = value_arity,
.name_tok = name_tok,
.owner_type_path = owner_type_path,
.pattern = @intFromEnum(decl.pattern),
.anno = null,
.region = .{ .start = decl.region.start, .end = decl.region.end },
};
},
.@"var" => |v| DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = .var_decl,
.name_tok = v.name,
.owner_type_path = owner_type_path,
.pattern = null,
.anno = null,
.region = .{ .start = v.region.start, .end = v.region.end },
},
.import => |i| blk: {
if (self.tok_buf.resolveIdentifier(i.module_name_tok)) |module_name| {
try self.decl_index.addImport(.{
.module_name = module_name,
.qualifier = if (i.qualifier_tok) |qualifier_tok| self.tok_buf.resolveIdentifier(qualifier_tok) else null,
.nested = i.nested_import,
.region = .{ .start = i.region.start, .end = i.region.end },
});
}
break :blk DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = .import,
.name_tok = i.alias_tok orelse i.module_name_tok,
.pattern = null,
.anno = null,
.region = .{ .start = i.region.start, .end = i.region.end },
};
},
.file_import => |fi| DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = .file_import,
.name_tok = fi.name_tok,
.pattern = null,
.anno = null,
.region = .{ .start = fi.region.start, .end = fi.region.end },
},
.type_decl => |td| blk: {
const header = self.store.getTypeHeader(td.header) catch break :blk null;
const kind: DeclIndex.DeclKind = switch (td.kind) {
.alias => .type_alias,
.nominal => .nominal,
.@"opaque" => .@"opaque",
};
break :blk DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = kind,
.name_tok = header.name,
.owner_type_path = owner_type_path,
.type_path = type_path,
.pattern = null,
.anno = @intFromEnum(td.anno),
.associated_scope = if (td.associated) |assoc| assoc.scope else null,
.type_dependencies = type_dependencies,
.region = .{ .start = td.region.start, .end = td.region.end },
};
},
.type_anno => |ta| DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = if (ta.is_var) .var_anno else .value_anno,
.name_tok = ta.name,
.owner_type_path = owner_type_path,
.pattern = null,
.anno = @intFromEnum(ta.anno),
.region = .{ .start = ta.region.start, .end = ta.region.end },
},
else => null,
} orelse {
if (self.currentPendingAnno()) |pending| pending.* = null;
return;
};
if (record.name_tok) |name_tok| {
record.name_ident = self.tok_buf.resolveIdentifier(name_tok);
}
const decl_idx = try self.decl_index.addDecl(record);
if (record.kind == .value_anno or record.kind == .var_anno) {
if (self.currentPendingAnno()) |pending| pending.* = decl_idx;
return;
}
if (record.kind == .value or record.kind == .var_decl) {
if (self.currentPendingAnno()) |pending| {
if (pending.*) |anno_idx| {
const anno = self.decl_index.decls.items[@intFromEnum(anno_idx)];
const kinds_match = (record.kind == .value and anno.kind == .value_anno) or
(record.kind == .var_decl and anno.kind == .var_anno);
if (kinds_match and self.tokenIdentsEqual(anno.name_tok, record.name_tok)) {
self.decl_index.pairAnnotation(anno_idx, decl_idx);
}
}
pending.* = null;
}
return;
}
if (self.currentPendingAnno()) |pending| pending.* = null;
}
fn addStatement(self: *Parser, statement: AST.Statement) Error!AST.Statement.Idx {
return try self.addStatementWithTypeDependencies(statement, DeclIndex.Span.empty());
}
inline fn addDeclStatement(
self: *Parser,
pattern: AST.Pattern.Idx,
body: AST.Expr.Idx,
region: AST.TokenizedRegion,
) Error!AST.Statement.Idx {
const idx = try self.store.addStatement(.{ .decl = .{
.pattern = pattern,
.body = body,
.region = region,
} });
try self.recordValueDecl(idx, pattern, body, region);
return idx;
}
fn recordValueDecl(
self: *Parser,
statement_idx: AST.Statement.Idx,
pattern_idx: AST.Pattern.Idx,
body_idx: AST.Expr.Idx,
region: AST.TokenizedRegion,
) Error!void {
const scope_idx = self.decl_index.currentScope() orelse return;
const owner_type_path = self.currentAssociatedOwnerPath();
const pattern = self.store.getPattern(pattern_idx);
const name_tok: ?Token.Idx = if (pattern == .ident)
pattern.ident.ident_tok
else
null;
const body = self.store.getExpr(body_idx);
const value_form: DeclIndex.ValueDeclForm, const value_arity: u32 = switch (body) {
.lambda => |lambda| .{
.lambda,
@intCast(self.store.patternSlice(lambda.args).len),
},
else => .{ .none, 0 },
};
var record = DeclIndex.Decl{
.scope = scope_idx,
.statement = @intFromEnum(statement_idx),
.kind = .value,
.value_form = value_form,
.value_arity = value_arity,
.name_tok = name_tok,
.owner_type_path = owner_type_path,
.pattern = @intFromEnum(pattern_idx),
.anno = null,
.region = .{ .start = region.start, .end = region.end },
};
if (record.name_tok) |tok| {
record.name_ident = self.tok_buf.resolveIdentifier(tok);
}
const decl_idx = try self.decl_index.addDecl(record);
if (self.currentPendingAnno()) |pending| {
if (pending.*) |anno_idx| {
const anno = self.decl_index.decls.items[@intFromEnum(anno_idx)];
if (anno.kind == .value_anno and self.tokenIdentsEqual(anno.name_tok, record.name_tok)) {
self.decl_index.pairAnnotation(anno_idx, decl_idx);
}
}
pending.* = null;
}
}
fn addStatementWithTypeDependencies(
self: *Parser,
statement: AST.Statement,
type_dependencies: DeclIndex.Span,
) Error!AST.Statement.Idx {
const idx = try self.store.addStatement(statement);
try self.recordStatementDecl(idx, statement, type_dependencies, null);
return idx;
}
fn addTypeDeclStatement(
self: *Parser,
statement: AST.Statement,
type_dependencies: DeclIndex.Span,
type_path: ?DeclIndex.TypePathIdx,
) Error!AST.Statement.Idx {
const idx = try self.store.addStatement(statement);
try self.recordStatementDecl(idx, statement, type_dependencies, type_path);
return idx;
}
fn tokenText(self: *const Parser, token: Token.Idx) []const u8 {
const region = self.tok_buf.resolve(token);
return self.tok_buf.env.source[region.start.offset..region.end.offset];
}
fn recordPackageHeaderModules(self: *Parser, exposes: AST.ExposedItem.Span) Error!void {
for (self.store.exposedItemSlice(exposes)) |exposed_idx| {
const exposed = self.store.getExposedItem(exposed_idx);
const name_token: Token.Idx, const region: AST.TokenizedRegion = switch (exposed) {
.upper_ident => |ui| .{ ui.ident, ui.region },
.upper_ident_star => |ui| .{ ui.ident, ui.region },
.lower_ident, .malformed => continue,
};
const module_name = self.tok_buf.resolveIdentifier(name_token) orelse continue;
try self.decl_index.addPackageHeaderModule(module_name, .{
.start = region.start,
.end = region.end,
});
}
}
fn typeIdentFromDeprecatedSuffix(self: *Parser, suffix: NumericLiteral.DeprecatedSuffix) Error!?base.Ident.Idx {
const type_name = suffix.newTypeName() orelse return null;
return try self.tok_buf.env.insertIdent(self.gpa, base.Ident.for_text(type_name));
}
fn pushDeprecatedNumberSuffixDiagnostic(self: *Parser, suffix: NumericLiteral.DeprecatedSuffix, region: AST.TokenizedRegion) Error!void {
if (suffix != .none) {
try self.pushDiagnostic(.deprecated_number_suffix, region);
}
}
/// add a diagnostic error
pub fn pushDiagnostic(self: *Parser, tag: AST.Diagnostic.Tag, region: AST.TokenizedRegion) Error!void {
if (self.diagnostics.items.len < MAX_PARSE_DIAGNOSTICS) {
try self.diagnostics.append(self.gpa, .{ .tag = tag, .region = region });
}
}
/// add a malformed token
pub fn pushMalformed(self: *Parser, comptime T: type, tag: AST.Diagnostic.Tag, start: TokenIdx) Error!T {
const pos = self.pos;
if (self.peek() != .EndOfFile) {
self.advance(); // TODO: find a better point to advance to
}
if (self.diagnostics.items.len < MAX_PARSE_DIAGNOSTICS) {
// Create a diagnostic region that points to the problematic token
// If the parser has moved too far from the start, use the start token for better error location
const diagnostic_start = if (self.pos > start and (self.pos - start) > 2) start else @min(pos, self.pos);
const diagnostic_end = if (self.pos > start and (self.pos - start) > 2) start + 1 else @max(pos, self.pos);
// If start equals end, make it a single-token region
const diagnostic_region = AST.TokenizedRegion{
.start = diagnostic_start,
.end = if (diagnostic_start == diagnostic_end) diagnostic_start + 1 else diagnostic_end,
};
// AST node should span the entire malformed expression
const ast_region = AST.TokenizedRegion{ .start = start, .end = self.pos };
try self.diagnostics.append(self.gpa, .{
.tag = tag,
.region = diagnostic_region,
});
return try self.store.addMalformed(T, tag, ast_region);
} else {
// Return a cached malformed node to avoid creating excessive nodes after the diagnostic limit.
if (self.cached_malformed_node == null) {
const malformed_region = AST.TokenizedRegion{ .start = start, .end = self.pos };
const nid = try self.store.nodes.append(self.gpa, .{
.tag = .malformed,
.main_token = 0,
.data = .{ .lhs = @intFromEnum(AST.Diagnostic.Tag.expr_unexpected_token), .rhs = 0 },
.region = malformed_region,
});
self.cached_malformed_node = nid;
}
// Cast the cached node to the requested type
return @enumFromInt(@intFromEnum(self.cached_malformed_node.?));
}
}
fn recoverMalformedTypeDeclLine(self: *Parser, start: TokenIdx) void {
const source = self.tok_buf.env.source;
const start_region = self.tok_buf.resolve(start);
const statement_start_end: usize = @intCast(start_region.end.offset);
while (self.peek() != .EndOfFile and self.peek() != .CloseCurly) {
const current_region = self.tok_buf.resolve(self.pos);
const current_start: usize = @intCast(current_region.start.offset);
if (current_start > statement_start_end and
std.mem.findScalar(u8, source[statement_start_end..current_start], '\n') != null)
{
return;
}
self.advance();
}
}
/// parse a `.roc` module
///
/// the tokens are provided at Parser initialisation
pub fn runFile(self: *Parser) Error!void {
const trace = tracy.trace(@src());
defer trace.end();
self.store.emptyScratch();
const module_scope = try self.enterDeclScope(.module, .file, AST.TokenizedRegion.empty());
try self.store.addFile(.{
.header = undefined,
.statements = AST.Statement.Span{ .span = base.DataSpan.empty() },
.scope = module_scope,
.region = AST.TokenizedRegion.empty(),
});
const header = try self.parseHeaderTokens();
const scratch_top = self.store.scratchStatementTop();
while (self.peek() != .EndOfFile) {
const statement = try self.runTopLevelStatement();
try self.store.addScratchStatement(statement);
}
const file_region = AST.TokenizedRegion{ .start = 0, .end = @intCast(self.tok_buf.tokens.len - 1) };
try self.exitDeclScope(module_scope, file_region);
try self.store.addFile(.{
.header = header,
.statements = try self.store.statementSpanFrom(scratch_top),
.scope = module_scope,
.region = file_region,
});
}
/// Parse a Roc file header.
pub fn runHeader(self: *Parser) Error!AST.Header.Idx {
const trace = tracy.trace(@src());
defer trace.end();
return try self.parseHeaderTokens();
}
fn parseExposedItemTokens(self: *Parser) Error!AST.ExposedItem.Idx {
const start = self.pos;
switch (self.peek()) {
.LowerIdent => {
var as: ?TokenIdx = null;
if (self.peekNext() == .KwAs) {
self.advance();
self.advance();
as = self.pos;
self.expect(.LowerIdent) catch {
return try self.pushMalformed(AST.ExposedItem.Idx, .expected_lower_name_after_exposed_item_as, start);
};
} else {
self.advance();
}
return try self.store.addExposedItem(.{ .lower_ident = .{
.region = .{ .start = start, .end = self.pos },
.ident = start,
.as = as,
} });
},
.UpperIdent => {
var as: ?TokenIdx = null;
const qual_result = try self.readQualificationChain();
self.pos = qual_result.final_token + 1;
const ident = qual_result.final_token;
if (self.peek() == .KwAs) {
self.advance();
as = self.pos;
self.expect(.UpperIdent) catch {
return try self.pushMalformed(AST.ExposedItem.Idx, .expected_upper_name_after_exposed_item_as, start);
};
} else if (self.peek() == .DotStar) {
self.advance();
return try self.store.addExposedItem(.{ .upper_ident_star = .{
.region = .{ .start = start, .end = self.pos },
.ident = ident,
} });
}
return try self.store.addExposedItem(.{ .upper_ident = .{
.region = .{ .start = start, .end = self.pos },
.ident = ident,
.as = as,
} });
},
else => return try self.pushMalformed(AST.ExposedItem.Idx, .exposed_item_unexpected_token, start),
}
}
fn parseStringExprTokens(self: *Parser) Error!AST.Expr.Idx {
std.debug.assert(self.peek() == .StringStart);
return try self.runExprRoot(0);
}
fn parseRecordFieldTokens(self: *Parser) Error!AST.RecordField.Idx {
const start = self.pos;
self.expect(.LowerIdent) catch {
return try self.pushMalformed(AST.RecordField.Idx, .expected_expr_record_field_name, start);
};
const name = start;
var value: ?AST.Expr.Idx = null;
if (self.peek() == .OpColon) {
self.advance();
value = try self.runExprRoot(0);
}
return try self.store.addRecordField(.{
.name = name,
.value = value,
.region = .{ .start = start, .end = self.pos },
});
}
fn parseTypeIdentToken(self: *Parser) Error!AST.TypeAnno.Idx {
switch (self.peek()) {
.LowerIdent, .NamedUnderscore, .Underscore => {
const tok = self.pos;
self.advance();
const region = AST.TokenizedRegion{ .start = tok, .end = self.pos };
return try self.store.addTypeAnno(switch (self.tok_buf.tokens.items(.tag)[tok]) {
.LowerIdent => .{ .ty_var = .{ .region = region, .tok = tok } },
.NamedUnderscore => .{ .underscore_type_var = .{ .region = region, .tok = tok } },
.Underscore => .{ .underscore = .{ .region = region } },
else => unreachable,
});
},
else => return self.pushMalformed(AST.TypeAnno.Idx, .invalid_type_arg, self.pos),
}
}
fn parseTypeHeaderTokens(self: *Parser) Error!AST.TypeHeader.Idx {
const start = self.pos;
std.debug.assert(self.peek() == .UpperIdent);
self.advance();
const open_tok = self.peek();
if (open_tok != .NoSpaceOpenRound and open_tok != .OpenRound) {
return try self.store.addTypeHeader(.{
.name = start,
.args = .{ .span = .{ .start = 0, .len = 0 } },
.region = .{ .start = start, .end = self.pos },
});
}
self.advance();
const scratch_top = self.store.scratchTypeAnnoTop();
while (self.peek() != .CloseRound and self.peek() != .EndOfFile) {
try self.store.addScratchTypeAnno(try self.parseTypeIdentToken());
if (!self.consumeComma()) {
break;
}
}
if (self.peek() != .CloseRound) {
self.store.clearScratchTypeAnnosFrom(scratch_top);
return try self.pushMalformed(AST.TypeHeader.Idx, .expected_ty_anno_close_round_or_comma, start);
}
self.advance();
const args = try self.store.typeAnnoSpanFrom(scratch_top);
return try self.store.addTypeHeader(.{
.name = start,
.args = args,
.region = .{ .start = start, .end = self.pos },
});
}
fn parseImportStatementTokens(self: *Parser) Error!AST.Statement.Idx {
const start = self.pos;
std.debug.assert(self.peek() == .KwImport);
self.advance();
if (self.peek() == .StringStart) {
self.advance();
const path_tok = self.pos;
self.expect(.StringPart) catch {
return try self.pushMalformed(AST.Statement.Idx, .incomplete_import, start);
};
self.expect(.StringEnd) catch {
return try self.pushMalformed(AST.Statement.Idx, .incomplete_import, start);
};
self.expect(.KwAs) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_expected_as, start);
};
const name_tok = self.pos;
self.expect(.LowerIdent) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_expected_name, start);
};
self.expect(.OpColon) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_expected_type, start);
};
const type_tok = self.pos;
self.expect(.UpperIdent) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_expected_type, start);
};
const type_text = blk: {
const range = self.tok_buf.resolve(type_tok);
break :blk self.tok_buf.env.source[@intCast(range.start.offset)..@intCast(range.end.offset)];
};
var is_bytes = false;
if (std.mem.eql(u8, type_text, "Str")) {} else if (std.mem.eql(u8, type_text, "List")) {
is_bytes = true;
self.expect(.NoSpaceOpenRound) catch {
self.expect(.OpenRound) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_invalid_type, start);
};
};
if (self.peek() != .UpperIdent) {
return try self.pushMalformed(AST.Statement.Idx, .file_import_invalid_type, start);
}
const inner_type = blk: {
const range = self.tok_buf.resolve(self.pos);
break :blk self.tok_buf.env.source[@intCast(range.start.offset)..@intCast(range.end.offset)];
};
if (!std.mem.eql(u8, inner_type, "U8")) {
return try self.pushMalformed(AST.Statement.Idx, .file_import_invalid_type, start);
}
self.advance();
self.expect(.CloseRound) catch {
return try self.pushMalformed(AST.Statement.Idx, .file_import_invalid_type, start);
};
} else {
return try self.pushMalformed(AST.Statement.Idx, .file_import_invalid_type, start);
}
return try self.addStatement(.{ .file_import = .{
.path_tok = path_tok,
.name_tok = name_tok,
.type_tok = type_tok,
.is_bytes = is_bytes,
.region = .{ .start = start, .end = self.pos },
} });
}
var qualifier: ?TokenIdx = null;
var alias_tok: ?TokenIdx = null;
if (self.peek() == .LowerIdent) {
qualifier = self.pos;
self.advance();
}
if (!((qualifier == null and self.peek() == .UpperIdent) or
(qualifier != null and (self.peek() == .NoSpaceDotUpperIdent or self.peek() == .DotUpperIdent))))
{
return try self.pushMalformed(AST.Statement.Idx, .incomplete_import, start);
}
var exposes = AST.ExposedItem.Span{ .span = base.DataSpan.empty() };
var nested_import = false;
var last_upper_tok: TokenIdx = self.pos;
const module_name_tok = self.pos;
self.advance();
while (self.peek() == .NoSpaceDotUpperIdent or self.peek() == .DotUpperIdent) {
last_upper_tok = self.pos;
self.advance();
}
const has_explicit_clause = self.peek() == .KwAs or self.peek() == .KwExposing;
const has_multiple_segments = last_upper_tok != module_name_tok;
if (has_multiple_segments and !has_explicit_clause) {
nested_import = true;
const scratch_top = self.store.scratchExposedItemTop();
const exposed_item = try self.store.addExposedItem(.{ .upper_ident = .{
.region = .{ .start = last_upper_tok, .end = last_upper_tok },
.ident = last_upper_tok,
.as = null,
} });
try self.store.addScratchExposedItem(exposed_item);
exposes = try self.store.exposedItemSpanFrom(scratch_top);
} else {
if (self.peek() == .KwAs) {
self.advance();
alias_tok = self.pos;
self.expect(.UpperIdent) catch {
return try self.pushMalformed(AST.Statement.Idx, .expected_upper_name_after_import_as, start);
};
}
if (self.peek() == .KwExposing) {
self.advance();
self.expect(.OpenSquare) catch {
return try self.pushMalformed(AST.Statement.Idx, .import_exposing_no_open, start);
};
const scratch_top = self.store.scratchExposedItemTop();
while (self.peek() != .CloseSquare and self.peek() != .EndOfFile) {
try self.store.addScratchExposedItem(try self.parseExposedItemTokens());
if (!self.consumeComma()) {
break;
}
}
if (self.peek() != .CloseSquare) {
while (self.peek() != .CloseSquare and self.peek() != .EndOfFile) {
self.advance();
}
self.expect(.CloseSquare) catch {};
self.store.clearScratchExposedItemsFrom(scratch_top);
return try self.pushMalformed(AST.Statement.Idx, .import_exposing_no_close, start);
}
self.advance();