This repository has been archived by the owner on Feb 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
tres.zig
1912 lines (1582 loc) · 70.4 KB
/
tres.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");
/// Validate with more granularity (for example, tres_string_enum makes no sense in a struct)
fn validateCustomDecls(comptime T: type) void {
const map = std.ComptimeStringMap(void, .{
.{ "tres_null_meaning", {} },
.{ "tres_string_enum", {} },
.{ "tres_remap", {} },
});
return switch (@typeInfo(T)) {
.Struct, .Enum, .Union => {
const decls = std.meta.declarations(T);
inline for (decls) |decl| {
if (map.has(decl.name) and !decl.is_pub) {
@compileError("Found '" ++ decl.name ++ "' in '" ++ @typeName(T) ++ "' but it isn't public!");
}
}
},
else => {},
};
}
/// Use after `isArrayList` and/or `isHashMap`
pub fn isManaged(comptime T: type) bool {
return @hasField(T, "allocator");
}
pub fn isArrayList(comptime T: type) bool {
// TODO: Improve this ArrayList check, specifically by actually checking the functions we use
// TODO: Consider unmanaged ArrayLists
if (!@hasField(T, "items")) return false;
if (!@hasField(T, "capacity")) return false;
return true;
}
pub fn isHashMap(comptime T: type) bool {
// TODO: Consider unmanaged HashMaps
if (!@hasDecl(T, "KV")) return false;
if (!@hasField(T.KV, "key")) return false;
if (!@hasField(T.KV, "value")) return false;
const Key = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "key") orelse unreachable].type;
const Value = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "value") orelse unreachable].type;
if (!@hasDecl(T, "put")) return false;
const put = @typeInfo(@TypeOf(T.put));
if (put != .Fn) return false;
switch (put.Fn.params.len) {
3 => {
if (put.Fn.params[0].type.? != *T) return false;
if (put.Fn.params[1].type.? != Key) return false;
if (put.Fn.params[2].type.? != Value) return false;
},
4 => {
if (put.Fn.params[0].type.? != *T) return false;
if (put.Fn.params[1].type.? != std.mem.Allocator) return false;
if (put.Fn.params[2].type.? != Key) return false;
if (put.Fn.params[3].type.? != Value) return false;
},
else => return false,
}
if (put.Fn.return_type == null) return false;
const put_return = @typeInfo(put.Fn.return_type.?);
if (put_return != .ErrorUnion) return false;
if (put_return.ErrorUnion.payload != void) return false;
return true;
}
test "isManaged, isArrayList, isHashMap" {
const T1 = std.ArrayList(u8);
try std.testing.expect(isArrayList(T1) and isManaged(T1));
const T2 = std.ArrayListUnmanaged(u8);
try std.testing.expect(isArrayList(T2) and !isManaged(T2));
const T3 = std.AutoHashMap(u8, u16);
try std.testing.expect(isHashMap(T3) and isManaged(T3));
const T4 = std.AutoHashMapUnmanaged(u8, u16);
try std.testing.expect(isHashMap(T4) and !isManaged(T4));
}
/// Arena recommended.
pub fn parse(comptime T: type, tree: std.json.Value, allocator: ?std.mem.Allocator) ParseInternalError(T)!T {
return try parseInternal(T, tree, allocator, false);
}
pub fn Undefinedable(comptime T: type) type {
return struct {
const __json_T = T;
const __json_is_undefinedable = true;
value: T,
missing: bool,
pub fn asOptional(self: @This()) ?T {
return if (self.missing)
null
else
self.value;
}
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
if (self.missing)
try writer.print("Undefinedable({s}){{ missing }}", .{@typeName(T)})
else {
try writer.print("Undefinedable({s}){{ .value = {any} }}", .{ @typeName(T), self.value });
}
}
};
}
const NullMeaning = enum {
/// ?T; a null leads to the field not being written
field,
/// ?T; a null leads to the field being written with the value null
value,
/// ??T; first null is field, second null is value
dual,
};
fn dualable(comptime T: type) bool {
return @typeInfo(T) == .Optional and @typeInfo(@typeInfo(T).Optional.child) == .Optional;
}
// TODO: Respect stringify options
fn nullMeaning(comptime T: type, comptime field: std.builtin.Type.StructField) ?NullMeaning {
const true_default = td: {
if (dualable(T)) break :td NullMeaning.dual;
break :td null;
};
if (!@hasDecl(T, "tres_null_meaning")) return true_default;
const tnm = @field(T, "tres_null_meaning");
if (!@hasField(@TypeOf(tnm), field.name)) return true_default;
return @field(tnm, field.name);
}
fn mightRemap(comptime T: type, comptime field: []const u8) []const u8 {
if (!@hasDecl(T, "tres_remap")) return field;
const remap = @field(T, "tres_remap");
if (!@hasField(@TypeOf(remap), field)) return field;
return @field(remap, field);
}
pub fn ParseInternalError(comptime T: type) type {
// `inferred_types` is used to avoid infinite recursion for recursive type definitions.
const inferred_types = [_]type{};
return ParseInternalErrorImpl(T, &inferred_types);
}
fn ParseInternalErrorImpl(comptime T: type, comptime inferred_types: []const type) type {
if (comptime std.meta.trait.isContainer(T) and @hasDecl(T, "tresParse")) {
const tresParse_return = @typeInfo(@typeInfo(@TypeOf(T.tresParse)).Fn.return_type.?);
if (tresParse_return == .ErrorUnion) {
return tresParse_return.ErrorUnion.error_set;
} else {
return error{};
}
}
for (inferred_types) |ty| {
if (T == ty) return error{};
}
const inferred_set = inferred_types ++ [_]type{T};
switch (@typeInfo(T)) {
.Bool, .Float => return error{UnexpectedFieldType},
.Int => return error{ UnexpectedFieldType, Overflow },
.Optional => |info| return ParseInternalErrorImpl(info.child, inferred_set),
.Enum => return error{ InvalidEnumTag, UnexpectedFieldType },
.Union => |info| {
var errors = error{UnexpectedFieldType};
for (info.fields) |field| {
errors = errors || ParseInternalErrorImpl(field.type, inferred_set);
}
return errors;
},
.Struct => |info| {
var errors = error{
UnexpectedFieldType,
InvalidFieldValue,
MissingRequiredField,
};
if (isArrayList(T)) {
const Child = std.meta.Child(@field(T, "Slice"));
errors = errors || ParseInternalErrorImpl(Child, inferred_set);
}
if (isHashMap(T)) {
const Value = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "value") orelse unreachable].type;
errors = errors || ParseInternalErrorImpl(Value, inferred_set);
}
if (isAllocatorRequired(T)) {
errors = errors || error{AllocatorRequired} || std.mem.Allocator.Error;
}
for (info.fields) |field| {
errors = errors || ParseInternalErrorImpl(field.type, inferred_set);
}
return errors;
},
.Pointer => |info| {
var errors = error{UnexpectedFieldType};
if (isAllocatorRequired(T)) {
errors = errors || error{AllocatorRequired} || std.mem.Allocator.Error;
}
if (info.size == .Slice and info.child == u8 or info.child == std.json.Value)
return errors;
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
.Array => |info| {
var errors = error{UnexpectedFieldType};
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
.Vector => |info| {
var errors = error{UnexpectedFieldType};
errors = errors || ParseInternalErrorImpl(info.child, inferred_set);
return errors;
},
else => return error{},
}
}
pub fn isAllocatorRequired(comptime T: type) bool {
// `inferred_types` is used to avoid infinite recursion for recursive type definitions.
const inferred_types = [_]type{};
return isAllocatorRequiredImpl(T, &inferred_types);
}
fn isAllocatorRequiredImpl(comptime T: type, comptime inferred_types: []const type) bool {
for (inferred_types) |ty| {
if (T == ty) return false;
}
const inferred_set = inferred_types ++ [_]type{T};
switch (@typeInfo(T)) {
.Optional => |info| return isAllocatorRequiredImpl(info.child, inferred_set),
.Union => |info| {
for (info.fields) |field| {
if (isAllocatorRequiredImpl(field.type, inferred_set))
return true;
}
},
.Struct => |info| {
if (isArrayList(T)) {
if (T == std.json.Array)
return false;
return true;
}
if (isHashMap(T)) {
if (T == std.json.ObjectMap)
return false;
return true;
}
for (info.fields) |field| {
if (@typeInfo(field.type) == .Struct and @hasDecl(field.type, "__json_is_undefinedable")) {
if (isAllocatorRequiredImpl(field.type.__json_T, inferred_set))
return true;
} else if (isAllocatorRequiredImpl(field.type, inferred_set))
return true;
}
},
.Pointer => |info| {
if (info.size == .Slice and info.child == u8 or info.child == std.json.Value)
return false;
return true;
},
.Array => |info| {
return isAllocatorRequiredImpl(info.child, inferred_set);
},
.Vector => |info| {
return isAllocatorRequiredImpl(info.child, inferred_set); // is it even possible for this to be true?
},
else => {},
}
return false;
}
const logger = std.log.scoped(.json);
fn parseInternal(
comptime T: type,
json_value: std.json.Value,
maybe_allocator: ?std.mem.Allocator,
comptime suppress_error_logs: bool,
) ParseInternalError(T)!T {
comptime validateCustomDecls(T);
if (T == std.json.Value) return json_value;
if (comptime std.meta.trait.isContainer(T) and @hasDecl(T, "tresParse")) {
return T.tresParse(json_value, maybe_allocator);
}
switch (@typeInfo(T)) {
.Bool => {
if (json_value == .bool) {
return json_value.bool;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Bool, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Float => {
if (json_value == .float) {
return @as(T, @floatCast(json_value.float));
} else if (json_value == .integer) {
return @as(T, @floatFromInt(json_value.integer));
} else {
if (comptime !suppress_error_logs) logger.debug("expected Float, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Int => {
if (json_value == .integer) {
return std.math.cast(T, json_value.integer) orelse return error.Overflow;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Integer, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Optional => |info| {
if (json_value == .null) {
return null;
} else {
return try parseInternal(
info.child,
json_value,
maybe_allocator,
suppress_error_logs,
);
}
},
.Enum => {
if (json_value == .integer) {
// we use this to convert signed to unsigned and check if it actually fits.
const tag = std.math.cast(std.meta.Tag(T), json_value.integer) orelse {
if (comptime !suppress_error_logs) logger.debug("invalid enum tag for {s}, found {d}", .{ @typeName(T), json_value.integer });
return error.InvalidEnumTag;
};
return try std.meta.intToEnum(T, tag);
} else if (json_value == .string) {
return std.meta.stringToEnum(T, json_value.string) orelse {
if (comptime !suppress_error_logs) logger.debug("invalid enum tag for {s}, found '{s}'", .{ @typeName(T), json_value.string });
return error.InvalidEnumTag;
};
} else {
if (comptime !suppress_error_logs) logger.debug("expected Integer or String, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Union => |info| {
if (info.tag_type != null) {
inline for (info.fields) |field| {
if (parseInternal(
field.type,
json_value,
maybe_allocator,
true,
)) |parsed_value| {
return @unionInit(T, field.name, parsed_value);
} else |_| {}
}
if (comptime !suppress_error_logs) logger.debug("union fell through for {s}, found {s}", .{ @typeName(T), @tagName(json_value) });
return error.UnexpectedFieldType;
} else {
@compileError("cannot parse an untagged union: " ++ @typeName(T));
}
},
.Struct => |info| {
if (comptime isArrayList(T)) {
const Child = std.meta.Child(@field(T, "Slice"));
if (json_value == .array) {
if (T == std.json.Array) return json_value.array;
const allocator = maybe_allocator orelse return error.AllocatorRequired;
var array_list = try T.initCapacity(allocator, json_value.array.capacity);
for (json_value.array.items) |item| {
if (comptime isManaged(T))
try array_list.append(try parseInternal(
Child,
item,
maybe_allocator,
suppress_error_logs,
))
else
try array_list.append(allocator, try parseInternal(
Child,
item,
maybe_allocator,
suppress_error_logs,
));
}
return array_list;
} else {
if (comptime !suppress_error_logs) logger.debug("expected array of {s}, found {s}", .{ @typeName(Child), @tagName(json_value) });
return error.UnexpectedFieldType;
}
}
if (comptime isHashMap(T)) {
const managed = comptime isManaged(T);
const Key = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "key") orelse unreachable].type;
const Value = std.meta.fields(T.KV)[std.meta.fieldIndex(T.KV, "value") orelse unreachable].type;
if (Key != []const u8) @compileError("HashMap key must be of type []const u8!");
if (json_value == .object) {
if (T == std.json.ObjectMap) return json_value.object;
const allocator = maybe_allocator orelse return error.AllocatorRequired;
var map: T = if (managed) T.init(allocator) else .{};
var map_iterator = json_value.object.iterator();
while (map_iterator.next()) |entry| {
if (managed)
try map.put(entry.key_ptr.*, try parseInternal(
Value,
entry.value_ptr.*,
maybe_allocator,
suppress_error_logs,
))
else
try map.put(allocator, entry.key_ptr.*, try parseInternal(
Value,
entry.value_ptr.*,
maybe_allocator,
suppress_error_logs,
));
}
return map;
} else {
if (comptime !suppress_error_logs) logger.debug("expected map of {s} found {s}", .{ @typeName(Value), @tagName(json_value) });
return error.UnexpectedFieldType;
}
}
if (info.is_tuple) {
if (json_value != .array) {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
if (json_value.array.items.len != std.meta.fields(T).len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of Tuple {s} but it doesn't", .{@typeName(T)});
return error.UnexpectedFieldType;
}
var tuple: T = undefined;
comptime var index: usize = 0;
inline while (index < std.meta.fields(T).len) : (index += 1) {
tuple[index] = try parseInternal(
std.meta.fields(T)[index].type,
json_value.array.items[index],
maybe_allocator,
suppress_error_logs,
);
}
return tuple;
}
if (json_value == .object) {
var result: T = undefined;
// Must use in order to bypass [#2727](https://github.com/ziglang/zig/issues/2727) :(
var missing_field = false;
inline for (info.fields) |field| {
const nm = comptime nullMeaning(T, field) orelse .value;
const field_value = json_value.object.get(mightRemap(T, field.name));
if (field.is_comptime) {
if (field_value == null) {
if (comptime !suppress_error_logs) logger.debug("comptime field {s}.{s} missing", .{ @typeName(T), field.name });
return error.InvalidFieldValue;
}
if (field.default_value) |default| {
const parsed_value = try parseInternal(
field.type,
field_value.?,
maybe_allocator,
suppress_error_logs,
);
const default_value = @as(*const field.type, @ptrCast(@alignCast(default))).*;
// NOTE: This only works for strings!
// TODODODODODODO ASAP
if (!std.mem.eql(u8, parsed_value, default_value)) {
if (comptime !suppress_error_logs) logger.debug("comptime field {s}.{s} does not match", .{ @typeName(T), field.name });
return error.InvalidFieldValue;
}
} else unreachable; // zig requires comptime fields to have a default initialization value
} else if (comptime dualable(field.type) and nm == .dual) {
if (field_value == null) {
@field(result, field.name) = null;
} else {
@field(result, field.name) = try parseInternal(@typeInfo(@TypeOf(@field(result, field.name))).Optional.child, field_value.?, maybe_allocator, suppress_error_logs);
}
} else {
if (field_value) |fv| {
if (@typeInfo(field.type) == .Struct and @hasDecl(field.type, "__json_is_undefinedable"))
@field(result, field.name) = .{
.value = try parseInternal(
field.type.__json_T,
fv,
maybe_allocator,
suppress_error_logs,
),
.missing = false,
}
else
@field(result, field.name) = try parseInternal(
field.type,
fv,
maybe_allocator,
suppress_error_logs,
);
} else {
if (@typeInfo(field.type) == .Struct and @hasDecl(field.type, "__json_is_undefinedable")) {
@field(result, field.name) = .{
.value = undefined,
.missing = true,
};
} else if (field.default_value) |default| {
const default_value = @as(*const field.type, @ptrCast(@alignCast(default))).*;
@field(result, field.name) = default_value;
} else if (@typeInfo(field.type) == .Optional and nm == .field) {
@field(result, field.name) = null;
} else {
if (comptime !suppress_error_logs) logger.debug("required field {s}.{s} missing", .{ @typeName(T), field.name });
missing_field = true;
}
}
}
}
if (missing_field) return error.MissingRequiredField;
return result;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Object, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Pointer => |info| {
if (info.size == .Slice) {
if (info.child == u8) {
if (json_value == .string) {
return json_value.string;
} else {
if (comptime !suppress_error_logs) logger.debug("expected String, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
} else if (info.child == std.json.Value) {
return json_value.array.items;
}
}
const allocator = maybe_allocator orelse return error.AllocatorRequired;
switch (info.size) {
.Slice, .Many => {
const sentinel = if (info.sentinel) |ptr| @as(*const info.child, @ptrCast(ptr)).* else null;
if (info.child == u8 and json_value == .string) {
const array = try allocator.allocWithOptions(
info.child,
json_value.string.len,
info.alignment,
sentinel,
);
std.mem.copy(u8, array, json_value.string);
return @as(T, @ptrCast(array));
}
if (json_value == .array) {
if (info.child == std.json.Value) return json_value.array.items;
const array = try allocator.allocWithOptions(
info.child,
json_value.array.items.len,
info.alignment,
sentinel,
);
for (json_value.array.items, 0..) |item, index|
array[index] = try parseInternal(
info.child,
item,
maybe_allocator,
suppress_error_logs,
);
return @as(T, @ptrCast(array));
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.One, .C => {
const data = try allocator.allocWithOptions(info.child, 1, info.alignment, null);
data[0] = try parseInternal(
info.child,
json_value,
maybe_allocator,
suppress_error_logs,
);
return &data[0];
},
}
},
.Array => |info| {
if (json_value == .array) {
var array: T = undefined;
if (info.sentinel) |ptr| {
const sentinel = @as(*const info.child, @ptrCast(ptr)).*;
array[array.len] = sentinel;
}
if (json_value.array.items.len != info.len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of {s} but it doesn't", .{@typeName(T)});
return error.UnexpectedFieldType;
}
for (array, 0..) |_, index|
array[index] = try parseInternal(
info.child,
json_value.array.items[index],
maybe_allocator,
suppress_error_logs,
);
return array;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Vector => |info| {
if (json_value == .array) {
var vector: T = undefined;
if (json_value.array.items.len != info.len) {
if (comptime !suppress_error_logs) logger.debug("expected Array to match length of {s} ({d}) but it doesn't", .{ @typeName(T), info.len });
return error.UnexpectedFieldType;
}
for (vector) |*item|
item.* = try parseInternal(
info.child,
item,
maybe_allocator,
suppress_error_logs,
);
return vector;
} else {
if (comptime !suppress_error_logs) logger.debug("expected Array, found {s}", .{@tagName(json_value)});
return error.UnexpectedFieldType;
}
},
.Void => return,
else => {
@compileError("unhandled json type: " ++ @typeName(T));
},
}
}
fn outputUnicodeEscape(
codepoint: u21,
out_stream: anytype,
) !void {
if (codepoint <= 0xFFFF) {
// If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),
// then it may be represented as a six-character sequence: a reverse solidus, followed
// by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
} else {
std.debug.assert(codepoint <= 0x10FFFF);
// To escape an extended character that is not in the Basic Multilingual Plane,
// the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
const high = @as(u16, @intCast((codepoint - 0x10000) >> 10)) + 0xD800;
const low = @as(u16, @intCast(codepoint & 0x3FF)) + 0xDC00;
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
try out_stream.writeAll("\\u");
try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
}
}
fn outputJsonString(value: []const u8, options: std.json.StringifyOptions, out_stream: anytype) !void {
try out_stream.writeByte('\"');
var i: usize = 0;
while (i < value.len) : (i += 1) {
switch (value[i]) {
// normal ascii character
0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => |c| try out_stream.writeByte(c),
// only 2 characters that *must* be escaped
'\\' => try out_stream.writeAll("\\\\"),
'\"' => try out_stream.writeAll("\\\""),
// solidus is optional to escape
'/' => {
if (options.string.String.escape_solidus) {
try out_stream.writeAll("\\/");
} else {
try out_stream.writeByte('/');
}
},
// control characters with short escapes
// TODO: option to switch between unicode and 'short' forms?
0x8 => try out_stream.writeAll("\\b"),
0xC => try out_stream.writeAll("\\f"),
'\n' => try out_stream.writeAll("\\n"),
'\r' => try out_stream.writeAll("\\r"),
'\t' => try out_stream.writeAll("\\t"),
else => {
const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;
// control characters (only things left with 1 byte length) should always be printed as unicode escapes
if (ulen == 1 or options.string.String.escape_unicode) {
const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;
try outputUnicodeEscape(codepoint, out_stream);
} else {
try out_stream.writeAll(value[i .. i + ulen]);
}
i += ulen - 1;
},
}
}
try out_stream.writeByte('\"');
}
pub fn stringify(
value: anytype,
options: std.json.StringifyOptions,
out_stream: anytype,
) @TypeOf(out_stream).Error!void {
const T = @TypeOf(value);
comptime validateCustomDecls(T);
switch (@typeInfo(T)) {
.Float, .ComptimeFloat => {
return std.fmt.formatFloatScientific(value, std.fmt.FormatOptions{}, out_stream);
},
.Int, .ComptimeInt => {
return std.fmt.formatIntValue(value, "", std.fmt.FormatOptions{}, out_stream);
},
.Bool => {
return out_stream.writeAll(if (value) "true" else "false");
},
.Null => {
return out_stream.writeAll("null");
},
.Optional => {
if (value) |payload| {
return try stringify(payload, options, out_stream);
} else {
return try stringify(null, options, out_stream);
}
},
.Enum => {
if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
return value.jsonStringify(options, out_stream);
}
if (@hasDecl(T, "tres_string_enum")) {
return try stringify(@tagName(value), options, out_stream);
} else {
return try stringify(@intFromEnum(value), options, out_stream);
}
},
.Union => {
if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
return value.jsonStringify(options, out_stream);
}
const info = @typeInfo(T).Union;
if (info.tag_type) |UnionTagType| {
inline for (info.fields) |u_field| {
if (value == @field(UnionTagType, u_field.name)) {
return try stringify(@field(value, u_field.name), options, out_stream);
}
}
return;
} else {
@compileError("Unable to stringify untagged union '" ++ @typeName(T) ++ "'");
}
},
.Struct => |S| {
if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
return value.jsonStringify(options, out_stream);
}
if (comptime isArrayList(T)) {
return stringify(value.items, options, out_stream);
}
try out_stream.writeByte('{');
var field_output = false;
var child_options = options;
child_options.whitespace.indent_level += 1;
if (comptime isHashMap(T)) {
var iterator = value.iterator();
while (iterator.next()) |entry| {
if (!field_output) {
field_output = true;
} else {
try out_stream.writeByte(',');
}
try child_options.whitespace.outputIndent(out_stream);
try outputJsonString(entry.key_ptr.*, options, out_stream);
try out_stream.writeByte(':');
if (child_options.whitespace.separator) {
try out_stream.writeByte(' ');
}
try stringify(entry.value_ptr.*, child_options, out_stream);
}
} else {
inline for (S.fields) |Field| {
const nm = nullMeaning(T, Field) orelse (if (options.emit_null_optional_fields) NullMeaning.value else NullMeaning.field);
// don't include void fields
if (Field.type == void) continue;
var emit_field = true;
// don't include optional fields that are null when emit_null_optional_fields is set to false
if (@typeInfo(Field.type) == .Optional) {
if (nm == .field or nm == .dual) {
if (@field(value, Field.name) == null) {
emit_field = false;
}
}
}
const is_undefinedable = comptime @typeInfo(@TypeOf(@field(value, Field.name))) == .Struct and @hasDecl(@TypeOf(@field(value, Field.name)), "__json_is_undefinedable");
if (is_undefinedable) {
if (@field(value, Field.name).missing)
emit_field = false;
}
if (emit_field) {
if (!field_output) {
field_output = true;
} else {
try out_stream.writeByte(',');
}
try child_options.whitespace.outputIndent(out_stream);
try outputJsonString(mightRemap(T, Field.name), options, out_stream);
try out_stream.writeByte(':');
if (child_options.whitespace.separator) {
try out_stream.writeByte(' ');
}
if (is_undefinedable) {
try stringify(@field(value, Field.name).value, child_options, out_stream);
} else if ((comptime dualable(Field.type)) and nm == .dual)
try stringify(@field(value, Field.name).?, child_options, out_stream)
else {
try stringify(@field(value, Field.name), child_options, out_stream);
}
}
}
}
if (field_output) {
try options.whitespace.outputIndent(out_stream);
}
try out_stream.writeByte('}');
return;
},
.ErrorSet => return stringify(@as([]const u8, @errorName(value)), options, out_stream),
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => switch (@typeInfo(ptr_info.child)) {
.Array => {
const Slice = []const std.meta.Elem(ptr_info.child);
return stringify(@as(Slice, value), options, out_stream);
},
else => {
// TODO: avoid loops?
return stringify(value.*, options, out_stream);
},
},
// TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)
.Slice => {
if (ptr_info.child == u8 and options.string == .String and std.unicode.utf8ValidateSlice(value)) {
try outputJsonString(value, options, out_stream);
return;
}
try out_stream.writeByte('[');
var child_options = options;
child_options.whitespace.indent_level += 1;
for (value, 0..) |x, i| {
if (i != 0) {
try out_stream.writeByte(',');
}
try child_options.whitespace.outputIndent(out_stream);
try stringify(x, child_options, out_stream);
}
if (value.len != 0) {
try options.whitespace.outputIndent(out_stream);
}
try out_stream.writeByte(']');
return;
},
else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
},
.Array => return stringify(&value, options, out_stream),
.Vector => |info| {
const array: [info.len]info.child = value;
return stringify(&array, options, out_stream);
},
.Void => return try out_stream.writeAll("{}"),
else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
}
unreachable;
}
pub const ToValueOptions = struct {
copy_strings: bool = false,
// TODO: Add string options
};
/// Arena recommended.
pub fn toValue(
allocator: std.mem.Allocator,
value: anytype,
options: ToValueOptions,
) std.mem.Allocator.Error!std.json.Value {