forked from alichay/zig-wasm3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgyro_plugin.zig
1821 lines (1698 loc) · 71.8 KB
/
gyro_plugin.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
const std = @import("std");
const submod_build_plugin = @import("submod_build_plugin.zig");
fn getWasm3Src() []const u8 {
const sep = std.fs.path.sep_str;
const gyro_dir = comptime get_gyro: {
const parent_dir = std.fs.path.dirname(@src().file).?;
const maybe_clone_hash_dir = std.fs.path.dirname(parent_dir);
const maybe_gyro_dir = if(maybe_clone_hash_dir) |d| std.fs.path.dirname(d) else null;
if(std.ascii.eqlIgnoreCase(std.fs.path.basename(parent_dir), "pkg") and maybe_gyro_dir != null and
std.ascii.eqlIgnoreCase(std.fs.path.basename(maybe_gyro_dir.?), ".gyro")) {
break :get_gyro maybe_gyro_dir.?;
} else {
break :get_gyro std.fs.path.dirname(@src().file).? ++ sep ++ ".gyro";
}
};
const gyro_zzz_src = @embedFile("gyro.zzz");
const path = [_][]const u8{"deps", "wasm3_csrc", "git", "ref"};
var tree = zzz.ZTree(1, 100){};
var config_node = tree.appendText(gyro_zzz_src) catch unreachable;
for(path) |key| {
config_node = config_node.findNth(0, .{.String = key}) orelse unreachable;
}
return std.mem.join(std.heap.page_allocator, "", &.{gyro_dir, sep, "wasm3-wasm3-github.com-", config_node.child.?.value.String[0..8], sep, "pkg"}) catch unreachable;
}
fn repoDir(b: *std.build.Builder) []const u8 {
return std.fs.path.resolve(b.allocator, &[_][]const u8{b.build_root, getWasm3Src()}) catch unreachable;
}
/// Queues a build job for the C code of Wasm3.
/// This builds a static library that depends on libc, so make sure to link that into your exe!
pub fn compile(b: *std.build.Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.LibExeObjStep {
return submod_build_plugin.compile(b, mode, target, repoDir(b));
}
/// Compiles Wasm3 and links it into the provided exe.
/// If you use this API, you do not need to also use the compile() function.
pub fn addTo(exe: *std.build.LibExeObjStep) void {
submod_build_plugin.addTo(exe, repoDir(exe.builder));
}
pub const pkg = submod_build_plugin.pkg;
// We used to ship this as a dev dependency, but that dependency wasn't
// being resolved in client applications that used this library,
// so we have to just bundle and ship it ourselves.
const zzz = struct {
//! zzz format serializer and deserializer. public domain.
//!
//! StreamingParser inspired by Zig's JSON parser.
//!
//! SPARSE SPEC
//! (zzz text is escaped using Zig's multiline string: \\)
//!
//! zzz text describes a tree of strings. Special characters (and spaces) are used to go up and down
//! the tree. The tree has an implicit null root node.
//!
//! Descending the tree:
//! \\grandparent:parent:child:grandchild
//! Output:
//! null -> "grandparent" -> "parent" -> "child" -> "grandchild"
//!
//! Traversing the children of root (siblings):
//! \\sibling1,sibling2,sibling3
//! Output:
//! null -> "sibling1"
//! -> "sibling2"
//! -> "sibling3"
//!
//! Going up to the parent:
//! \\parent:child;anotherparent
//! Output:
//! null -> "parent" -> "child"
//! -> "anotherparent"
//!
//! White space and newlines are significant. A newline will take you back to the root:
//! \\parent:child
//! \\anotherparent
//! Output:
//! null -> "parent" -> "child"
//! -> "anotherparent"
//!
//! Exactly two spaces are used to to go down a level in the tree:
//! \\parent:child
//! \\ siblingtend
//! null -> "parent" -> "child"
//! -> "sibling"
//!
//! You can only go one level deeper than the previous line's depth. Anything more is an error:
//! \\parent:child
//! \\ sibling
//! Output: Error!
//!
//! Trailing commas, semicolons, and colons are optional. So the above (correct one) can be written
//! as:
//! \\parent
//! \\ child
//! \\ sibling
//! Output:
//! null -> "parent" -> "child"
//! -> "sibling"
//!
//! zzz can contain strings, integers (i32), floats (f32), boolean, and nulls:
//! \\string:42:42.0:true::
//! Output:
//! null -> "string" -> 42 -> 42.0 -> true -> null
//!
//! strings are trimmed, they may still contain spaces:
//! \\parent: child: grand child ;
//! Output:
//! null -> "parent" -> "child" -> "grand child"
//!
//! strings can be quoted with double quotes or Lua strings:
//! \\"parent":[[ child ]]:[==[grand child]=]]==];
//! Output:
//! null -> "parent" -> " child " -> "grand child]=]"
//!
//! Lua strings will skip the first empty newline:
//! \\[[
//! \\some text]]
//! Output:
//! null -> "some text"
//!
//! Strings are not escaped and taken "as-is".
//! \\"\n\t\r"
//! Output:
//! null -> "\n\t\r"
//!
//! Comments begin with # and run up to the end of the line. Their indentation follows the same
//! rules as nodes.
//! \\# A comment
//! \\a node
//! \\ # Another comment
//! \\ a sibling
//! Output:
//! null -> "a node" -> "a sibling"
/// The only output of the tokenizer.
pub const ZNodeToken = struct {
const Self = @This();
/// 0 is root, 1 is top level children.
depth: usize,
/// The extent of the slice.
start: usize,
end: usize,
};
/// Parses text outputting ZNodeTokens. Does not convert strings to numbers, and all strings are
/// "as is", no escaping is performed.
pub const StreamingParser = struct {
const Self = @This();
state: State,
start_index: usize,
current_index: usize,
// The maximum node depth.
max_depth: usize,
// The current line's depth.
line_depth: usize,
// The current node depth.
node_depth: usize,
/// Level of multiline string.
open_string_level: usize,
/// Current level of multiline string close.
close_string_level: usize,
/// Account for any extra spaces trailing at the end of a word.
trailing_spaces: usize,
pub const Error = error{
TooMuchIndentation,
InvalidWhitespace,
OddIndentationValue,
InvalidQuotation,
InvalidMultilineOpen,
InvalidMultilineClose,
InvalidNewLineInString,
InvalidCharacterAfterString,
SemicolonWentPastRoot,
UnexpectedEof,
};
pub const State = enum {
/// Whether we're starting on an openline.
OpenLine,
ExpectZNode,
Indent,
OpenCharacter,
Quotation,
SingleLineCharacter,
MultilineOpen0,
MultilineOpen1,
MultilineLevelOpen,
MultilineLevelClose,
MultilineClose0,
MultilineCharacter,
EndString,
OpenComment,
Comment,
};
/// Returns a blank parser.
pub fn init() Self {
var self: StreamingParser = undefined;
self.reset();
return self;
}
/// Resets the parser back to the beginning state.
pub fn reset(self: *Self) void {
self.state = .OpenLine;
self.start_index = 0;
self.current_index = 0;
self.max_depth = 0;
self.line_depth = 0;
self.node_depth = 0;
self.open_string_level = 0;
self.close_string_level = 0;
self.trailing_spaces = 0;
}
pub fn completeOrError(self: *const Self) !void {
switch (self.state) {
.ExpectZNode, .OpenLine, .EndString, .Comment, .OpenComment, .Indent => {},
else => return Error.UnexpectedEof,
}
}
/// Feeds a character to the parser. May output a ZNode. Check "hasCompleted" to see if there
/// are any unfinished strings.
pub fn feed(self: *Self, c: u8) Error!?ZNodeToken {
defer self.current_index += 1;
//std.debug.print("FEED<{}> {} {} ({c})\n", .{self.state, self.current_index, c, c});
switch (self.state) {
.OpenComment, .Comment => switch (c) {
'\n' => {
self.start_index = self.current_index + 1;
// We're ending a line with nodes.
if (self.state == .Comment) {
self.max_depth = self.line_depth + 1;
}
self.node_depth = 0;
self.line_depth = 0;
self.state = .OpenLine;
},
else => {
// Skip.
},
},
// All basically act the same except for a few minor differences.
.ExpectZNode, .OpenLine, .EndString, .OpenCharacter => switch (c) {
'#' => {
if (self.state == .OpenLine) {
self.state = .OpenComment;
} else {
defer self.state = .Comment;
if (self.state == .OpenCharacter) {
return ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.trailing_spaces,
};
}
}
},
// The tricky character (and other whitespace).
' ' => {
if (self.state == .OpenLine) {
if (self.line_depth >= self.max_depth) {
return Error.TooMuchIndentation;
}
self.state = .Indent;
} else if (self.state == .OpenCharacter) {
self.trailing_spaces += 1;
} else {
// Skip spaces when expecting a node on a closed line,
// including this one.
self.start_index = self.current_index + 1;
}
},
':' => {
defer self.state = .ExpectZNode;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.trailing_spaces,
};
self.start_index = self.current_index + 1;
self.node_depth += 1;
// Only return when we're not at end of a string.
if (self.state != .EndString) {
return node;
}
},
',' => {
defer self.state = .ExpectZNode;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.trailing_spaces,
};
self.start_index = self.current_index + 1;
// Only return when we're not at end of a string.
if (self.state != .EndString) {
return node;
}
},
';' => {
if (self.node_depth == 0) {
return Error.SemicolonWentPastRoot;
}
defer self.state = .ExpectZNode;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.trailing_spaces,
};
self.start_index = self.current_index + 1;
self.node_depth -= 1;
// Only return when we're not at end of a string, or in semicolons
// special case, when we don't have an empty string.
if (self.state != .EndString and node.start < node.end) {
return node;
}
},
'"' => {
if (self.state == .EndString) {
return Error.InvalidCharacterAfterString;
}
// Don't start another string.
if (self.state == .OpenCharacter) {
return null;
}
// We start here to account for the possibility of a string being ""
self.start_index = self.current_index + 1;
self.state = .Quotation;
},
'[' => {
if (self.state == .EndString) {
return Error.InvalidCharacterAfterString;
}
// Don't start another string.
if (self.state == .OpenCharacter) {
return null;
}
self.open_string_level = 0;
self.state = .MultilineOpen0;
},
'\n' => {
defer self.state = .OpenLine;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.trailing_spaces,
};
self.start_index = self.current_index + 1;
// Only reset on a non open line.
if (self.state != .OpenLine) {
self.max_depth = self.line_depth + 1;
self.line_depth = 0;
}
self.node_depth = 0;
// Only return something if there is something. Quoted strings are good.
if (self.state == .OpenCharacter) {
return node;
}
},
'\t', '\r' => {
return Error.InvalidWhitespace;
},
else => {
// We already have a string.
if (self.state == .EndString) {
return Error.InvalidCharacterAfterString;
}
// Don't reset if we're in a string.
if (self.state != .OpenCharacter) {
self.start_index = self.current_index;
}
self.trailing_spaces = 0;
self.state = .OpenCharacter;
},
},
.Indent => switch (c) {
' ' => {
self.start_index = self.current_index + 1;
self.line_depth += 1;
self.state = .OpenLine;
},
else => {
return Error.OddIndentationValue;
},
},
.Quotation => switch (c) {
'"' => {
self.state = .EndString;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index,
};
// Reset because we're going to expecting nodes.
self.start_index = self.current_index + 1;
return node;
},
else => {
self.state = .SingleLineCharacter;
},
},
.SingleLineCharacter => switch (c) {
'"' => {
self.state = .EndString;
const node = ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index,
};
// Reset because we're going to expecting nodes.
self.start_index = self.current_index + 1;
return node;
},
'\n' => {
return Error.InvalidNewLineInString;
},
else => {
// Consume.
},
},
.MultilineOpen0, .MultilineLevelOpen => switch (c) {
'=' => {
self.open_string_level += 1;
self.state = .MultilineLevelOpen;
},
'[' => {
self.start_index = self.current_index + 1;
self.state = .MultilineOpen1;
},
else => {
return Error.InvalidMultilineOpen;
},
},
.MultilineOpen1 => switch (c) {
']' => {
self.state = .MultilineClose0;
},
'\n' => {
// Skip first newline.
self.start_index = self.current_index + 1;
},
else => {
self.state = .MultilineCharacter;
},
},
.MultilineCharacter => switch (c) {
']' => {
self.close_string_level = 0;
self.state = .MultilineClose0;
},
else => {
// Capture EVERYTHING.
},
},
.MultilineClose0, .MultilineLevelClose => switch (c) {
'=' => {
self.close_string_level += 1;
self.state = .MultilineLevelClose;
},
']' => {
if (self.close_string_level == self.open_string_level) {
self.state = .EndString;
return ZNodeToken{
.depth = self.line_depth + self.node_depth + 1,
.start = self.start_index,
.end = self.current_index - self.open_string_level - 1,
};
}
self.state = .MultilineCharacter;
},
else => {
return Error.InvalidMultilineClose;
},
},
}
return null;
}
};
fn testNextTextOrError(stream: *StreamingParser, idx: *usize, text: []const u8) ![]const u8 {
while (idx.* < text.len) {
const node = try stream.feed(text[idx.*]);
idx.* += 1;
if (node) |n| {
//std.debug.print("TOKEN {}\n", .{text[n.start..n.end]});
return text[n.start..n.end];
}
}
return error.ExhaustedLoop;
}
test "parsing slice output" {
const testing = std.testing;
const text =
\\# woo comment
\\mp:10
\\[[sy]]
\\ # another
\\ : n : "en" , [[m]]
\\ "sc" : [[10]] , g #inline
\\ [[]]:[==[
\\hi]==]
;
var idx: usize = 0;
var stream = StreamingParser.init();
try testing.expectEqualSlices(u8, "mp", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "sy", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "n", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "en", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "m", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "sc", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "g", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text));
try testing.expectEqualSlices(u8, "hi", try testNextTextOrError(&stream, &idx, text));
}
fn testNextLevelOrError(stream: *StreamingParser, idx: *usize, text: []const u8) !usize {
while (idx.* < text.len) {
const node = try stream.feed(text[idx.*]);
idx.* += 1;
if (node) |n| {
return n.depth;
}
}
return error.ExhaustedLoop;
}
test "parsing depths" {
const testing = std.testing;
const text =
\\# woo comment
\\mp:10
\\[[sy]]
\\ # another
\\ : n : "en" , [[m]]
\\ # more
\\
\\ # even more
\\
\\ "sc" : [[10]] , g #inline
\\ [[]]:[==[
\\hi]==]
;
var idx: usize = 0;
var stream = StreamingParser.init();
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2);
try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3);
}
/// Parses the stream, outputting ZNodeTokens which reference the text.
pub fn parseStream(stream: *StreamingParser, idx: *usize, text: []const u8) !?ZNodeToken {
while (idx.* <= text.len) {
// Insert an extra newline at the end of the stream.
const node = if (idx.* == text.len) try stream.feed('\n') else try stream.feed(text[idx.*]);
idx.* += 1;
if (node) |n| {
return n;
}
}
return null;
}
/// A `ZNode`'s value.
pub const ZValue = union(enum) {
const Self = @This();
Null,
String: []const u8,
Int: i32,
Float: f32,
Bool: bool,
/// Checks a ZValues equality.
pub fn equals(self: Self, other: Self) bool {
if (self == .Null and other == .Null) {
return true;
}
if (self == .String and other == .String) {
return std.mem.eql(u8, self.String, other.String);
}
if (self == .Int and other == .Int) {
return self.Int == other.Int;
}
if (self == .Float and other == .Float) {
return std.math.approxEqAbs(f32, self.Float, other.Float, std.math.f32_epsilon);
}
if (self == .Bool and other == .Bool) {
return self.Bool == other.Bool;
}
return false;
}
/// Outputs a value to the `out_stream`. This output is parsable.
pub fn stringify(self: Self, out_stream: anytype) @TypeOf(out_stream).Error!void {
switch (self) {
.Null => {
// Skip.
},
.String => {
const find = std.mem.indexOfScalar;
const chars = "\"\n\t\r,:;";
const chars_count = @sizeOf(@TypeOf(chars));
var need_escape = false;
var found = [_]bool{false} ** chars_count;
for ("\"\n\t\r,:;") |ch, i| {
const f = find(u8, self.String, ch);
if (f != null) {
found[i] = true;
need_escape = true;
}
}
// TODO: Escaping ]] in string.
if (need_escape) {
// 0=" 1=\n
if (found[0] or found[1]) {
// Escape with Lua.
try out_stream.writeAll("[[");
const ret = try out_stream.writeAll(self.String);
try out_stream.writeAll("]]");
return ret;
} else {
// Escape with basic quotes.
try out_stream.writeAll("\"");
const ret = try out_stream.writeAll(self.String);
try out_stream.writeAll("\"");
return ret;
}
}
return try out_stream.writeAll(self.String);
},
.Int => {
return std.fmt.formatIntValue(self.Int, "", std.fmt.FormatOptions{}, out_stream);
},
.Float => {
return std.fmt.formatFloatScientific(self.Float, std.fmt.FormatOptions{}, out_stream);
},
.Bool => {
return out_stream.writeAll(if (self.Bool) "true" else "false");
},
}
}
///
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
switch (self) {
.Null => try std.fmt.format(writer, ".Null", .{}),
.String => try std.fmt.format(writer, ".String({s})", .{self.String}),
.Int => try std.fmt.format(writer, ".Int({})", .{self.Int}),
.Float => try std.fmt.format(writer, ".Float({})", .{self.Float}),
.Bool => try std.fmt.format(writer, ".Bool({})", .{self.Bool}),
}
}
};
/// Result of imprinting
pub fn Imprint(comptime T: type) type {
return struct {
result: T,
arena: std.heap.ArenaAllocator,
};
}
pub const ImprintError = error{
ExpectedBoolNode,
ExpectedFloatNode,
ExpectedUnsignedIntNode,
ExpectedIntNode,
ExpectedIntOrStringNode,
ExpectedStringNode,
FailedToConvertStringToEnum,
FailedToConvertIntToEnum,
FieldNodeDoesNotExist,
ValueNodeDoesNotExist,
ArrayElemDoesNotExist,
OutOfMemory,
InvalidPointerType,
InvalidType,
};
/// Represents a node in a static tree. Nodes have a parent, child, and sibling pointer
/// to a spot in the array.
pub const ZNode = struct {
const Self = @This();
value: ZValue = .Null,
parent: ?*ZNode = null,
sibling: ?*ZNode = null,
child: ?*ZNode = null,
/// Returns the next Node in the tree. Will return Null after reaching root. For nodes further
/// down the tree, they will bubble up, resulting in a negative depth. Self is considered to be
/// at depth 0.
pub fn next(self: *const Self, depth: *isize) ?*ZNode {
if (self.child) |c| {
depth.* += 1;
return c;
} else if (self.sibling) |c| {
return c;
} else {
// Go up and forward.
var iter: ?*const ZNode = self;
while (iter != null) {
iter = iter.?.parent;
if (iter != null) {
depth.* -= 1;
if (iter.?.sibling) |c| {
return c;
}
}
}
return null;
}
}
/// Returns the next node in the tree until reaching root or the stopper node.
pub fn nextUntil(self: *const Self, stopper: *const ZNode, depth: *isize) ?*ZNode {
if (self.child) |c| {
if (c == stopper) {
return null;
}
depth.* += 1;
return c;
} else if (self.sibling) |c| {
if (c == stopper) {
return null;
}
return c;
} else {
// Go up and forward.
var iter: ?*const ZNode = self;
while (iter != null) {
iter = iter.?.parent;
// All these checks. :/
if (iter == stopper) {
return null;
}
if (iter != null) {
depth.* -= 1;
if (iter.?.sibling) |c| {
if (c == stopper) {
return null;
}
return c;
}
}
}
return null;
}
}
/// Iterates this node's children. Pass null to start. `iter = node.nextChild(iter);`
pub fn nextChild(self: *const Self, iter: ?*const ZNode) ?*ZNode {
if (iter) |it| {
return it.sibling;
} else {
return self.child;
}
}
/// Returns the nth child's value. Or null if neither the node or child exist.
pub fn getChildValue(self: *const Self, nth: usize) ?ZValue {
var count: usize = 0;
var iter: ?*ZNode = self.child;
while (iter) |n| {
if (count == nth) {
if (n.child) |c| {
return c.value;
} else {
return null;
}
}
count += 1;
iter = n.sibling;
}
return null;
}
/// Returns the nth child. O(n)
pub fn getChild(self: *const Self, nth: usize) ?*ZNode {
var count: usize = 0;
var iter: ?*ZNode = self.child;
while (iter) |n| {
if (count == nth) {
return n;
}
count += 1;
iter = n.sibling;
}
return null;
}
/// Returns the number of children. O(n)
pub fn getChildCount(self: *const Self) usize {
var count: usize = 0;
var iter: ?*ZNode = self.child;
while (iter) |n| {
count += 1;
iter = n.sibling;
}
return count;
}
/// Finds the next child after the given iterator. This is good for when you can guess the order
/// of the nodes, which can cut down on starting from the beginning. Passing null starts over
/// from the beginning. Returns the found node or null (it will loop back around).
pub fn findNextChild(self: *const Self, start: ?*const ZNode, value: ZValue) ?*ZNode {
var iter: ?*ZNode = self.child;
if (start) |si| {
iter = si.sibling;
}
while (iter != start) {
if (iter) |it| {
if (it.value.equals(value)) {
return it;
}
iter = it.sibling;
} else {
// Loop back.
iter = self.child;
}
}
return null;
}
/// Finds the nth child node with a specific tag.
pub fn findNthAny(self: *const Self, nth: usize, tag: std.meta.Tag(ZValue)) ?*ZNode {
var count: usize = 0;
var iter: ?*ZNode = self.child;
while (iter) |n| {
if (n.value == tag) {
if (count == nth) {
return n;
}
count += 1;
}
iter = n.sibling;
}
return null;
}
/// Finds the nth child node with a specific value.
pub fn findNth(self: *const Self, nth: usize, value: ZValue) ?*ZNode {
var count: usize = 0;
var iter: ?*ZNode = self.child orelse return null;
while (iter) |n| {
if (n.value.equals(value)) {
if (count == nth) {
return n;
}
count += 1;
}
iter = n.sibling;
}
return null;
}
/// Traverses descendants until a node with the tag is found.
pub fn findNthAnyDescendant(self: *const Self, nth: usize, tag: std.meta.Tag(ZValue)) ?*ZNode {
var depth: isize = 0;
var count: usize = 0;
var iter: *const ZNode = self;
while (iter.nextUntil(self, &depth)) |n| : (iter = n) {
if (n.value == tag) {
if (count == nth) {
return n;
}
count += 1;
}
}
return null;
}
/// Traverses descendants until a node with the specific value is found.
pub fn findNthDescendant(self: *const Self, nth: usize, value: ZValue) ?*ZNode {
var depth: isize = 0;
var count: usize = 0;
var iter: *const ZNode = self;
while (iter.nextUntil(self, &depth)) |n| : (iter = n) {
if (n.value.equals(value)) {
if (count == nth) {
return n;
}
count += 1;
}
}
return null;
}
/// Converts strings to specific types. This just tries converting the string to an int, then
/// float, then bool. Booleans are only the string values "true" or "false".
pub fn convertStrings(self: *const Self) void {
var depth: isize = 0;
var iter: *const ZNode = self;
while (iter.nextUntil(self, &depth)) |c| : (iter = c) {
if (c.value != .String) {
continue;
}
// Try to cast to numbers, then true/false checks, then string.
const slice = c.value.String;
const integer = std.fmt.parseInt(i32, slice, 10) catch {
const float = std.fmt.parseFloat(f32, slice) catch {
if (std.mem.eql(u8, "true", slice)) {
c.value = ZValue{ .Bool = true };
} else if (std.mem.eql(u8, "false", slice)) {
c.value = ZValue{ .Bool = false };
} else {
// Keep the value.
}
continue;
};
c.value = ZValue{ .Float = float };
continue;
};
c.value = ZValue{ .Int = integer };
}
}
fn imprint_(self: *const Self, comptime T: type, allocator: ?*std.mem.Allocator) ImprintError!T {
const TI = @typeInfo(T);
switch (TI) {
.Void => {},
.Bool => {
return switch (self.value) {
.Bool => |b| b,
else => ImprintError.ExpectedBoolNode,
};
},
.Float, .ComptimeFloat => {
return switch (self.value) {
.Float => |n| @floatCast(T, n),
.Int => |n| @intToFloat(T, n),
else => ImprintError.ExpectedFloatNode,
};
},
.Int, .ComptimeInt => {
const is_signed = (TI == .Int and TI.Int.signedness == .signed) or (TI == .ComptimeInt and TI.CompTimeInt.is_signed);
switch (self.value) {
.Int => |n| {
if (is_signed) {
return @intCast(T, n);
} else {
if (n < 0) {
return ImprintError.ExpectedUnsignedIntNode;
}
return @intCast(T, n);
}
},
else => return ImprintError.ExpectedIntNode,
}
},
.Enum => {
switch (self.value) {
.Int => |int| {
return std.meta.intToEnum(T, int) catch {
return ImprintError.FailedToConvertIntToEnum;
};
},
.String => {
if (std.meta.stringToEnum(T, self.value.String)) |e| {
return e;
} else {
return ImprintError.FailedToConvertStringToEnum;
}
},
else => return ImprintError.ExpectedIntOrStringNode,
}
},
.Optional => |opt_info| {