| ... | @@ -0,0 +1,66 @@ |
| 1 | const std = @import("std.zig"); |
| 2 | const SegmentedList = std.SegmentedList; |
| 3 | const Token = std.c.Token; |
| 4 | const Source = std.c.tokenizer.Source; |
| 5 | |
| 6 | pub const TokenIndex = usize; |
| 7 | |
| 8 | pub const Tree = struct { |
| 9 | tokens: TokenList, |
| 10 | sources: SourceList, |
| 11 | root_node: *Node.Root, |
| 12 | arena_allocator: std.heap.ArenaAllocator, |
| 13 | errors: ErrorList, |
| 14 | |
| 15 | pub const SourceList = SegmentedList(Source, 4); |
| 16 | pub const TokenList = Source.TokenList; |
| 17 | pub const ErrorList = SegmentedList(Error, 0); |
| 18 | |
| 19 | pub fn deinit(self: *Tree) void { |
| 20 | // Here we copy the arena allocator into stack memory, because |
| 21 | // otherwise it would destroy itself while it was still working. |
| 22 | var arena_allocator = self.arena_allocator; |
| 23 | arena_allocator.deinit(); |
| 24 | // self is destroyed |
| 25 | } |
| 26 | }; |
| 27 | |
| 28 | pub const Error = union(enum) { |
| 29 | InvalidToken: InvalidToken, |
| 30 | |
| 31 | pub fn render(self: *const Error, tokens: *Tree.TokenList, stream: var) !void { |
| 32 | switch (self.*) { |
| 33 | .InvalidToken => |*x| return x.render(tokens, stream), |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn loc(self: *const Error) TokenIndex { |
| 38 | switch (self.*) { |
| 39 | .InvalidToken => |x| return x.token, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | pub const InvalidToken = SingleTokenError("Invalid token '{}'"); |
| 44 | |
| 45 | fn SingleTokenError(comptime msg: []const u8) type { |
| 46 | return struct { |
| 47 | token: TokenIndex, |
| 48 | |
| 49 | pub fn render(self: *const @This(), tokens: *Tree.TokenList, stream: var) !void { |
| 50 | const actual_token = tokens.at(self.token); |
| 51 | return stream.print(msg, .{actual_token.id.symbol()}); |
| 52 | } |
| 53 | }; |
| 54 | } |
| 55 | }; |
| 56 | |
| 57 | pub const Root = struct { |
| 58 | decls: DeclList, |
| 59 | eof_token: TokenIndex, |
| 60 | |
| 61 | pub const DeclList = SegmentedList(*Decl, 4); |
| 62 | }; |
| 63 | |
| 64 | pub const Decl = struct { |
| 65 | |
| 66 | }; |
| \ No newline at end of file |