/
Ast.zig
3583 lines (3368 loc) · 122 KB
/
Ast.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
//! Abstract Syntax Tree for Zig source code.
//! For Zig syntax, the root node is at nodes[0] and contains the list of
//! sub-nodes.
//! For Zon syntax, the root node is at nodes[0] and contains lhs as the node
//! index of the main expression.
/// Reference to externally-owned data.
source: [:0]const u8,
tokens: TokenList.Slice,
/// The root AST node is assumed to be index 0. Since there can be no
/// references to the root node, this means 0 is available to indicate null.
nodes: NodeList.Slice,
extra_data: []Node.Index,
mode: Mode = .zig,
errors: []const Error,
pub const TokenIndex = u32;
pub const ByteOffset = u32;
pub const TokenList = std.MultiArrayList(struct {
tag: Token.Tag,
start: ByteOffset,
});
pub const NodeList = std.MultiArrayList(Node);
pub const Location = struct {
line: usize,
column: usize,
line_start: usize,
line_end: usize,
};
pub const Span = struct {
start: u32,
end: u32,
main: u32,
};
pub fn deinit(tree: *Ast, gpa: Allocator) void {
tree.tokens.deinit(gpa);
tree.nodes.deinit(gpa);
gpa.free(tree.extra_data);
gpa.free(tree.errors);
tree.* = undefined;
}
pub const RenderError = error{
/// Ran out of memory allocating call stack frames to complete rendering, or
/// ran out of memory allocating space in the output buffer.
OutOfMemory,
};
pub const Mode = enum { zig, zon };
/// Result should be freed with tree.deinit() when there are
/// no more references to any of the tokens or nodes.
pub fn parse(gpa: Allocator, source: [:0]const u8, mode: Mode) Allocator.Error!Ast {
var tokens = Ast.TokenList{};
defer tokens.deinit(gpa);
// Empirically, the zig std lib has an 8:1 ratio of source bytes to token count.
const estimated_token_count = source.len / 8;
try tokens.ensureTotalCapacity(gpa, estimated_token_count);
var tokenizer = std.zig.Tokenizer.init(source);
while (true) {
const token = tokenizer.next();
try tokens.append(gpa, .{
.tag = token.tag,
.start = @as(u32, @intCast(token.loc.start)),
});
if (token.tag == .eof) break;
}
var parser: Parse = .{
.source = source,
.gpa = gpa,
.token_tags = tokens.items(.tag),
.token_starts = tokens.items(.start),
.errors = .{},
.nodes = .{},
.extra_data = .{},
.scratch = .{},
.tok_i = 0,
};
defer parser.errors.deinit(gpa);
defer parser.nodes.deinit(gpa);
defer parser.extra_data.deinit(gpa);
defer parser.scratch.deinit(gpa);
// Empirically, Zig source code has a 2:1 ratio of tokens to AST nodes.
// Make sure at least 1 so we can use appendAssumeCapacity on the root node below.
const estimated_node_count = (tokens.len + 2) / 2;
try parser.nodes.ensureTotalCapacity(gpa, estimated_node_count);
switch (mode) {
.zig => try parser.parseRoot(),
.zon => try parser.parseZon(),
}
// TODO experiment with compacting the MultiArrayList slices here
return Ast{
.source = source,
.mode = mode,
.tokens = tokens.toOwnedSlice(),
.nodes = parser.nodes.toOwnedSlice(),
.extra_data = try parser.extra_data.toOwnedSlice(gpa),
.errors = try parser.errors.toOwnedSlice(gpa),
};
}
/// `gpa` is used for allocating the resulting formatted source code.
/// Caller owns the returned slice of bytes, allocated with `gpa`.
pub fn render(tree: Ast, gpa: Allocator) RenderError![]u8 {
var buffer = std.ArrayList(u8).init(gpa);
defer buffer.deinit();
try tree.renderToArrayList(&buffer, .{});
return buffer.toOwnedSlice();
}
pub const Fixups = private_render.Fixups;
pub fn renderToArrayList(tree: Ast, buffer: *std.ArrayList(u8), fixups: Fixups) RenderError!void {
return @import("./render.zig").renderTree(buffer, tree, fixups);
}
/// Returns an extra offset for column and byte offset of errors that
/// should point after the token in the error message.
pub fn errorOffset(tree: Ast, parse_error: Error) u32 {
return if (parse_error.token_is_prev)
@as(u32, @intCast(tree.tokenSlice(parse_error.token).len))
else
0;
}
pub fn tokenLocation(self: Ast, start_offset: ByteOffset, token_index: TokenIndex) Location {
var loc = Location{
.line = 0,
.column = 0,
.line_start = start_offset,
.line_end = self.source.len,
};
const token_start = self.tokens.items(.start)[token_index];
// Scan to by line until we go past the token start
while (std.mem.indexOfScalarPos(u8, self.source, loc.line_start, '\n')) |i| {
if (i >= token_start) {
break; // Went past
}
loc.line += 1;
loc.line_start = i + 1;
}
const offset = loc.line_start;
for (self.source[offset..], 0..) |c, i| {
if (i + offset == token_start) {
loc.line_end = i + offset;
while (loc.line_end < self.source.len and self.source[loc.line_end] != '\n') {
loc.line_end += 1;
}
return loc;
}
if (c == '\n') {
loc.line += 1;
loc.column = 0;
loc.line_start = i + 1;
} else {
loc.column += 1;
}
}
return loc;
}
pub fn tokenSlice(tree: Ast, token_index: TokenIndex) []const u8 {
const token_starts = tree.tokens.items(.start);
const token_tags = tree.tokens.items(.tag);
const token_tag = token_tags[token_index];
// Many tokens can be determined entirely by their tag.
if (token_tag.lexeme()) |lexeme| {
return lexeme;
}
// For some tokens, re-tokenization is needed to find the end.
var tokenizer: std.zig.Tokenizer = .{
.buffer = tree.source,
.index = token_starts[token_index],
.pending_invalid_token = null,
};
const token = tokenizer.findTagAtCurrentIndex(token_tag);
assert(token.tag == token_tag);
return tree.source[token.loc.start..token.loc.end];
}
pub fn extraData(tree: Ast, index: usize, comptime T: type) T {
const fields = std.meta.fields(T);
var result: T = undefined;
inline for (fields, 0..) |field, i| {
comptime assert(field.type == Node.Index);
@field(result, field.name) = tree.extra_data[index + i];
}
return result;
}
pub fn rootDecls(tree: Ast) []const Node.Index {
// Root is always index 0.
const nodes_data = tree.nodes.items(.data);
return tree.extra_data[nodes_data[0].lhs..nodes_data[0].rhs];
}
pub fn renderError(tree: Ast, parse_error: Error, stream: anytype) !void {
const token_tags = tree.tokens.items(.tag);
switch (parse_error.tag) {
.asterisk_after_ptr_deref => {
// Note that the token will point at the `.*` but ideally the source
// location would point to the `*` after the `.*`.
return stream.writeAll("'.*' cannot be followed by '*'. Are you missing a space?");
},
.chained_comparison_operators => {
return stream.writeAll("comparison operators cannot be chained");
},
.decl_between_fields => {
return stream.writeAll("declarations are not allowed between container fields");
},
.expected_block => {
return stream.print("expected block, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_block_or_assignment => {
return stream.print("expected block or assignment, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_block_or_expr => {
return stream.print("expected block or expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_block_or_field => {
return stream.print("expected block or field, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_container_members => {
return stream.print("expected test, comptime, var decl, or container field, found '{s}'", .{
token_tags[parse_error.token].symbol(),
});
},
.expected_expr => {
return stream.print("expected expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_expr_or_assignment => {
return stream.print("expected expression or assignment, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_expr_or_var_decl => {
return stream.print("expected expression or var decl, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_fn => {
return stream.print("expected function, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_inlinable => {
return stream.print("expected 'while' or 'for', found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_labelable => {
return stream.print("expected 'while', 'for', 'inline', or '{{', found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_param_list => {
return stream.print("expected parameter list, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_prefix_expr => {
return stream.print("expected prefix expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_primary_type_expr => {
return stream.print("expected primary type expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_pub_item => {
return stream.writeAll("expected function or variable declaration after pub");
},
.expected_return_type => {
return stream.print("expected return type expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_semi_or_else => {
return stream.writeAll("expected ';' or 'else' after statement");
},
.expected_semi_or_lbrace => {
return stream.writeAll("expected ';' or block after function prototype");
},
.expected_statement => {
return stream.print("expected statement, found '{s}'", .{
token_tags[parse_error.token].symbol(),
});
},
.expected_suffix_op => {
return stream.print("expected pointer dereference, optional unwrap, or field access, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_type_expr => {
return stream.print("expected type expression, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_var_decl => {
return stream.print("expected variable declaration, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_var_decl_or_fn => {
return stream.print("expected variable declaration or function, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_loop_payload => {
return stream.print("expected loop payload, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.expected_container => {
return stream.print("expected a struct, enum or union, found '{s}'", .{
token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)].symbol(),
});
},
.extern_fn_body => {
return stream.writeAll("extern functions have no body");
},
.extra_addrspace_qualifier => {
return stream.writeAll("extra addrspace qualifier");
},
.extra_align_qualifier => {
return stream.writeAll("extra align qualifier");
},
.extra_allowzero_qualifier => {
return stream.writeAll("extra allowzero qualifier");
},
.extra_const_qualifier => {
return stream.writeAll("extra const qualifier");
},
.extra_volatile_qualifier => {
return stream.writeAll("extra volatile qualifier");
},
.ptr_mod_on_array_child_type => {
return stream.print("pointer modifier '{s}' not allowed on array child type", .{
token_tags[parse_error.token].symbol(),
});
},
.invalid_bit_range => {
return stream.writeAll("bit range not allowed on slices and arrays");
},
.same_line_doc_comment => {
return stream.writeAll("same line documentation comment");
},
.unattached_doc_comment => {
return stream.writeAll("unattached documentation comment");
},
.test_doc_comment => {
return stream.writeAll("documentation comments cannot be attached to tests");
},
.comptime_doc_comment => {
return stream.writeAll("documentation comments cannot be attached to comptime blocks");
},
.varargs_nonfinal => {
return stream.writeAll("function prototype has parameter after varargs");
},
.expected_continue_expr => {
return stream.writeAll("expected ':' before while continue expression");
},
.expected_semi_after_decl => {
return stream.writeAll("expected ';' after declaration");
},
.expected_semi_after_stmt => {
return stream.writeAll("expected ';' after statement");
},
.expected_comma_after_field => {
return stream.writeAll("expected ',' after field");
},
.expected_comma_after_arg => {
return stream.writeAll("expected ',' after argument");
},
.expected_comma_after_param => {
return stream.writeAll("expected ',' after parameter");
},
.expected_comma_after_initializer => {
return stream.writeAll("expected ',' after initializer");
},
.expected_comma_after_switch_prong => {
return stream.writeAll("expected ',' after switch prong");
},
.expected_comma_after_for_operand => {
return stream.writeAll("expected ',' after for operand");
},
.expected_comma_after_capture => {
return stream.writeAll("expected ',' after for capture");
},
.expected_initializer => {
return stream.writeAll("expected field initializer");
},
.mismatched_binary_op_whitespace => {
return stream.print("binary operator `{s}` has whitespace on one side, but not the other.", .{token_tags[parse_error.token].lexeme().?});
},
.invalid_ampersand_ampersand => {
return stream.writeAll("ambiguous use of '&&'; use 'and' for logical AND, or change whitespace to ' & &' for bitwise AND");
},
.c_style_container => {
return stream.print("'{s} {s}' is invalid", .{
parse_error.extra.expected_tag.symbol(), tree.tokenSlice(parse_error.token),
});
},
.zig_style_container => {
return stream.print("to declare a container do 'const {s} = {s}'", .{
tree.tokenSlice(parse_error.token), parse_error.extra.expected_tag.symbol(),
});
},
.previous_field => {
return stream.writeAll("field before declarations here");
},
.next_field => {
return stream.writeAll("field after declarations here");
},
.expected_var_const => {
return stream.writeAll("expected 'var' or 'const' before variable declaration");
},
.wrong_equal_var_decl => {
return stream.writeAll("variable initialized with '==' instead of '='");
},
.var_const_decl => {
return stream.writeAll("use 'var' or 'const' to declare variable");
},
.extra_for_capture => {
return stream.writeAll("extra capture in for loop");
},
.for_input_not_captured => {
return stream.writeAll("for input is not captured");
},
.expected_token => {
const found_tag = token_tags[parse_error.token + @intFromBool(parse_error.token_is_prev)];
const expected_symbol = parse_error.extra.expected_tag.symbol();
switch (found_tag) {
.invalid => return stream.print("expected '{s}', found invalid bytes", .{
expected_symbol,
}),
else => return stream.print("expected '{s}', found '{s}'", .{
expected_symbol, found_tag.symbol(),
}),
}
},
}
}
pub fn firstToken(tree: Ast, node: Node.Index) TokenIndex {
const tags = tree.nodes.items(.tag);
const datas = tree.nodes.items(.data);
const main_tokens = tree.nodes.items(.main_token);
const token_tags = tree.tokens.items(.tag);
var end_offset: TokenIndex = 0;
var n = node;
while (true) switch (tags[n]) {
.root => return 0,
.test_decl,
.@"errdefer",
.@"defer",
.bool_not,
.negation,
.bit_not,
.negation_wrap,
.address_of,
.@"try",
.@"await",
.optional_type,
.@"switch",
.switch_comma,
.if_simple,
.@"if",
.@"suspend",
.@"resume",
.@"continue",
.@"break",
.@"return",
.anyframe_type,
.identifier,
.anyframe_literal,
.char_literal,
.number_literal,
.unreachable_literal,
.string_literal,
.multiline_string_literal,
.grouped_expression,
.builtin_call_two,
.builtin_call_two_comma,
.builtin_call,
.builtin_call_comma,
.error_set_decl,
.@"comptime",
.@"nosuspend",
.asm_simple,
.@"asm",
.array_type,
.array_type_sentinel,
.error_value,
=> return main_tokens[n] - end_offset,
.array_init_dot,
.array_init_dot_comma,
.array_init_dot_two,
.array_init_dot_two_comma,
.struct_init_dot,
.struct_init_dot_comma,
.struct_init_dot_two,
.struct_init_dot_two_comma,
.enum_literal,
=> return main_tokens[n] - 1 - end_offset,
.@"catch",
.field_access,
.unwrap_optional,
.equal_equal,
.bang_equal,
.less_than,
.greater_than,
.less_or_equal,
.greater_or_equal,
.assign_mul,
.assign_div,
.assign_mod,
.assign_add,
.assign_sub,
.assign_shl,
.assign_shl_sat,
.assign_shr,
.assign_bit_and,
.assign_bit_xor,
.assign_bit_or,
.assign_mul_wrap,
.assign_add_wrap,
.assign_sub_wrap,
.assign_mul_sat,
.assign_add_sat,
.assign_sub_sat,
.assign,
.merge_error_sets,
.mul,
.div,
.mod,
.array_mult,
.mul_wrap,
.mul_sat,
.add,
.sub,
.array_cat,
.add_wrap,
.sub_wrap,
.add_sat,
.sub_sat,
.shl,
.shl_sat,
.shr,
.bit_and,
.bit_xor,
.bit_or,
.@"orelse",
.bool_and,
.bool_or,
.slice_open,
.slice,
.slice_sentinel,
.deref,
.array_access,
.array_init_one,
.array_init_one_comma,
.array_init,
.array_init_comma,
.struct_init_one,
.struct_init_one_comma,
.struct_init,
.struct_init_comma,
.call_one,
.call_one_comma,
.call,
.call_comma,
.switch_range,
.for_range,
.error_union,
=> n = datas[n].lhs,
.assign_destructure => {
const extra_idx = datas[n].lhs;
const lhs_len = tree.extra_data[extra_idx];
assert(lhs_len > 0);
n = tree.extra_data[extra_idx + 1];
},
.fn_decl,
.fn_proto_simple,
.fn_proto_multi,
.fn_proto_one,
.fn_proto,
=> {
var i = main_tokens[n]; // fn token
while (i > 0) {
i -= 1;
switch (token_tags[i]) {
.keyword_extern,
.keyword_export,
.keyword_pub,
.keyword_inline,
.keyword_noinline,
.string_literal,
=> continue,
else => return i + 1 - end_offset,
}
}
return i - end_offset;
},
.@"usingnamespace" => {
const main_token = main_tokens[n];
if (main_token > 0 and token_tags[main_token - 1] == .keyword_pub) {
end_offset += 1;
}
return main_token - end_offset;
},
.async_call_one,
.async_call_one_comma,
.async_call,
.async_call_comma,
=> {
end_offset += 1; // async token
n = datas[n].lhs;
},
.container_field_init,
.container_field_align,
.container_field,
=> {
const name_token = main_tokens[n];
if (name_token > 0 and token_tags[name_token - 1] == .keyword_comptime) {
end_offset += 1;
}
return name_token - end_offset;
},
.global_var_decl,
.local_var_decl,
.simple_var_decl,
.aligned_var_decl,
=> {
var i = main_tokens[n]; // mut token
while (i > 0) {
i -= 1;
switch (token_tags[i]) {
.keyword_extern,
.keyword_export,
.keyword_comptime,
.keyword_pub,
.keyword_threadlocal,
.string_literal,
=> continue,
else => return i + 1 - end_offset,
}
}
return i - end_offset;
},
.block,
.block_semicolon,
.block_two,
.block_two_semicolon,
=> {
// Look for a label.
const lbrace = main_tokens[n];
if (token_tags[lbrace - 1] == .colon and
token_tags[lbrace - 2] == .identifier)
{
end_offset += 2;
}
return lbrace - end_offset;
},
.container_decl,
.container_decl_trailing,
.container_decl_two,
.container_decl_two_trailing,
.container_decl_arg,
.container_decl_arg_trailing,
.tagged_union,
.tagged_union_trailing,
.tagged_union_two,
.tagged_union_two_trailing,
.tagged_union_enum_tag,
.tagged_union_enum_tag_trailing,
=> {
const main_token = main_tokens[n];
switch (token_tags[main_token -| 1]) {
.keyword_packed, .keyword_extern => end_offset += 1,
else => {},
}
return main_token - end_offset;
},
.ptr_type_aligned,
.ptr_type_sentinel,
.ptr_type,
.ptr_type_bit_range,
=> {
const main_token = main_tokens[n];
return switch (token_tags[main_token]) {
.asterisk,
.asterisk_asterisk,
=> switch (token_tags[main_token -| 1]) {
.l_bracket => main_token -| 1,
else => main_token,
},
.l_bracket => main_token,
else => unreachable,
} - end_offset;
},
.switch_case_one => {
if (datas[n].lhs == 0) {
return main_tokens[n] - 1 - end_offset; // else token
} else {
n = datas[n].lhs;
}
},
.switch_case_inline_one => {
if (datas[n].lhs == 0) {
return main_tokens[n] - 2 - end_offset; // else token
} else {
return firstToken(tree, datas[n].lhs) - 1;
}
},
.switch_case => {
const extra = tree.extraData(datas[n].lhs, Node.SubRange);
assert(extra.end - extra.start > 0);
n = tree.extra_data[extra.start];
},
.switch_case_inline => {
const extra = tree.extraData(datas[n].lhs, Node.SubRange);
assert(extra.end - extra.start > 0);
return firstToken(tree, tree.extra_data[extra.start]) - 1;
},
.asm_output, .asm_input => {
assert(token_tags[main_tokens[n] - 1] == .l_bracket);
return main_tokens[n] - 1 - end_offset;
},
.while_simple,
.while_cont,
.@"while",
.for_simple,
.@"for",
=> {
// Look for a label and inline.
const main_token = main_tokens[n];
var result = main_token;
if (token_tags[result -| 1] == .keyword_inline) {
result -= 1;
}
if (token_tags[result -| 1] == .colon) {
result -|= 2;
}
return result - end_offset;
},
};
}
pub fn lastToken(tree: Ast, node: Node.Index) TokenIndex {
const tags = tree.nodes.items(.tag);
const datas = tree.nodes.items(.data);
const main_tokens = tree.nodes.items(.main_token);
const token_starts = tree.tokens.items(.start);
const token_tags = tree.tokens.items(.tag);
var n = node;
var end_offset: TokenIndex = 0;
while (true) switch (tags[n]) {
.root => return @as(TokenIndex, @intCast(tree.tokens.len - 1)),
.@"usingnamespace",
.bool_not,
.negation,
.bit_not,
.negation_wrap,
.address_of,
.@"try",
.@"await",
.optional_type,
.@"resume",
.@"nosuspend",
.@"comptime",
=> n = datas[n].lhs,
.test_decl,
.@"errdefer",
.@"defer",
.@"catch",
.equal_equal,
.bang_equal,
.less_than,
.greater_than,
.less_or_equal,
.greater_or_equal,
.assign_mul,
.assign_div,
.assign_mod,
.assign_add,
.assign_sub,
.assign_shl,
.assign_shl_sat,
.assign_shr,
.assign_bit_and,
.assign_bit_xor,
.assign_bit_or,
.assign_mul_wrap,
.assign_add_wrap,
.assign_sub_wrap,
.assign_mul_sat,
.assign_add_sat,
.assign_sub_sat,
.assign,
.assign_destructure,
.merge_error_sets,
.mul,
.div,
.mod,
.array_mult,
.mul_wrap,
.mul_sat,
.add,
.sub,
.array_cat,
.add_wrap,
.sub_wrap,
.add_sat,
.sub_sat,
.shl,
.shl_sat,
.shr,
.bit_and,
.bit_xor,
.bit_or,
.@"orelse",
.bool_and,
.bool_or,
.anyframe_type,
.error_union,
.if_simple,
.while_simple,
.for_simple,
.fn_proto_simple,
.fn_proto_multi,
.ptr_type_aligned,
.ptr_type_sentinel,
.ptr_type,
.ptr_type_bit_range,
.array_type,
.switch_case_one,
.switch_case_inline_one,
.switch_case,
.switch_case_inline,
.switch_range,
=> n = datas[n].rhs,
.for_range => if (datas[n].rhs != 0) {
n = datas[n].rhs;
} else {
return main_tokens[n] + end_offset;
},
.field_access,
.unwrap_optional,
.grouped_expression,
.multiline_string_literal,
.error_set_decl,
.asm_simple,
.asm_output,
.asm_input,
.error_value,
=> return datas[n].rhs + end_offset,
.anyframe_literal,
.char_literal,
.number_literal,
.unreachable_literal,
.identifier,
.deref,
.enum_literal,
.string_literal,
=> return main_tokens[n] + end_offset,
.@"return" => if (datas[n].lhs != 0) {
n = datas[n].lhs;
} else {
return main_tokens[n] + end_offset;
},
.call, .async_call => {
end_offset += 1; // for the rparen
const params = tree.extraData(datas[n].rhs, Node.SubRange);
if (params.end - params.start == 0) {
return main_tokens[n] + end_offset;
}
n = tree.extra_data[params.end - 1]; // last parameter
},
.tagged_union_enum_tag => {
const members = tree.extraData(datas[n].rhs, Node.SubRange);
if (members.end - members.start == 0) {
end_offset += 4; // for the rparen + rparen + lbrace + rbrace
n = datas[n].lhs;
} else {
end_offset += 1; // for the rbrace
n = tree.extra_data[members.end - 1]; // last parameter
}
},
.call_comma,
.async_call_comma,
.tagged_union_enum_tag_trailing,
=> {
end_offset += 2; // for the comma/semicolon + rparen/rbrace
const params = tree.extraData(datas[n].rhs, Node.SubRange);
assert(params.end > params.start);
n = tree.extra_data[params.end - 1]; // last parameter
},
.@"switch" => {
const cases = tree.extraData(datas[n].rhs, Node.SubRange);
if (cases.end - cases.start == 0) {
end_offset += 3; // rparen, lbrace, rbrace
n = datas[n].lhs; // condition expression
} else {
end_offset += 1; // for the rbrace
n = tree.extra_data[cases.end - 1]; // last case
}
},
.container_decl_arg => {
const members = tree.extraData(datas[n].rhs, Node.SubRange);
if (members.end - members.start == 0) {
end_offset += 3; // for the rparen + lbrace + rbrace
n = datas[n].lhs;
} else {
end_offset += 1; // for the rbrace
n = tree.extra_data[members.end - 1]; // last parameter
}
},
.@"asm" => {
const extra = tree.extraData(datas[n].rhs, Node.Asm);
return extra.rparen + end_offset;
},
.array_init,
.struct_init,
=> {
const elements = tree.extraData(datas[n].rhs, Node.SubRange);
assert(elements.end - elements.start > 0);
end_offset += 1; // for the rbrace
n = tree.extra_data[elements.end - 1]; // last element
},
.array_init_comma,
.struct_init_comma,
.container_decl_arg_trailing,
.switch_comma,
=> {
const members = tree.extraData(datas[n].rhs, Node.SubRange);
assert(members.end - members.start > 0);
end_offset += 2; // for the comma + rbrace
n = tree.extra_data[members.end - 1]; // last parameter
},
.array_init_dot,
.struct_init_dot,
.block,
.container_decl,
.tagged_union,
.builtin_call,