forked from roc-lang/roc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAST.zig
More file actions
2721 lines (2440 loc) · 109 KB
/
AST.zig
File metadata and controls
2721 lines (2440 loc) · 109 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
//!
//! This file implements the Intermediate Representation (IR) for Roc's parser.
//!
//! The IR provides a structured, tree-based representation of Roc source code after parsing
//!
//! The design uses an arena-based memory allocation strategy with a "multi-list" approach where nodes
//! are stored in a flat list but cross-referenced via indices rather than pointers. This improves
//! memory locality and efficiency.
//!
//! The implementation includes comprehensive facilities for building, manipulating, and traversing
//! the IR, as well as converting it to S-expressions for debugging and visualization.
const std = @import("std");
const testing = std.testing;
const base = @import("base");
const collections = @import("collections");
const reporting = @import("reporting");
const Node = @import("Node.zig");
const NodeStore = @import("NodeStore.zig");
pub const Token = tokenize.Token;
const TokenizedBuffer = tokenize.TokenizedBuffer;
const SExpr = base.SExpr;
const SExprTree = base.SExprTree;
const Ident = base.Ident;
const Allocator = std.mem.Allocator;
const CommonEnv = base.CommonEnv;
const tokenize = @import("tokenize.zig");
pub const tokensToHtml = @import("HTML.zig").tokensToHtml;
const AST = @This();
env: *CommonEnv,
tokens: TokenizedBuffer,
store: NodeStore,
root_node_idx: u32 = 0,
tokenize_diagnostics: std.ArrayListUnmanaged(tokenize.Diagnostic),
parse_diagnostics: std.ArrayListUnmanaged(AST.Diagnostic),
/// Calculate whether this region is - or will be - multiline
pub fn regionIsMultiline(self: *AST, region: TokenizedRegion) bool {
if (region.start >= region.end) return false;
// Check if there's a newline in the source text between start and end tokens
const start_region = self.tokens.resolve(region.start);
const end_region = self.tokens.resolve(region.end - 1);
const source_start = start_region.start.offset;
const source_end = end_region.end.offset;
// Look for newlines in the source text
for (self.env.source[source_start..source_end]) |c| {
if (c == '\n') {
return true;
}
}
// Also check for trailing comma patterns that indicate multiline
var i = region.start;
const tags = self.tokens.tokens.items(.tag);
while (i < region.end) {
if (tags[i] == .Comma and i + 1 < self.tokens.tokens.len and (tags[i + 1] == .CloseSquare or
tags[i + 1] == .CloseRound or
tags[i + 1] == .CloseCurly or
tags[i + 1] == .OpBar))
{
return true;
}
i += 1;
}
return false;
}
/// Returns whether this AST has any diagnostic errors.
pub fn hasErrors(self: *AST) bool {
return self.tokenize_diagnostics.items.len > 0 or self.parse_diagnostics.items.len > 0;
}
/// Returns diagnostic position information for the given region.
pub fn calcRegionInfo(self: *AST, region: TokenizedRegion, line_starts: []const u32) base.RegionInfo {
const start = self.tokens.resolve(region.start);
const end = self.tokens.resolve(region.end);
const info = base.RegionInfo.position(self.env.source, line_starts, start.start.offset, end.end.offset) catch {
// std.debug.panic("failed to calculate position info for region {?}, start: {}, end: {}", .{ region, start, end });
return .{
.start_line_idx = 0,
.start_col_idx = 0,
.end_line_idx = 0,
.end_col_idx = 0,
};
};
return info;
}
/// Append region information to an S-expression node for diagnostics
pub fn appendRegionInfoToSexprTree(self: *const AST, env: *const CommonEnv, tree: *SExprTree, region: TokenizedRegion) std.mem.Allocator.Error!void {
const start = self.tokens.resolve(region.start);
const region_end_idx = if (region.end > 0) region.end - 1 else region.end;
const end = self.tokens.resolve(region_end_idx);
const info: base.RegionInfo = base.RegionInfo.position(self.env.source, env.line_starts.items.items, start.start.offset, end.end.offset) catch .{
.start_line_idx = 0,
.start_col_idx = 0,
.end_line_idx = 0,
.end_col_idx = 0,
};
try tree.pushBytesRange(start.start.offset, end.end.offset, info);
}
pub fn deinit(self: *AST, gpa: std.mem.Allocator) void {
defer self.tokens.deinit(gpa);
defer self.store.deinit();
defer self.tokenize_diagnostics.deinit(gpa);
defer self.parse_diagnostics.deinit(gpa);
}
/// Convert a tokenize diagnostic to a Report for rendering
pub fn tokenizeDiagnosticToReport(self: *AST, diagnostic: tokenize.Diagnostic, allocator: std.mem.Allocator) !reporting.Report {
const title = switch (diagnostic.tag) {
.MisplacedCarriageReturn => "MISPLACED CARRIAGE RETURN",
.AsciiControl => "ASCII CONTROL CHARACTER",
.LeadingZero => "LEADING ZERO",
.UppercaseBase => "UPPERCASE BASE",
.InvalidUnicodeEscapeSequence => "INVALID UNICODE ESCAPE SEQUENCE",
.InvalidEscapeSequence => "INVALID ESCAPE SEQUENCE",
.UnclosedString => "UNCLOSED STRING",
.NonPrintableUnicodeInStrLiteral => "NON-PRINTABLE UNICODE IN STRING-LIKE LITERAL",
.InvalidUtf8InSource => "INVALID UTF-8",
};
const body = switch (diagnostic.tag) {
.MisplacedCarriageReturn => "Carriage return characters (\\r) are not allowed in Roc source code.",
.AsciiControl => "ASCII control characters are not allowed in Roc source code.",
.LeadingZero => "Numbers cannot have leading zeros.",
.UppercaseBase => "Number base prefixes must be lowercase (0x, 0o, 0b).",
.InvalidUnicodeEscapeSequence => "This Unicode escape sequence is not valid.",
.InvalidEscapeSequence => "This escape sequence is not recognized.",
.UnclosedString => "This string is missing a closing quote.",
.NonPrintableUnicodeInStrLiteral => "Non-printable Unicode characters are not allowed in string-like literals.",
.InvalidUtf8InSource => "Invalid UTF-8 encoding found in source code. Roc source files must be valid UTF-8.",
};
var report = reporting.Report.init(allocator, title, .runtime_error);
try report.document.addText(body);
try report.document.addLineBreak();
try report.document.addLineBreak();
// Add the region information from the diagnostic if valid
if (diagnostic.region.start.offset < diagnostic.region.end.offset and
diagnostic.region.end.offset <= self.env.source.len)
{
var env = self.env.*;
if (env.line_starts.items.items.len == 0) {
try env.calcLineStarts(allocator);
}
// Convert region to RegionInfo
const region_info = base.RegionInfo.position(
self.env.source,
env.line_starts.items.items,
diagnostic.region.start.offset,
diagnostic.region.end.offset,
) catch {
// If we can't calculate region info, just return the report without source context
return report;
};
// Add source region to the report
try report.document.addSourceRegion(
region_info,
.error_highlight,
null, // No filename available for tokenize diagnostics
self.env.source,
env.line_starts.items.items,
);
}
return report;
}
/// Convert TokenizedRegion to base.Region for error reporting
pub fn tokenizedRegionToRegion(self: *AST, tokenized_region: TokenizedRegion) base.Region {
const token_count: u32 = @intCast(self.tokens.tokens.len);
// Ensure both start and end are within bounds
const safe_start_idx = if (tokenized_region.start >= token_count)
token_count - 1
else
tokenized_region.start;
const safe_end_idx = if (tokenized_region.end > token_count)
token_count
else
tokenized_region.end;
// Ensure end is at least start to prevent invalid regions
const final_end_idx = if (safe_end_idx < safe_start_idx)
safe_start_idx + 1
else
safe_end_idx;
const start_region = self.tokens.resolve(safe_start_idx);
const end_region = self.tokens.resolve(final_end_idx - 1);
return .{
.start = start_region.start,
.end = end_region.end,
};
}
/// Get the text content of a token for error reporting
fn getTokenText(self: *AST, token_idx: Token.Idx) []const u8 {
const token_region = self.tokens.resolve(@intCast(token_idx));
return self.env.source[token_region.start.offset..token_region.end.offset];
}
/// Convert a parse diagnostic to a Report for rendering
pub fn parseDiagnosticToReport(self: *AST, env: *const CommonEnv, diagnostic: Diagnostic, allocator: std.mem.Allocator, filename: []const u8) !reporting.Report {
const raw_region = self.tokenizedRegionToRegion(diagnostic.region);
// Ensure region bounds are valid for source slicing
const region = base.Region{
.start = .{ .offset = @min(raw_region.start.offset, self.env.source.len) },
.end = .{ .offset = @min(@max(raw_region.end.offset, raw_region.start.offset), self.env.source.len) },
};
const title = switch (diagnostic.tag) {
.multiple_platforms => "MULTIPLE PLATFORMS",
.no_platform => "NO PLATFORM",
.missing_header => "MISSING HEADER",
.missing_arrow => "MISSING ARROW",
.expected_exposes => "EXPECTED EXPOSES",
.expected_exposes_close_square => "EXPECTED CLOSING BRACKET",
.expected_exposes_open_square => "EXPECTED OPENING BRACKET",
.expected_imports => "EXPECTED IMPORTS",
.pattern_unexpected_token => "UNEXPECTED TOKEN IN PATTERN",
.pattern_list_rest_old_syntax => "BAD LIST REST PATTERN SYNTAX",
.pattern_unexpected_eof => "UNEXPECTED END OF FILE IN PATTERN",
.ty_anno_unexpected_token => "UNEXPECTED TOKEN IN TYPE ANNOTATION",
.string_unexpected_token => "UNEXPECTED TOKEN IN STRING",
.expr_unexpected_token => "UNEXPECTED TOKEN IN EXPRESSION",
.import_must_be_top_level => "IMPORT MUST BE TOP LEVEL",
.expected_expr_close_square_or_comma => "LIST NOT CLOSED",
.where_expected_mod_open => "WHERE CLAUSE ERROR",
.where_expected_var => "WHERE CLAUSE ERROR",
.where_expected_mod_close => "WHERE CLAUSE ERROR",
.where_expected_arg_open => "WHERE CLAUSE ERROR",
.where_expected_arg_close => "WHERE CLAUSE ERROR",
.where_expected_method_arrow => "WHERE CLAUSE ERROR",
.where_expected_method_or_alias_name => "WHERE CLAUSE ERROR",
.where_expected_module => "WHERE CLAUSE ERROR",
.where_expected_colon => "WHERE CLAUSE ERROR",
.where_expected_constraints => "WHERE CLAUSE ERROR",
.no_else => "IF WITHOUT ELSE",
else => "PARSE ERROR",
};
var report = reporting.Report.init(allocator, title, .runtime_error);
// Add detailed error message based on the diagnostic type
switch (diagnostic.tag) {
.missing_header => {
try report.document.addReflowingText("Roc files must start with a module header.");
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addText("For example:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("module [main]");
try report.document.addLineBreak();
try report.document.addText("or for an app:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("app [main!] { pf: platform \"../basic-cli/platform.roc\" }");
},
.multiple_platforms => {
try report.document.addReflowingText("Only one platform declaration is allowed per file.");
try report.document.addLineBreak();
try report.document.addReflowingText("Remove the duplicate platform declaration.");
},
.no_platform => {
try report.document.addReflowingText("App files must specify a platform.");
try report.document.addLineBreak();
try report.document.addText("Add a platform specification like:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("{ pf: platform \"../basic-cli/platform.roc\" }");
},
.missing_arrow => {
try report.document.addText("Expected an arrow ");
try report.document.addAnnotated("->", .emphasized);
try report.document.addText(" here.");
try report.document.addLineBreak();
try report.document.addReflowingText("Function type annotations require arrows between parameter and return types.");
},
.expected_exposes, .expected_exposes_close_square, .expected_exposes_open_square => {
try report.document.addReflowingText("Module headers must have an ");
try report.document.addKeyword("exposing");
try report.document.addReflowingText(" section that lists what the module exposes.");
try report.document.addLineBreak();
try report.document.addText("For example: ");
try report.document.addCodeBlock("module [main, add, subtract]");
},
.expected_imports => {
try report.document.addReflowingText("Import statements must specify what is being imported.");
try report.document.addLineBreak();
try report.document.addText("For example: ");
try report.document.addCodeBlock("import pf.Stdout exposing [line!]");
},
.pattern_unexpected_token => {
const token_text = if (diagnostic.region.start != diagnostic.region.end)
self.env.source[region.start.offset..region.end.offset]
else
"<unknown>";
const owned_token = try report.addOwnedString(token_text);
try report.document.addText("The token ");
try report.document.addAnnotated(owned_token, .error_highlight);
try report.document.addText(" is not expected in a pattern.");
try report.document.addLineBreak();
try report.document.addReflowingText("Patterns can contain identifiers, literals, lists, records, or tags.");
},
.pattern_list_rest_old_syntax => {
try report.document.addReflowingText("List rest patterns should use the `.. as name` syntax, not `..name`.");
try report.document.addLineBreak();
try report.document.addReflowingText("For example, use `[first, .. as rest]` instead of `[first, ..rest]`.");
},
.pattern_unexpected_eof => {
try report.document.addReflowingText("This pattern is incomplete - the file ended unexpectedly.");
try report.document.addLineBreak();
try report.document.addReflowingText("Complete the pattern or remove the incomplete pattern.");
},
.ty_anno_unexpected_token => {
const token_text = if (diagnostic.region.start != diagnostic.region.end)
self.env.source[region.start.offset..region.end.offset]
else
"<unknown>";
const owned_token = try report.addOwnedString(token_text);
try report.document.addText("The token ");
try report.document.addAnnotated(owned_token, .error_highlight);
try report.document.addText(" is not expected in a type annotation.");
try report.document.addLineBreak();
try report.document.addReflowingText("Type annotations should contain types like ");
try report.document.addType("Str");
try report.document.addText(", ");
try report.document.addType("Num a");
try report.document.addText(", or ");
try report.document.addType("List U64");
try report.document.addText(".");
},
.string_unexpected_token => {
const token_text = if (diagnostic.region.start != diagnostic.region.end)
self.env.source[region.start.offset..region.end.offset]
else
"<unknown>";
const owned_token = try report.addOwnedString(token_text);
try report.document.addText("The token ");
try report.document.addAnnotated(owned_token, .error_highlight);
try report.document.addText(" is not expected in a string literal.");
try report.document.addLineBreak();
try report.document.addReflowingText("String literals should be enclosed in double quotes.");
},
.expr_unexpected_token => {
const token_text = if (diagnostic.region.start != diagnostic.region.end)
self.env.source[region.start.offset..region.end.offset]
else
"<unknown>";
const owned_token = try report.addOwnedString(token_text);
try report.document.addText("The token ");
try report.document.addAnnotated(owned_token, .error_highlight);
try report.document.addText(" is not expected in an expression.");
try report.document.addLineBreak();
try report.document.addReflowingText("Expressions can be identifiers, literals, function calls, or operators.");
},
.import_must_be_top_level => {
try report.document.addReflowingText("Import statements must appear at the top level of a module.");
try report.document.addLineBreak();
try report.document.addReflowingText("Move this import to the top of the file, after the module header but before any definitions.");
},
.expected_expr_close_square_or_comma => {
try report.document.addReflowingText("This list is missing a closing bracket or has a syntax error.");
try report.document.addLineBreak();
try report.document.addText("Lists must be closed with ");
try report.document.addAnnotated("]", .emphasized);
try report.document.addText(" and list items must be separated by commas.");
try report.document.addLineBreak();
try report.document.addText("For example: ");
try report.document.addCodeBlock("[1, 2, 3]");
},
.expected_colon_after_type_annotation => {
try report.document.addReflowingText("Type applications require parentheses around their type arguments.");
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addReflowingText("I found a type followed by what looks like a type argument, but they need to be connected with parentheses.");
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addText("Instead of:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addAnnotated("List U8", .error_highlight);
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addText("Use:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addAnnotated("List(U8)", .emphasized);
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addText("Other valid examples:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addAnnotated("Dict(Str, Num)", .dimmed);
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addAnnotated("Result(a, Str)", .dimmed);
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addAnnotated("Maybe(List(U64))", .dimmed);
},
.where_expected_mod_open => {
try report.document.addReflowingText("Expected an opening parenthesis after ");
try report.document.addKeyword("module");
try report.document.addText(" in this where clause.");
try report.document.addLineBreak();
try report.document.addText("Module constraints should look like: ");
try report.document.addCodeBlock("module(a).method : Type");
},
.where_expected_var => {
try report.document.addReflowingText("Expected a type variable name here.");
try report.document.addLineBreak();
try report.document.addReflowingText("Type variables are lowercase identifiers that represent types.");
},
.where_expected_mod_close => {
try report.document.addReflowingText("Expected a closing parenthesis after the type variable in this module constraint.");
try report.document.addLineBreak();
try report.document.addText("Module constraints should look like: ");
try report.document.addCodeBlock("module(a).method : Type");
},
.where_expected_arg_open => {
try report.document.addReflowingText("Expected an opening parenthesis for the method arguments.");
try report.document.addLineBreak();
try report.document.addText("Method constraints should look like: ");
try report.document.addCodeBlock("module(a).method : args -> ret");
},
.where_expected_arg_close => {
try report.document.addReflowingText("Expected a closing parenthesis after the method arguments.");
try report.document.addLineBreak();
try report.document.addText("Method constraints should look like: ");
try report.document.addCodeBlock("module(a).method : args -> ret");
},
.where_expected_method_arrow => {
try report.document.addReflowingText("Expected an arrow ");
try report.document.addAnnotated("->", .emphasized);
try report.document.addText(" after the method arguments.");
try report.document.addLineBreak();
try report.document.addText("Method constraints should look like: ");
try report.document.addCodeBlock("module(a).method : args -> ret");
},
.where_expected_method_or_alias_name => {
try report.document.addReflowingText("Expected a method name or type alias after the dot.");
try report.document.addLineBreak();
try report.document.addText("Where clauses can contain:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addText("• Method constraints: ");
try report.document.addCodeBlock("module(a).method : args -> ret");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addText("• Type aliases: ");
try report.document.addCodeBlock("module(a).SomeTypeAlias");
},
.where_expected_module => {
try report.document.addReflowingText("Expected ");
try report.document.addKeyword("module");
try report.document.addText(" at the start of this where clause constraint.");
try report.document.addLineBreak();
try report.document.addText("Where clauses can contain:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addText("• Method constraints: ");
try report.document.addCodeBlock("module(a).method : Type");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addText("• Type aliases: ");
try report.document.addCodeBlock("module(a).SomeType");
},
.where_expected_colon => {
try report.document.addReflowingText("Expected a colon ");
try report.document.addAnnotated(":", .emphasized);
try report.document.addText(" after the method name in this where clause constraint.");
try report.document.addLineBreak();
try report.document.addReflowingText("Method constraints require a colon to separate the method name from its type.");
try report.document.addLineBreak();
try report.document.addText("For example: ");
try report.document.addCodeBlock("module(a).method : a -> b");
},
.where_expected_constraints => {
try report.document.addReflowingText("A ");
try report.document.addKeyword("where");
try report.document.addText(" clause cannot be empty.");
try report.document.addLineBreak();
try report.document.addReflowingText("Where clauses must contain at least one constraint.");
try report.document.addLineBreak();
try report.document.addText("For example:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("module(a).method : a -> b");
},
.match_branch_wrong_arrow => {
try report.document.addReflowingText("Match branches use `=>` instead of `->`.");
},
.multi_arrow_needs_parens => {
try report.document.addReflowingText("Function types with multiple arrows need parentheses.");
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addText("Instead of writing ");
try report.document.addAnnotated("a -> b -> c", .error_highlight);
try report.document.addText(", use parentheses to clarify which you mean:");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("a -> (b -> c)");
try report.document.addText(" for a ");
try report.document.addAnnotated("curried", .emphasized);
try report.document.addText(" function (a function that ");
try report.document.addAnnotated("returns", .emphasized);
try report.document.addText(" another function)");
try report.document.addLineBreak();
try report.document.addIndent(1);
try report.document.addCodeBlock("(a -> b) -> c");
try report.document.addText(" for a ");
try report.document.addAnnotated("higher-order", .emphasized);
try report.document.addText(" function (a function that ");
try report.document.addAnnotated("takes", .emphasized);
try report.document.addText(" another function)");
},
.no_else => {
try report.document.addText("This ");
try report.document.addKeyword("if");
try report.document.addText(" is being used as an expression, but it doesn't have an ");
try report.document.addKeyword("else");
try report.document.addText(".");
try report.document.addLineBreak();
try report.document.addLineBreak();
try report.document.addReflowingText("When ");
try report.document.addKeyword("if");
try report.document.addReflowingText(" is used as an expression (to evaluate to a value), it must have an ");
try report.document.addKeyword("else");
try report.document.addReflowingText(" branch to specify what value to use when the condition is ");
try report.document.addKeyword("False");
try report.document.addReflowingText(".");
},
else => {
const tag_name = @tagName(diagnostic.tag);
const owned_tag = try report.addOwnedString(tag_name);
try report.document.addText("A parsing error occurred: ");
try report.document.addAnnotated(owned_tag, .dimmed);
try report.document.addLineBreak();
try report.document.addReflowingText("This is an unexpected parsing error. Please check your syntax.");
},
}
// Add source context if we have a valid region
if (region.start.offset <= region.end.offset and region.end.offset <= self.env.source.len) {
// Use proper region info calculation with converted region
const region_info = base.RegionInfo.position(self.env.source, env.line_starts.items.items, region.start.offset, region.end.offset) catch {
return report; // Return report without source context if region calculation fails
};
try report.document.addLineBreak();
try report.document.addLineBreak();
// Use the proper addSourceContext method with owned filename
const owned_filename = try report.addOwnedString(filename);
try report.addSourceContext(region_info, owned_filename, self.env.source, env.line_starts.items.items);
}
return report;
}
/// Diagnostics related to parsing
pub const Diagnostic = struct {
tag: Tag,
region: TokenizedRegion,
/// different types of diagnostic errors
pub const Tag = enum {
multiple_platforms,
no_platform,
missing_header,
missing_arrow,
expected_exposes,
expected_exposes_close_square,
expected_exposes_open_square,
expected_imports,
expected_package_or_platform_name,
expected_package_or_platform_colon,
expected_package_or_platform_string,
expected_package_platform_close_curly,
expected_package_platform_open_curly,
expected_packages,
expected_packages_close_curly,
expected_packages_open_curly,
expected_platform_name_end,
expected_platform_name_start,
expected_platform_name_string,
expected_platform_string,
expected_provides,
expected_provides_close_square,
expected_provides_open_square,
expected_requires,
expected_requires_rigids_close_curly,
expected_requires_rigids_open_curly,
expected_requires_signatures_close_curly,
expected_requires_signatures_open_curly,
header_expected_open_square,
header_expected_close_square,
pattern_unexpected_token,
pattern_list_rest_old_syntax,
pattern_unexpected_eof,
bad_as_pattern_name,
ty_anno_unexpected_token,
statement_unexpected_token,
string_unexpected_token,
string_expected_close_interpolation,
string_unclosed,
expr_no_space_dot_int,
import_exposing_no_open,
import_exposing_no_close,
no_else,
expected_type_field_name,
expected_colon_after_type_field_name,
expected_arrow,
multi_arrow_needs_parens,
expected_ty_close_curly_or_comma,
expected_ty_close_square_or_comma,
expected_lower_name_after_exposed_item_as,
expected_upper_name_after_exposed_item_as,
exposed_item_unexpected_token,
expected_upper_name_after_import_as,
expected_colon_after_type_annotation,
expected_lower_ident_pat_field_name,
expected_colon_after_pat_field_name,
expected_expr_bar,
expected_expr_close_curly_or_comma,
expected_expr_close_round_or_comma,
expected_expr_close_square_or_comma,
expected_close_curly_at_end_of_match,
expected_open_curly_after_match,
expr_unexpected_token,
expected_expr_record_field_name,
expected_ty_apply_close_round,
expected_expr_apply_close_round,
where_expected_mod_open,
where_expected_var,
where_expected_mod_close,
where_expected_arg_open,
where_expected_arg_close,
where_expected_method_arrow,
where_expected_method_or_alias_name,
where_expected_module,
where_expected_colon,
where_expected_constraints,
import_must_be_top_level,
invalid_type_arg,
expr_arrow_expects_ident,
var_only_allowed_in_a_body,
var_must_have_ident,
var_expected_equals,
for_expected_in,
match_branch_wrong_arrow,
match_branch_missing_arrow,
expected_ty_anno_close_round,
expected_ty_anno_close_round_or_comma,
expected_expr_comma,
expected_expr_close_curly,
expr_dot_suffix_not_allowed,
};
};
/// The first and last token consumed by a Node
pub const TokenizedRegion = struct {
start: Token.Idx,
end: Token.Idx,
pub fn empty() TokenizedRegion {
return .{ .start = 0, .end = 0 };
}
pub fn spanAcross(self: TokenizedRegion, other: TokenizedRegion) TokenizedRegion {
return .{
.start = self.start,
.end = other.end,
};
}
pub fn toBase(self: TokenizedRegion) base.Region {
return .{
.start = base.Region.Position{ .offset = self.start },
.end = base.Region.Position{ .offset = self.end },
};
}
};
/// Resolve a token index to a string slice from the source code.
pub fn resolve(self: *const AST, token: Token.Idx) []const u8 {
const range = self.tokens.resolve(token);
return self.env.source[@intCast(range.start.offset)..@intCast(range.end.offset)];
}
/// Resolves a fully qualified name from a chain of qualifier tokens and a final token.
/// If there are qualifiers, returns a slice from the first qualifier to the final token.
/// Otherwise, returns the final token text with any leading dot stripped based on the token type.
pub fn resolveQualifiedName(
self: *const AST,
qualifiers: Token.Span,
final_token: Token.Idx,
strip_dot_from_tokens: []const Token.Tag,
) []const u8 {
const qualifier_tokens = self.store.tokenSlice(qualifiers);
if (qualifier_tokens.len > 0) {
// Get the region of the first qualifier token
const first_qualifier_tok = @as(Token.Idx, @intCast(qualifier_tokens[0]));
const first_region = self.tokens.resolve(first_qualifier_tok);
// Get the region of the final token
const final_region = self.tokens.resolve(final_token);
// Slice from the start of the first qualifier to the end of the final token
const start_offset = first_region.start.offset;
const end_offset = final_region.end.offset;
return self.env.source[@intCast(start_offset)..@intCast(end_offset)];
} else {
// Get the raw token text and strip leading dot if it's one of the specified tokens
const raw_text = self.resolve(final_token);
const token_tag = self.tokens.tokens.items(.tag)[@intCast(final_token)];
for (strip_dot_from_tokens) |dot_token_tag| {
if (token_tag == dot_token_tag and raw_text.len > 0 and raw_text[0] == '.') {
return raw_text[1..];
}
}
return raw_text;
}
}
/// Contains properties of the thing to the right of the `import` keyword.
pub const ImportRhs = packed struct {
/// e.g. 1 in case we use import `as`: `import Module as Mod`
aliased: u1,
/// 1 in case the import is qualified, e.g. `pf` in `import pf.Stdout ...`
qualified: u1,
/// The number of things in the exposes list. e.g. 3 in `import SomeModule exposing [a1, a2, a3]`
num_exposes: u30,
};
// Check that all packed structs are 4 bytes size as they as cast to
// and from a u32
comptime {
std.debug.assert(@sizeOf(Header.AppHeaderRhs) == 4);
std.debug.assert(@sizeOf(ImportRhs) == 4);
}
test {
_ = std.testing.refAllDeclsRecursive(@This());
}
/// Helper function to convert the AST to a human friendly representation in S-expression format
pub fn toSExprStr(ast: *@This(), gpa: std.mem.Allocator, env: *const CommonEnv, writer: std.io.AnyWriter) !void {
const file = ast.store.getFile();
var tree = SExprTree.init(gpa);
defer tree.deinit();
try file.pushToSExprTree(gpa, env, ast, &tree);
try tree.toStringPretty(writer);
}
/// The kind of the type declaration represented, either:
/// 1. An alias of the form `Foo = (Bar, Baz)`
/// 2. A nominal type of the form `Foo := [Bar, Baz]`
pub const TypeDeclKind = enum {
alias,
nominal,
};
/// Represents a statement. Not all statements are valid in all positions.
pub const Statement = union(enum) {
decl: Decl,
@"var": struct {
name: Token.Idx,
body: Expr.Idx,
region: TokenizedRegion,
},
expr: struct {
expr: Expr.Idx,
region: TokenizedRegion,
},
crash: struct {
expr: Expr.Idx,
region: TokenizedRegion,
},
dbg: struct {
expr: Expr.Idx,
region: TokenizedRegion,
},
expect: struct {
body: Expr.Idx,
region: TokenizedRegion,
},
@"for": struct {
patt: Pattern.Idx,
expr: Expr.Idx,
body: Expr.Idx,
region: TokenizedRegion,
},
@"return": struct {
expr: Expr.Idx,
region: TokenizedRegion,
},
import: struct {
module_name_tok: Token.Idx,
qualifier_tok: ?Token.Idx,
alias_tok: ?Token.Idx,
exposes: ExposedItem.Span,
region: TokenizedRegion,
},
type_decl: struct {
header: TypeHeader.Idx,
anno: TypeAnno.Idx,
where: ?Collection.Idx,
kind: TypeDeclKind,
region: TokenizedRegion,
},
type_anno: struct {
name: Token.Idx,
anno: TypeAnno.Idx,
where: ?Collection.Idx,
region: TokenizedRegion,
},
malformed: struct {
reason: Diagnostic.Tag,
region: TokenizedRegion,
},
pub const Idx = enum(u32) { _ };
pub const Span = struct { span: base.DataSpan };
pub const Decl = struct {
pattern: Pattern.Idx,
body: Expr.Idx,
region: TokenizedRegion,
};
/// Push this Statement to the SExprTree stack
pub fn pushToSExprTree(self: @This(), gpa: std.mem.Allocator, env: *const CommonEnv, ast: *const AST, tree: *SExprTree) std.mem.Allocator.Error!void {
switch (self) {
.decl => |decl| {
const begin = tree.beginNode();
try tree.pushStaticAtom("s-decl");
try ast.appendRegionInfoToSexprTree(env, tree, decl.region);
const attrs = tree.beginNode();
// pattern
try ast.store.getPattern(decl.pattern).pushToSExprTree(gpa, env, ast, tree);
// body
try ast.store.getExpr(decl.body).pushToSExprTree(gpa, env, ast, tree);
try tree.endNode(begin, attrs);
},
.@"var" => |v| {
const begin = tree.beginNode();
try tree.pushStaticAtom("s-var");
try ast.appendRegionInfoToSexprTree(env, tree, v.region);
const name_str = ast.resolve(v.name);
try tree.pushStringPair("name", name_str);
const attrs = tree.beginNode();
try ast.store.getExpr(v.body).pushToSExprTree(gpa, env, ast, tree);
try tree.endNode(begin, attrs);
},
.expr => |expr| {
try ast.store.getExpr(expr.expr).pushToSExprTree(gpa, env, ast, tree);
},
.import => |import| {
const begin = tree.beginNode();
try tree.pushStaticAtom("s-import");
try ast.appendRegionInfoToSexprTree(env, tree, import.region);
// Reconstruct full qualified module name
const module_name_raw = ast.resolve(import.module_name_tok);
if (import.qualifier_tok) |tok| {
const qualifier_str = ast.resolve(tok);
// Strip leading dot from module name if present
const module_name_clean = if (module_name_raw.len > 0 and module_name_raw[0] == '.')
module_name_raw[1..]
else
module_name_raw;
// Combine qualifier and module name
const full_module_name = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ qualifier_str, module_name_clean });
defer gpa.free(full_module_name);
try tree.pushStringPair("raw", full_module_name);
} else {
try tree.pushStringPair("raw", module_name_raw);
}
// alias e.g. `OUT` in `import pf.Stdout as OUT`
if (import.alias_tok) |tok| {
const alias_str = ast.resolve(tok);
try tree.pushStringPair("alias", alias_str);
}
const attrs = tree.beginNode();
// exposed identifiers e.g. [foo, bar] in `import pf.Stdout exposing [foo, bar]`
const exposed_slice = ast.store.exposedItemSlice(import.exposes);
if (exposed_slice.len > 0) {
const exposed = tree.beginNode();
try tree.pushStaticAtom("exposing");
const attrs2 = tree.beginNode();
for (ast.store.exposedItemSlice(import.exposes)) |e| {
try ast.store.getExposedItem(e).pushToSExprTree(gpa, env, ast, tree);
}
try tree.endNode(exposed, attrs2);
}
try tree.endNode(begin, attrs);
},
.type_decl => |a| {
const begin = tree.beginNode();
try tree.pushStaticAtom("s-type-decl");
try ast.appendRegionInfoToSexprTree(env, tree, a.region);
const attrs = tree.beginNode();
// pattern
{
const header = tree.beginNode();
try tree.pushStaticAtom("header");
// Check if the type header node is malformed before calling getTypeHeader
const header_node = ast.store.nodes.get(@enumFromInt(@intFromEnum(a.header)));
if (header_node.tag == .malformed) {
// Handle malformed type header by creating a placeholder
try ast.appendRegionInfoToSexprTree(env, tree, header_node.region);
try tree.pushStringPair("name", "<malformed>");
const attrs2 = tree.beginNode();
const args_begin = tree.beginNode();
try tree.pushStaticAtom("args");
const args_attrs = tree.beginNode();
try tree.endNode(args_begin, args_attrs);
try tree.endNode(header, attrs2);
} else {
const ty_header = ast.store.getTypeHeader(a.header) catch unreachable; // Malformed handled above
try ast.appendRegionInfoToSexprTree(env, tree, ty_header.region);
try tree.pushStringPair("name", ast.resolve(ty_header.name));
const attrs2 = tree.beginNode();
const args_begin = tree.beginNode();
try tree.pushStaticAtom("args");
const args_node = tree.beginNode();
for (ast.store.typeAnnoSlice(ty_header.args)) |b| {
const anno = ast.store.getTypeAnno(b);
try anno.pushToSExprTree(gpa, env, ast, tree);
}
try tree.endNode(args_begin, args_node);
try tree.endNode(header, attrs2);
}
}
try ast.store.getTypeAnno(a.anno).pushToSExprTree(gpa, env, ast, tree);
if (a.where) |where_coll| {
const where_node = tree.beginNode();
try tree.pushStaticAtom("where");
const attrs2 = tree.beginNode();
for (ast.store.whereClauseSlice(.{ .span = ast.store.getCollection(where_coll).span })) |clause_idx| {
const clause_child = ast.store.getWhereClause(clause_idx);
try clause_child.pushToSExprTree(gpa, env, ast, tree);
}
try tree.endNode(where_node, attrs2);
}
try tree.endNode(begin, attrs);
},
.crash => |a| {
const begin = tree.beginNode();
try tree.pushStaticAtom("s-crash");
try ast.appendRegionInfoToSexprTree(env, tree, a.region);
const attrs = tree.beginNode();
try ast.store.getExpr(a.expr).pushToSExprTree(gpa, env, ast, tree);
try tree.endNode(begin, attrs);
},