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
|
const std = @import("std");
const assert = std.debug.assert;
const log = std.log.scoped(.yaml);
const mem = std.mem;
const Allocator = mem.Allocator;
const Tokenizer = @import("Tokenizer.zig");
const Token = Tokenizer.Token;
const TokenIndex = Tokenizer.TokenIndex;
const TokenIterator = Tokenizer.TokenIterator;
pub const ParseError = error{
InvalidEscapeSequence,
MalformedYaml,
NestedDocuments,
UnexpectedEof,
UnexpectedToken,
Unhandled,
} || Allocator.Error;
pub const Node = struct {
tag: Tag,
tree: *const Tree,
start: TokenIndex,
end: TokenIndex,
pub const Tag = enum {
doc,
map,
list,
value,
pub fn Type(comptime tag: Tag) type {
return switch (tag) {
.doc => Doc,
.map => Map,
.list => List,
.value => Value,
};
}
};
pub fn cast(self: *const Node, comptime T: type) ?*const T {
if (self.tag != T.base_tag) {
return null;
}
return @fieldParentPtr("base", self);
}
pub fn deinit(self: *Node, allocator: Allocator) void {
switch (self.tag) {
inline else => |tag| {
const parent: *tag.Type() = @fieldParentPtr("base", self);
parent.deinit(allocator);
allocator.destroy(parent);
},
}
}
pub fn format(
self: *const Node,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
switch (self.tag) {
inline else => |tag| return @as(*tag.Type(), @fieldParentPtr("base", self)).format(fmt, options, writer),
}
}
pub const Doc = struct {
base: Node = Node{
.tag = Tag.doc,
.tree = undefined,
.start = undefined,
.end = undefined,
},
directive: ?TokenIndex = null,
value: ?*Node = null,
pub const base_tag: Node.Tag = .doc;
pub fn deinit(self: *Doc, allocator: Allocator) void {
if (self.value) |node| {
node.deinit(allocator);
}
}
pub fn format(
self: *const Doc,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
if (self.directive) |id| {
try std.fmt.format(writer, "{{ ", .{});
const directive = self.base.tree.getRaw(id, id);
try std.fmt.format(writer, ".directive = {s}, ", .{directive});
}
if (self.value) |node| {
try std.fmt.format(writer, "{}", .{node});
}
if (self.directive != null) {
try std.fmt.format(writer, " }}", .{});
}
}
};
pub const Map = struct {
base: Node = Node{
.tag = Tag.map,
.tree = undefined,
.start = undefined,
.end = undefined,
},
values: std.ArrayListUnmanaged(Entry) = .{},
pub const base_tag: Node.Tag = .map;
pub const Entry = struct {
key: TokenIndex,
value: ?*Node,
};
pub fn deinit(self: *Map, allocator: Allocator) void {
for (self.values.items) |entry| {
if (entry.value) |value| {
value.deinit(allocator);
}
}
self.values.deinit(allocator);
}
pub fn format(
self: *const Map,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
try std.fmt.format(writer, "{{ ", .{});
for (self.values.items) |entry| {
const key = self.base.tree.getRaw(entry.key, entry.key);
if (entry.value) |value| {
try std.fmt.format(writer, "{s} => {}, ", .{ key, value });
} else {
try std.fmt.format(writer, "{s} => null, ", .{key});
}
}
return std.fmt.format(writer, " }}", .{});
}
};
pub const List = struct {
base: Node = Node{
.tag = Tag.list,
.tree = undefined,
.start = undefined,
.end = undefined,
},
values: std.ArrayListUnmanaged(*Node) = .{},
pub const base_tag: Node.Tag = .list;
pub fn deinit(self: *List, allocator: Allocator) void {
for (self.values.items) |node| {
node.deinit(allocator);
}
self.values.deinit(allocator);
}
pub fn format(
self: *const List,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
try std.fmt.format(writer, "[ ", .{});
for (self.values.items) |node| {
try std.fmt.format(writer, "{}, ", .{node});
}
return std.fmt.format(writer, " ]", .{});
}
};
pub const Value = struct {
base: Node = Node{
.tag = Tag.value,
.tree = undefined,
.start = undefined,
.end = undefined,
},
string_value: std.ArrayListUnmanaged(u8) = .{},
pub const base_tag: Node.Tag = .value;
pub fn deinit(self: *Value, allocator: Allocator) void {
self.string_value.deinit(allocator);
}
pub fn format(
self: *const Value,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
const raw = self.base.tree.getRaw(self.base.start, self.base.end);
return std.fmt.format(writer, "{s}", .{raw});
}
};
};
pub const LineCol = struct {
line: usize,
col: usize,
};
pub const Tree = struct {
allocator: Allocator,
source: []const u8,
tokens: []Token,
line_cols: std.AutoHashMap(TokenIndex, LineCol),
docs: std.ArrayListUnmanaged(*Node) = .{},
pub fn init(allocator: Allocator) Tree {
return .{
.allocator = allocator,
.source = undefined,
.tokens = undefined,
.line_cols = std.AutoHashMap(TokenIndex, LineCol).init(allocator),
};
}
pub fn deinit(self: *Tree) void {
self.allocator.free(self.tokens);
self.line_cols.deinit();
for (self.docs.items) |doc| {
doc.deinit(self.allocator);
}
self.docs.deinit(self.allocator);
}
pub fn getDirective(self: Tree, doc_index: usize) ?[]const u8 {
assert(doc_index < self.docs.items.len);
const doc = self.docs.items[doc_index].cast(Node.Doc) orelse return null;
const id = doc.directive orelse return null;
return self.getRaw(id, id);
}
pub fn getRaw(self: Tree, start: TokenIndex, end: TokenIndex) []const u8 {
assert(start <= end);
assert(start < self.tokens.len and end < self.tokens.len);
const start_token = self.tokens[start];
const end_token = self.tokens[end];
return self.source[start_token.start..end_token.end];
}
pub fn parse(self: *Tree, source: []const u8) !void {
var tokenizer = Tokenizer{ .buffer = source };
var tokens = std.ArrayList(Token).init(self.allocator);
defer tokens.deinit();
var line: usize = 0;
var prev_line_last_col: usize = 0;
while (true) {
const token = tokenizer.next();
const tok_id = tokens.items.len;
try tokens.append(token);
try self.line_cols.putNoClobber(tok_id, .{
.line = line,
.col = token.start - prev_line_last_col,
});
switch (token.id) {
.eof => break,
.new_line => {
line += 1;
prev_line_last_col = token.end;
},
else => {},
}
}
self.source = source;
self.tokens = try tokens.toOwnedSlice();
var it = TokenIterator{ .buffer = self.tokens };
var parser = Parser{
.allocator = self.allocator,
.tree = self,
.token_it = &it,
.line_cols = &self.line_cols,
};
parser.eatCommentsAndSpace(&.{});
while (true) {
parser.eatCommentsAndSpace(&.{});
const token = parser.token_it.next() orelse break;
log.debug("(main) next {s}@{d}", .{ @tagName(token.id), parser.token_it.pos - 1 });
switch (token.id) {
.eof => break,
else => {
parser.token_it.seekBy(-1);
const doc = try parser.doc();
try self.docs.append(self.allocator, doc);
},
}
}
}
};
const Parser = struct {
allocator: Allocator,
tree: *Tree,
token_it: *TokenIterator,
line_cols: *const std.AutoHashMap(TokenIndex, LineCol),
fn value(self: *Parser) ParseError!?*Node {
self.eatCommentsAndSpace(&.{});
const pos = self.token_it.pos;
const token = self.token_it.next() orelse return error.UnexpectedEof;
log.debug(" next {s}@{d}", .{ @tagName(token.id), pos });
switch (token.id) {
.literal => if (self.eatToken(.map_value_ind, &.{ .new_line, .comment })) |_| {
// map
self.token_it.seekTo(pos);
return self.map();
} else {
// leaf value
self.token_it.seekTo(pos);
return self.leaf_value();
},
.single_quoted, .double_quoted => {
// leaf value
self.token_it.seekBy(-1);
return self.leaf_value();
},
.seq_item_ind => {
// list
self.token_it.seekBy(-1);
return self.list();
},
.flow_seq_start => {
// list
self.token_it.seekBy(-1);
return self.list_bracketed();
},
else => return null,
}
}
fn doc(self: *Parser) ParseError!*Node {
const node = try self.allocator.create(Node.Doc);
errdefer self.allocator.destroy(node);
node.* = .{};
node.base.tree = self.tree;
node.base.start = self.token_it.pos;
log.debug("(doc) begin {s}@{d}", .{ @tagName(self.tree.tokens[node.base.start].id), node.base.start });
// Parse header
const explicit_doc: bool = if (self.eatToken(.doc_start, &.{})) |doc_pos| explicit_doc: {
if (self.getCol(doc_pos) > 0) return error.MalformedYaml;
if (self.eatToken(.tag, &.{ .new_line, .comment })) |_| {
node.directive = try self.expectToken(.literal, &.{ .new_line, .comment });
}
break :explicit_doc true;
} else false;
// Parse value
node.value = try self.value();
if (node.value == null) {
self.token_it.seekBy(-1);
}
errdefer if (node.value) |val| {
val.deinit(self.allocator);
};
// Parse footer
footer: {
if (self.eatToken(.doc_end, &.{})) |pos| {
if (!explicit_doc) return error.UnexpectedToken;
if (self.getCol(pos) > 0) return error.MalformedYaml;
node.base.end = pos;
break :footer;
}
if (self.eatToken(.doc_start, &.{})) |pos| {
if (!explicit_doc) return error.UnexpectedToken;
if (self.getCol(pos) > 0) return error.MalformedYaml;
self.token_it.seekBy(-1);
node.base.end = pos - 1;
break :footer;
}
if (self.eatToken(.eof, &.{})) |pos| {
node.base.end = pos - 1;
break :footer;
}
return error.UnexpectedToken;
}
log.debug("(doc) end {s}@{d}", .{ @tagName(self.tree.tokens[node.base.end].id), node.base.end });
return &node.base;
}
fn map(self: *Parser) ParseError!*Node {
const node = try self.allocator.create(Node.Map);
errdefer self.allocator.destroy(node);
node.* = .{};
node.base.tree = self.tree;
node.base.start = self.token_it.pos;
errdefer {
for (node.values.items) |entry| {
if (entry.value) |val| {
val.deinit(self.allocator);
}
}
node.values.deinit(self.allocator);
}
log.debug("(map) begin {s}@{d}", .{ @tagName(self.tree.tokens[node.base.start].id), node.base.start });
const col = self.getCol(node.base.start);
while (true) {
self.eatCommentsAndSpace(&.{});
// Parse key
const key_pos = self.token_it.pos;
if (self.getCol(key_pos) < col) {
break;
}
const key = self.token_it.next() orelse return error.UnexpectedEof;
switch (key.id) {
.literal => {},
.doc_start, .doc_end, .eof => {
self.token_it.seekBy(-1);
break;
},
else => {
// TODO key not being a literal
return error.Unhandled;
},
}
log.debug("(map) key {s}@{d}", .{ self.tree.getRaw(key_pos, key_pos), key_pos });
// Separator
_ = try self.expectToken(.map_value_ind, &.{ .new_line, .comment });
// Parse value
const val = try self.value();
errdefer if (val) |v| {
v.deinit(self.allocator);
};
if (val) |v| {
if (self.getCol(v.start) < self.getCol(key_pos)) {
return error.MalformedYaml;
}
if (v.cast(Node.Value)) |_| {
if (self.getCol(v.start) == self.getCol(key_pos)) {
return error.MalformedYaml;
}
}
}
try node.values.append(self.allocator, .{
.key = key_pos,
.value = val,
});
}
node.base.end = self.token_it.pos - 1;
log.debug("(map) end {s}@{d}", .{ @tagName(self.tree.tokens[node.base.end].id), node.base.end });
return &node.base;
}
fn list(self: *Parser) ParseError!*Node {
const node = try self.allocator.create(Node.List);
errdefer self.allocator.destroy(node);
node.* = .{};
node.base.tree = self.tree;
node.base.start = self.token_it.pos;
errdefer {
for (node.values.items) |val| {
val.deinit(self.allocator);
}
node.values.deinit(self.allocator);
}
log.debug("(list) begin {s}@{d}", .{ @tagName(self.tree.tokens[node.base.start].id), node.base.start });
while (true) {
self.eatCommentsAndSpace(&.{});
_ = self.eatToken(.seq_item_ind, &.{}) orelse break;
const val = (try self.value()) orelse return error.MalformedYaml;
try node.values.append(self.allocator, val);
}
node.base.end = self.token_it.pos - 1;
log.debug("(list) end {s}@{d}", .{ @tagName(self.tree.tokens[node.base.end].id), node.base.end });
return &node.base;
}
fn list_bracketed(self: *Parser) ParseError!*Node {
const node = try self.allocator.create(Node.List);
errdefer self.allocator.destroy(node);
node.* = .{};
node.base.tree = self.tree;
node.base.start = self.token_it.pos;
errdefer {
for (node.values.items) |val| {
val.deinit(self.allocator);
}
node.values.deinit(self.allocator);
}
log.debug("(list) begin {s}@{d}", .{ @tagName(self.tree.tokens[node.base.start].id), node.base.start });
_ = try self.expectToken(.flow_seq_start, &.{});
while (true) {
self.eatCommentsAndSpace(&.{.comment});
if (self.eatToken(.flow_seq_end, &.{.comment})) |pos| {
node.base.end = pos;
break;
}
_ = self.eatToken(.comma, &.{.comment});
const val = (try self.value()) orelse return error.MalformedYaml;
try node.values.append(self.allocator, val);
}
log.debug("(list) end {s}@{d}", .{ @tagName(self.tree.tokens[node.base.end].id), node.base.end });
return &node.base;
}
fn leaf_value(self: *Parser) ParseError!*Node {
const node = try self.allocator.create(Node.Value);
errdefer self.allocator.destroy(node);
node.* = .{ .string_value = .{} };
node.base.tree = self.tree;
node.base.start = self.token_it.pos;
errdefer node.string_value.deinit(self.allocator);
// TODO handle multiline strings in new block scope
while (self.token_it.next()) |tok| {
switch (tok.id) {
.single_quoted => {
node.base.end = self.token_it.pos - 1;
const raw = self.tree.getRaw(node.base.start, node.base.end);
try self.parseSingleQuoted(node, raw);
break;
},
.double_quoted => {
node.base.end = self.token_it.pos - 1;
const raw = self.tree.getRaw(node.base.start, node.base.end);
try self.parseDoubleQuoted(node, raw);
break;
},
.literal => {},
.space => {
const trailing = self.token_it.pos - 2;
self.eatCommentsAndSpace(&.{});
if (self.token_it.peek()) |peek| {
if (peek.id != .literal) {
node.base.end = trailing;
const raw = self.tree.getRaw(node.base.start, node.base.end);
try node.string_value.appendSlice(self.allocator, raw);
break;
}
}
},
else => {
self.token_it.seekBy(-1);
node.base.end = self.token_it.pos - 1;
const raw = self.tree.getRaw(node.base.start, node.base.end);
try node.string_value.appendSlice(self.allocator, raw);
break;
},
}
}
log.debug("(leaf) {s}", .{self.tree.getRaw(node.base.start, node.base.end)});
return &node.base;
}
fn eatCommentsAndSpace(self: *Parser, comptime exclusions: []const Token.Id) void {
log.debug("eatCommentsAndSpace", .{});
outer: while (self.token_it.next()) |token| {
log.debug(" (token '{s}')", .{@tagName(token.id)});
switch (token.id) {
.comment, .space, .new_line => |space| {
inline for (exclusions) |excl| {
if (excl == space) {
self.token_it.seekBy(-1);
break :outer;
}
} else continue;
},
else => {
self.token_it.seekBy(-1);
break;
},
}
}
}
fn eatToken(self: *Parser, id: Token.Id, comptime exclusions: []const Token.Id) ?TokenIndex {
log.debug("eatToken('{s}')", .{@tagName(id)});
self.eatCommentsAndSpace(exclusions);
const pos = self.token_it.pos;
const token = self.token_it.next() orelse return null;
if (token.id == id) {
log.debug(" (found at {d})", .{pos});
return pos;
} else {
log.debug(" (not found)", .{});
self.token_it.seekBy(-1);
return null;
}
}
fn expectToken(self: *Parser, id: Token.Id, comptime exclusions: []const Token.Id) ParseError!TokenIndex {
log.debug("expectToken('{s}')", .{@tagName(id)});
return self.eatToken(id, exclusions) orelse error.UnexpectedToken;
}
fn getLine(self: *Parser, index: TokenIndex) usize {
return self.line_cols.get(index).?.line;
}
fn getCol(self: *Parser, index: TokenIndex) usize {
return self.line_cols.get(index).?.col;
}
fn parseSingleQuoted(self: *Parser, node: *Node.Value, raw: []const u8) ParseError!void {
assert(raw[0] == '\'' and raw[raw.len - 1] == '\'');
const raw_no_quotes = raw[1 .. raw.len - 1];
try node.string_value.ensureTotalCapacity(self.allocator, raw_no_quotes.len);
var state: enum {
start,
escape,
} = .start;
var index: usize = 0;
while (index < raw_no_quotes.len) : (index += 1) {
const c = raw_no_quotes[index];
switch (state) {
.start => switch (c) {
'\'' => {
state = .escape;
},
else => {
node.string_value.appendAssumeCapacity(c);
},
},
.escape => switch (c) {
'\'' => {
state = .start;
node.string_value.appendAssumeCapacity(c);
},
else => return error.InvalidEscapeSequence,
},
}
}
}
fn parseDoubleQuoted(self: *Parser, node: *Node.Value, raw: []const u8) ParseError!void {
assert(raw[0] == '"' and raw[raw.len - 1] == '"');
const raw_no_quotes = raw[1 .. raw.len - 1];
try node.string_value.ensureTotalCapacity(self.allocator, raw_no_quotes.len);
var state: enum {
start,
escape,
} = .start;
var index: usize = 0;
while (index < raw_no_quotes.len) : (index += 1) {
const c = raw_no_quotes[index];
switch (state) {
.start => switch (c) {
'\\' => {
state = .escape;
},
else => {
node.string_value.appendAssumeCapacity(c);
},
},
.escape => switch (c) {
'n' => {
state = .start;
node.string_value.appendAssumeCapacity('\n');
},
't' => {
state = .start;
node.string_value.appendAssumeCapacity('\t');
},
'"' => {
state = .start;
node.string_value.appendAssumeCapacity('"');
},
else => return error.InvalidEscapeSequence,
},
}
}
}
};
test {
std.testing.refAllDecls(@This());
_ = @import("parse/test.zig");
}
|