-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathzon_get_fields.zig
1998 lines (1866 loc) · 102 KB
/
zon_get_fields.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
// MIT License
//
// Copyright (c) 2023, 2024 Alexei Kireev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// zon_get_fields is available from https://github.com/Durobot/zon_get_fields
const std = @import("std");
/// Limit on the length of the path, used by
/// `getFieldVal*` functions. These functions
/// call `walkAst`, which is a recursive function,
/// and `zon_fld_path_len_limit` is the recursion
/// depth limit.
const zon_fld_path_len_limit = 20;
const ZonGetFieldsError = error
{
// errors common for `fn getFieldVal` and `fn zonToStruct`:
PathElementNotStruct, // One of the path elements (other than the last one) is not a sub-struct in ZON (AST).
PathElementNotArray, // One of the path elements (with [index]) is not an array in ZON (AST).
BadBooleanValue, // Field value could not be interpreted as a boolean, neither `false` nor `true`.
BadCharValue, // Field length is not 3, or field does not start or end with a quotation mark.
// `fn getFieldVal`-specific errors:
PathLimitReached, // Field path contains too many elements (separated by dots), see `zon_fld_path_len_limit`.
BadSeparatorPosition, // Zero-length (empty) field path, separator (dot) at the beginning of the field path,
// at the end of the field path, or two consecutive dots in the path.
BadArrIdxSyntax, // Bad array index syntax in a field path element, e.g. one brace is missing.
BadArrIdxValue, // Bad array index syntax in a field path element, e.g. non-numeric character(s)
// in index, or the array doesn't contain enough elements.
NotFound, // Field not found at the provided path.
// `fn zonToStruct`-specific errors:
NoAllocator, // Target struct contains field(s) that require memory allocation,
// but no allocator was provided (the optional allocator parameter is null).
IncompatibleTargetField, // Target struct field (array / slice elements) and AST field value are of
// incompatible types.
BadReportType, // Report struct field type doesn't match the target struct type.
// This should never happen, and is a sign of an internal problem in this library.
};
// ---------------------------------------------------------
// ---------------------- getFieldVal ----------------------
// ---------------------------------------------------------
/// Fetches the value of the field specified with dot-separated path from the AST.
/// T - The type to be returned. Supported types are integers, floats, bool and []const u8
/// ast - Abstract Syntax Tree to get the value from. Can be generated using std.zig.Ast.parse
/// fld_path - Dot-separated path to the field
pub fn getFieldVal(comptime T: type, ast: std.zig.Ast, fld_path: []const u8) !T
{
const str_val = try getFieldValStr(ast, fld_path);
switch (@typeInfo(T)) // tagged union: Type = union(enum)
{
.Int => |int_info|
{
// Requested type is u8 or u21 and field value is in a format that's not going to
// make `std.zig.parseCharLiteral()` crash, so let's try calling it
if ((int_info.bits == 8 or int_info.bits == 21) and int_info.signedness == .unsigned and
str_val[0] == '\'' and str_val[str_val.len - 1] == '\'')
{
if (str_val.len == 3) { return str_val[1]; } // Unless it's just one byte between ' and '
else
{
if (str_val.len > 3 and str_val.len <= 6 and // str_val.len is not 3, so we must try calling `parseCharLiteral`
(str_val[1] == '\\' or str_val[1] == 0 or
((str_val.len == 6 and str_val[1] & 0b11111000 == 0b11110000) or
(str_val.len == 5 and str_val[1] & 0b11110000 == 0b11100000) or
(str_val.len == 4 and str_val[1] & 0b11100000 == 0b11000000))))
{
const parsed_char = std.zig.parseCharLiteral(str_val);
switch (parsed_char)
{
.success =>
{
if (int_info.bits == 8 and parsed_char.success > 255)
{
std.log.warn("Field '{s}': value {s} (0x{x}) can't fit the requested type u8",
.{ fld_path, str_val, parsed_char.success });
return ZonGetFieldsError.BadCharValue;
}
return if (int_info.bits == 8) @as(T, @intCast(parsed_char.success & 0x0000FF))
else @as(T, @intCast(parsed_char.success)); // int_info.bits == 21
},
.failure =>
{
std.log.warn("Field '{s}': value {s} could not be parsed as a character : {}",
.{ fld_path, str_val, parsed_char.failure });
return ZonGetFieldsError.BadCharValue;
}
}
}
}
}
// Doesn't look like a character, try parsing it as an honest integer.
// Autodetect the base, to allow hex, etc. --v
const int_val = std.fmt.parseInt(T, str_val, 0) catch |err|
{
std.log.warn("Could not convert value of field '{s}' = '{s}' to type {s} : {}",
.{ fld_path, str_val, @typeName(T), err });
return err;
};
return int_val;
},
.Float =>
{
const float_val = std.fmt.parseFloat(T, str_val) catch |err|
{
std.log.warn("Could not convert value of field '{s}' = '{s}' to type {s} : {}",
.{ fld_path, str_val, @typeName(T), err });
return err;
};
return float_val;
},
.Bool =>
{
if (std.mem.eql(u8, str_val, "true")) { return true; }
else
{
if (std.mem.eql(u8, str_val, "false")) { return false; }
else
{
std.log.warn("Value of field '{s}' = '{s}' is neither 'true' nor 'false'",
.{ fld_path, str_val });
return ZonGetFieldsError.BadBooleanValue;
}
}
},
.Pointer => |ptr_info|
{
if (ptr_info.size == .Slice and ptr_info.child == u8 and ptr_info.is_const) { return str_val; }
else @compileError("fn getFieldVal: type '" ++ @typeName(T) ++ "' not supported");
},
else => @compileError("fn getFieldVal: type '" ++ @typeName(T) ++ "' not supported")
}
}
/// Returns field value as a string - a slice of characters within `ast`.
/// This is the base function used `getFieldVal` before it converts the value to the type it needs.
fn getFieldValStr(ast: std.zig.Ast, fld_path: []const u8) ![]const u8
{
var buf: [2]std.zig.Ast.Node.Index = undefined;
var path_itr = std.mem.splitScalar(u8, fld_path, '.'); // SplitIterator(T, .scalar)
const root_init = ast.fullStructInit(&buf, ast.nodes.items(.data)[0].lhs) orelse
{
std.log.warn("Zon parsing failed (top level struct)", .{});
return ZonGetFieldsError.PathElementNotStruct;
};
var str_val = try walkAst(ast, root_init.ast.fields, &path_itr, 1);
// Remove quotation marks if found
if (str_val[0] == '"' and str_val[str_val.len - 1] == '"')
{
str_val.ptr += 1;
str_val.len -= 2;
}
return str_val;
}
/// Meat and potatoes of the whole operation.
/// Goes through `ast_fields`, looking for the field referenced by
/// `path_itr.next()`. If `path_itr` contains no more elements after it,
/// returns field value, if it does, calls itself recursively.
/// In the end, returns the value of the field defined by `path_itr` as a
/// slice of characters within `ast` (a string), or an error.
fn walkAst(ast: std.zig.Ast,
ast_fields: []const std.zig.Ast.Node.Index,
path_itr: *std.mem.SplitIterator(u8, .scalar),
recursion_depth: u32) ![]const u8
{
if (recursion_depth > zon_fld_path_len_limit)// Limit recursion depth, for the sake of sanity
{
std.log.warn("fn walkAst: recursion limit ({}) exceeded", .{ zon_fld_path_len_limit });
return ZonGetFieldsError.PathLimitReached;
}
// `path_element` is the current path element this function is going to handle.
// There are 4 options:
// 1. `path_element` is the last element of the path, and refers to a scalar field
// `walkAst()` returns the value of this field;
// 2. `path_element` is the last element of the path, and refers to an array element (ends with [<idx>]),
// `walkAst()` returns the value of this array element;
// 3. `path_element` is not the last element of the path, and refers to a struct,
// `walkAst()` recursively calls itself;
// 4. `path_element` is not the last element of the path, and refers to an array element (ends with [<idx>])
// `walkAst()` recursively calls itself.
var path_element = path_itr.next() orelse
{
std.log.warn("Ran out of path elements", .{});
return ZonGetFieldsError.NotFound;
};
if (path_element.len == 0)
{
std.log.warn("Path starts with dot or zero-length path", .{});
return ZonGetFieldsError.BadSeparatorPosition;
}
// If this path element is an array element, we must figure out the index (arr_idx)
const arr_idx: ?std.zig.Ast.Node.Index = blk:
{
if (path_element[path_element.len - 1] == ']')
{
if (std.mem.lastIndexOfScalar(u8, path_element, '[')) |left_brace_pos|
{
const arr_idx = std.fmt.parseInt(std.zig.Ast.Node.Index,
path_element[(left_brace_pos+1)..(path_element.len-1)], 0) catch |err|
{
std.log.warn("Bad array index value in {s}, {}", .{ path_element, err });
return ZonGetFieldsError.BadArrIdxValue;
};
path_element.len = left_brace_pos; // Make sure we ignore the array index part from now on
break :blk arr_idx;
}
else
{
std.log.warn("Bad array index syntax in {s}", .{ path_element });
return ZonGetFieldsError.BadArrIdxSyntax;
}
}
break :blk null; // Index not found, `path_element` does NOT refer to an element of an array
};
const fld_idx = blk2:
{
if (path_element.len == 0) // Is this a pure index (no field name)?
{
if (arr_idx) |arr_idx_val|
{
if (arr_idx_val < 0 or arr_idx_val > ast_fields.len - 1)
{
std.log.warn("Array index out of bounds - unnamed array contains {d} elements, index is {d}",
.{ ast_fields.len, arr_idx_val });
return ZonGetFieldsError.BadArrIdxValue;
}
break :blk2 ast_fields[arr_idx_val];
}
// path_element.len == 0, but also arr_idx == null - empty path_element
std.log.warn("Path ends with dot, or two dots in a row", .{});
return ZonGetFieldsError.BadSeparatorPosition;
}
// path_element.len != 0, must find the field by name
for (ast_fields) |fld_idx|
{
const fld_name = ast.tokenSlice(ast.firstToken(fld_idx) - 2);
if (std.mem.eql(u8, path_element, fld_name))
break :blk2 fld_idx;
}
std.log.warn("Path element '{s}' not found", .{ path_element });
return ZonGetFieldsError.NotFound;
};
// --== Now, figure out what do we do with the field (fld_idx) we have found ==--
//
// If there's more in the path, must treat current field as either a (sub) struct, or an array
if (path_itr.peek()) |nxt| // Could have used if (path_itr_2.index) |_|, but need `len` too
{
if (nxt.len == 0)
{
std.log.warn("Path ends with dot, or two dots in a row", .{});
return ZonGetFieldsError.BadSeparatorPosition;
}
if (arr_idx) |arr_idx_val| // There's index in this `path_element`, treat it as an array
{
// -----------------------------------------------------
// 4. `path_element` is not the last element of the path,
// and refers to an array element (ends with [<idx>])
// -----------------------------------------------------
const node_idx = blk3: // std.zig.Ast.Node.Index
{
if (path_element.len == 0) // Pure index, no field name
{
if (arr_idx_val < 0 or arr_idx_val > ast_fields.len - 1)
{
std.log.warn("Array index out of bounds - anonymous arrys contains {d} elements, index is {d}",
.{ ast_fields.len, arr_idx_val });
return ZonGetFieldsError.BadArrIdxValue;
}
break :blk3 ast_fields[arr_idx_val];
}
// If we got here, remaining part of this `path_element` is NOT empty,
// which means we must get this array field's elements before we can return one of them
var buf: [2]std.zig.Ast.Node.Index = undefined;
const arr_init = ast.fullArrayInit(&buf, fld_idx) orelse // ?full.ArrayInit
{
std.log.warn("Parsing of field '{s}' failed, or value is not an array", .{ path_element });
return ZonGetFieldsError.PathElementNotArray;
};
if (arr_idx_val < 0 or arr_idx_val > arr_init.ast.elements.len - 1)
{
std.log.warn("Array index out of bounds - '{s}' contains {d} elements, index is {d}",
.{ path_element, arr_init.ast.elements.len, arr_idx_val });
return ZonGetFieldsError.BadArrIdxValue;
}
break :blk3 arr_init.ast.elements[arr_idx_val];
};
// Peek at the next path element to figure out how we should treat array element -
// as a struct or as an array
if (nxt[nxt.len - 1] == ']') // Array element is an array too
{
var buf: [2]std.zig.Ast.Node.Index = undefined;
const arr_elt_arr_init = ast.fullArrayInit(&buf, node_idx) orelse
{
std.log.warn("Parsing of field '{s}' failed, or its element {} is not an array",
.{ path_element, arr_idx_val });
return error.PathElementNotArray;
};
return walkAst(ast, arr_elt_arr_init.ast.elements, path_itr, recursion_depth + 1);
}
else // Array element is a struct
{
var buf: [2]std.zig.Ast.Node.Index = undefined;
const arr_elt_struct_init = ast.fullStructInit(&buf, node_idx) orelse
{
std.log.warn("Parsing of element {} of array field '{s}' failed, or this element is not a struct",
.{ arr_idx_val, path_element });
return error.PathElementNotStruct;
};
return walkAst(ast, arr_elt_struct_init.ast.fields, path_itr, recursion_depth + 1);
}
}
else // No index in this `path_element`, treat it as a struct
{
// -----------------------------------------------------------------------------
// 3. `path_element` is not the last element of the path, and refers to a struct
// -----------------------------------------------------------------------------
var buf: [2]std.zig.Ast.Node.Index = undefined;
const substruct_init = ast.fullStructInit(&buf, fld_idx) orelse
{
std.log.warn("Parsing of field '{s}' failed, or value is not a struct", .{ path_element });
return ZonGetFieldsError.PathElementNotStruct;
};
return walkAst(ast, substruct_init.ast.fields, path_itr, recursion_depth + 1);
}
}
else // --== No more path elements after this one, we have arrived, return the value ==--
{
// Get array element `arr_idx`, if any
if (arr_idx) |arr_idx_val|
{
// -----------------------------------------------------
// 2. `path_element` is the last element of the path,
// and refers to an array element (ends with [<idx>])
// so we treat it as a scalar value,
// and return as a string
// -----------------------------------------------------
// Is the remaining part of this `path_element` is empty, meaning
// `ast_fields` already contains the list of array element indices?
if (path_element.len == 0)
{
if (arr_idx_val < 0 or arr_idx_val > ast_fields.len - 1)
{
std.log.warn("Array index out of bounds - anonymous arrys contains {d} elements, index is {d}",
.{ ast_fields.len, arr_idx_val });
return ZonGetFieldsError.BadArrIdxValue;
}
return getValueSlice(ast, ast.nodes.items(.main_token)[ast_fields[arr_idx_val]]);
}
// If we got here, remaining part of this `path_element` is NOT empty,
// which means we must get this array field's elements before we can return one of them
var buf: [2]std.zig.Ast.Node.Index = undefined;
const arr_init = ast.fullArrayInit(&buf, fld_idx) orelse // ?full.ArrayInit
{
std.log.warn("Parsing of field '{s}' failed, or value is not an array", .{ path_element });
return ZonGetFieldsError.PathElementNotArray;
};
if (arr_idx_val < 0 or arr_idx_val > arr_init.ast.elements.len - 1)
{
std.log.warn("Array index out of bounds - '{s}' contains {d} elements, index is {d}",
.{ path_element, arr_init.ast.elements.len, arr_idx_val });
return ZonGetFieldsError.BadArrIdxValue;
}
const arr_elt_fld_idx = arr_init.ast.elements[arr_idx_val];
return getValueSlice(ast, ast.nodes.items(.main_token)[arr_elt_fld_idx]);
}
// -------------------------------------------------------------------------------
// 1. `path_element` is the last element of the path, and refers to a scalar field
// -------------------------------------------------------------------------------
// `arr_idx` is null, return the field value as a scalar
return getValueSlice(ast, ast.nodes.items(.main_token)[fld_idx]);
}
}
/// Wrapper around `std.zig.Ast.tokenSlice()`, to get negative numbers properly
fn getValueSlice(ast: std.zig.Ast, token_index: std.zig.Ast.TokenIndex) []const u8
{
const ts = ast.tokenSlice(token_index);
// Somehow for negative numbers (without quotation marks)
// `Ast.tokenSlice` returns just the "-", so we must fix that.
if (ts.len == 1 and ts[0] == '-')
{
// Ugly hack to get the correct slice
var ts2 = ast.tokenSlice(token_index + 1);
// We rely on the next tokenSlice being in `ast.source` right after
// the one that is our "-".
ts2.ptr -= 1;
ts2.len += 1;
return ts2;
}
return ts;
}
// ---------------------------------------------------------
// ------------------- getFieldVal Tests -------------------
// ---------------------------------------------------------
test "getFieldVal top level struct parsing error test"
{
// Missing dot in .struct_1 = {
const zon_txt =
\\.{
\\ .struct_1 =
\\ {
\\ .abc = "Hello",
\\ .def = "you",
\\ }
\\}
;
var ast = try std.zig.Ast.parse(std.testing.allocator, zon_txt, .zon);
defer ast.deinit(std.testing.allocator);
std.debug.print("\nDisregard the (warn) message below, it's expected and normal:\n", .{});
try std.testing.expectError(error.PathElementNotStruct, getFieldVal([]const u8, ast, "struct_1.abc"));
}
test "getFieldVal big test"
{
// Field order is not important
const zon_txt =
\\.{
\\ .hex_u8 = 0x11, // Hexadecimal is OK
\\ .str_u16 = "1991", // Number in a string is OK, as long as it's valid
\\ .bin_u8 = 0b10010110, // Binary is OK too
\\ .negative_i16 = -1000,
\\ .struct_1 =
\\ .{
\\ .abc = "Hello",
\\ .def = "you",
\\ .str_no_quotes = i_am_a_string_too, // Not a normal Zig string, but this works too
\\ .f32_cant_represent = 12.45, // See https://float.exposed , try this value
\\ .f32_negative = -10.0,
\\ .recursion = .{ .depth = .{ .limit = .{ .check = .{ .six = .{ .seven = .{ .eight = .{ .nine = .{ .ten = .{ .l11 = .{ .l12 = .{ .l13 = .{ .l14 = .{ .l15 = .{ .l16 = .{ .l17 = .{ .l18 = .{ .l19 = .{ .l20 = .{ .l21 = "TOO DEEP" }}}}}}}}}}}}}}}}}}},
\\ },
\\ .bool_1 = false,
\\ .bool_2 = true,
\\ .bool_str = "false",
\\ .bool_bad = "dontknow",
\\ .character_1 = 'A',
\\ .character_escaped = '\'',
\\ .character_newline = '\x0A', // aka '\n'
\\ .character_no_quotes = B, // Bad
\\ .character_unicode = '⚡',
\\ //.character_bad = 'a whole string!', - Makes Ast.parse() fail
\\ .str_unicode = "こんにちは",
\\ .arr_u8 = .{ 10, 20, 30, 40 }, // This is an array
\\ .arr_struct = // An array of structs
\\ .{
\\ .{ .abc = 12, .def = 34 },
\\ .{ .abc = 56, .def = 78 },
\\ .{ .abc = 90, .def = 12 },
\\ },
\\ .arr_arr = // Array of arrays
\\ .{
\\ .{ -11, -12, -13 },
\\ .{ 21, 22, 23 },
\\ .{ -31, -32, -33 },
\\ },
\\ .arr_arr_struct = // Array of arrays of structs
\\ .{
\\ .{ .{ .q = 1, .w = 2 }, .{ .q = 3, .w = 4 }, .{ .q = 5, .w = 6 } },
\\ .{ .{ .q = 7, .w = 8 }, .{ .q = 9, .w = 10 }, .{ .q = 11, .w = 12 } },
\\ .{ .{ .q = 13, .w = 14 }, .{ .q = 15, .w = 16 }, .{ .q = 17, .w = 18 } },
\\ },
\\}
;
var ast = try std.zig.Ast.parse(std.testing.allocator, zon_txt, .zon);
defer ast.deinit(std.testing.allocator);
std.debug.print("\nDisregard the (warn) messages below, they're expected and normal:\n", .{});
try std.testing.expectError(error.BadSeparatorPosition, getFieldVal([]const u8, ast, "struct_1..abc"));
try std.testing.expectError(error.BadSeparatorPosition, getFieldVal([]const u8, ast, ".struct_1.abc"));
try std.testing.expectError(error.BadSeparatorPosition, getFieldVal([]const u8, ast, "struct_1.abc."));
try std.testing.expectError(error.PathElementNotArray, getFieldVal([]const u8, ast, "struct_1[0]"));
try std.testing.expectError(error.PathElementNotStruct, getFieldVal([]const u8, ast, "arr_arr[0].abc"));
try std.testing.expectError(error.BadArrIdxValue, getFieldVal(u8, ast, "arr_u8[<bad index>]"));
try std.testing.expectError(error.BadArrIdxSyntax, getFieldVal(u8, ast, "arr_u8{2]"));
// Assuming zon_fld_path_len_limit == 20
try std.testing.expect(zon_fld_path_len_limit <= 20);
// Otherwise this test makes no sense and must be adjusted accordingly
try std.testing.expectError(error.PathLimitReached,
getFieldVal([]const u8, ast,
"struct_1.recursion.depth.limit.check.six.seven.eight." ++
"nine.ten.l11.l12.l13.l14.l15.l16.l17.l18.l19.l20.l21"));
var val_str = try getFieldVal([]const u8, ast, "hex_u8");
try std.testing.expectEqualStrings(val_str, "0x11");
//
var val_u16 = try getFieldVal(u16, ast, "hex_u8");
try std.testing.expectEqual(val_u16, 17);
val_str = try getFieldVal([]const u8, ast, "str_u16");
try std.testing.expectEqualStrings(val_str, "1991");
//
val_u16 = try getFieldVal(u16, ast, "str_u16");
try std.testing.expectEqual(val_u16, 1991);
//
try std.testing.expectError(error.Overflow, getFieldVal(u8, ast, "str_u16"));
var val_u8 = try getFieldVal(u8, ast, "bin_u8");
try std.testing.expectEqual(val_u8, 0b10010110);
const val_i16 = try getFieldVal(i16, ast, "negative_i16");
try std.testing.expectEqual(val_i16, -1000);
//
val_str = try getFieldVal([]const u8, ast, "negative_i16");
try std.testing.expectEqualStrings(val_str, "-1000");
val_str = try getFieldVal([]const u8, ast, "struct_1.def");
try std.testing.expectEqualStrings(val_str, "you");
val_str = try getFieldVal([]const u8, ast, "struct_1.str_no_quotes");
try std.testing.expectEqualStrings(val_str, "i_am_a_string_too");
try std.testing.expectError(error.NotFound, getFieldVal(u8, ast, "struct_1.bad_field"));
// See https://float.exposed , https://www.h-schmidt.net/FloatConverter/IEEE754.html
var val_float = try getFieldVal(f32, ast, "struct_1.f32_cant_represent");
try std.testing.expectEqual(val_float, 12.45);
val_float = try getFieldVal(f32, ast, "struct_1.f32_negative");
try std.testing.expectEqual(val_float, -10.0);
var val_bool = try getFieldVal(bool, ast, "bool_1");
try std.testing.expect(!val_bool);
//
val_bool = try getFieldVal(bool, ast, "bool_2");
try std.testing.expect(val_bool);
//
val_bool = try getFieldVal(bool, ast, "bool_str");
try std.testing.expect(!val_bool);
//
try std.testing.expectError(error.BadBooleanValue, getFieldVal(bool, ast, "bool_bad"));
val_u8 = try getFieldVal(u8, ast, "character_1");
try std.testing.expectEqual(val_u8, 'A');
//
val_u8 = try getFieldVal(u8, ast, "character_escaped");
try std.testing.expectEqual(val_u8, '\'');
//
val_u8 = try getFieldVal(u8, ast, "character_newline");
try std.testing.expectEqual(val_u8, '\n');
//
try std.testing.expectError(error.InvalidCharacter, getFieldVal(u8, ast, "character_no_quotes"));
try std.testing.expectError(error.InvalidCharacter, getFieldVal(u8, ast, "struct_1.str_no_quotes"));
try std.testing.expectError(error.BadCharValue, getFieldVal(u8, ast, "character_unicode"));
const val_u21 = try getFieldVal(u21, ast, "character_unicode");
try std.testing.expectEqual(val_u21, '⚡');
val_str = try getFieldVal([]const u8, ast, "str_unicode");
try std.testing.expectEqualStrings(val_str, "こんにちは");
val_u8 = try getFieldVal(u8, ast, "arr_u8[3]");
try std.testing.expectEqual(val_u8, 40);
//
try std.testing.expectError(error.BadArrIdxValue, getFieldVal(u8, ast, "arr_u8[4]"));
val_u8 = try getFieldVal(u8, ast, "arr_struct[2].abc");
try std.testing.expectEqual(val_u8, 90);
//
try std.testing.expectError(error.NotFound, getFieldVal(u8, ast, "arr_struct[2].not_there"));
val_str = try getFieldVal([]const u8, ast, "arr_arr[2].[2]");
try std.testing.expectEqualStrings(val_str, "-33");
//
const val_i8 = try getFieldVal(i8, ast, "arr_arr[2].[2]");
try std.testing.expectEqual(val_i8, -33);
val_u8 = try getFieldVal(u8, ast, "arr_arr_struct[2].[1].q");
try std.testing.expectEqual(val_u8, 15);
}
// ---------------------------------------------------------
// ---------------------- zonToStruct ----------------------
// ---------------------------------------------------------
/// Was the field / array element / slice element filled or not
const ZonFieldResult = enum
{
not_filled, // Field / array element / slice element was not filled
partially_filled, // This element of array or slice was filled, but not all elements were filled
filled, // Field / array / slice was filled
overflow_filled, // This element of array or slice was filled, and all others as well, but there
// were too many data elements in AST, and they were ignored
fn isGreaterThan(self: ZonFieldResult, other: ZonFieldResult) bool
{
return switch (other)
{
.not_filled => self == .partially_filled or self == .filled or self == .overflow_filled,
.partially_filled => self == .filled or self == .overflow_filled,
.filled => self == .overflow_filled,
.overflow_filled => false
};
}
};
/// Populate target struct fields with values from `ast`.
/// If a field has no counterpart in `ast`, it's not going to be filled.
/// `tgt_struct_ptr` Must be a pointer to a mutable (non-const) target struct instance.
/// `ast` Abstract syntax tree generated from the ZON source text.
/// `allocr` Optional allocator. May be null, but in this case target struct can't contain
/// slices, except for `[]const u8` - those will point to string values within `ast.source`
/// (or those slices have no counterparts in `ast` so they are ignored).
pub fn zonToStruct(tgt_struct_ptr: anytype, ast: std.zig.Ast, allocr: ?std.mem.Allocator)
!MakeReportStructType(if (@typeInfo(@TypeOf(tgt_struct_ptr)) != .Pointer or
@typeInfo(@TypeOf(tgt_struct_ptr)).Pointer.is_const or
@typeInfo(@TypeOf(tgt_struct_ptr)).Pointer.size != .One or
@typeInfo(@typeInfo(@TypeOf(tgt_struct_ptr)).Pointer.child) != .Struct)
@compileError("fn zonToStruct: `tgt_struct_ptr` is " ++ @typeName(@TypeOf(tgt_struct_ptr)) ++
" , expected a single-item pointer to a mutable (non-const) struct")
else
@typeInfo(@TypeOf(tgt_struct_ptr)).Pointer.child)
{
// Root field index -----------------------------------------------------v
return try populateStruct(tgt_struct_ptr, ast, ast.nodes.items(.data)[0].lhs,
ZonFieldResult.filled, allocr, 0);
}
/// Returns report struct (field) type that represents this target struct field type, `tgt_type`,
/// which is a struct (including the target struct itselg). See `Report struct field types` in README.md
fn MakeReportStructType(tgt_type: type) type
{
const tgt_type_info = @typeInfo(tgt_type);
if (tgt_type_info != .Struct)
@compileError("fn MakeReportStructType: `tgt_type` is " ++ @typeName(tgt_type) ++
" , expected a struct");
const flds =
blk:
{
var non_comptime_fld_count = 0; // Count non-comptime fields of the target struct
for (tgt_type_info.Struct.fields) |tgt_fld|
{
if (!tgt_fld.is_comptime)
non_comptime_fld_count += 1;
}
var flds_values: [non_comptime_fld_count]std.builtin.Type.StructField = undefined;
var i = 0; // comptime_int
// const unfilled = ZonFieldResult.not_filled;
for (tgt_type_info.Struct.fields) |tgt_fld|
{
if (!tgt_fld.is_comptime)
{
flds_values[i] =
.{
.name = tgt_fld.name,
.type =
switch (@typeInfo(tgt_fld.type))
{
.Struct => MakeReportStructType(tgt_fld.type),
.Array => MakeReportArrayType(tgt_fld.type),
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
MakeReportSliceType(tgt_fld.type)
else
ZonFieldResult,
else => ZonFieldResult,
},
.default_value = null,
// .default_value = if (@typeInfo(tgt_fld.type) != .Struct and @typeInfo(tgt_fld.type) != .Array)
// &unfilled //@as(?*ZonFieldResult, &unfilled)
// else
// null,
.is_comptime = false,
.alignment =
@alignOf(switch (@typeInfo(tgt_fld.type))
{
.Struct => MakeReportStructType(tgt_fld.type),
.Array => MakeReportArrayType(tgt_fld.type),
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
MakeReportSliceType(tgt_fld.type)
else
ZonFieldResult,
else => ZonFieldResult
}),
};
i += 1;
}
}
break :blk flds_values;
};
return @Type(.{
.Struct =
.{
.layout = .auto,
.backing_integer = null,
.fields = &flds,
.decls = &.{},
.is_tuple = false,
}
});
}
/// Returns report struct field type that represents this target struct field type, `tgt_type`,
/// which is an array. See `Report struct field types` in README.md
fn MakeReportArrayType(tgt_type: type) type
{
const tgt_type_info = @typeInfo(tgt_type);
if (tgt_type_info != .Array)
@compileError("fn MakeReportArrayType: `tgt_type` is " ++ @typeName(tgt_type) ++
" , expected an array");
return @Type(.{
.Array =
.{
.len = tgt_type_info.Array.len,
.child =
switch(@typeInfo(tgt_type_info.Array.child))
{
.Array => MakeReportArrayType(tgt_type_info.Array.child),
.Struct => MakeReportStructType(tgt_type_info.Array.child),
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
MakeReportSliceType(tgt_type_info.Array.child)
else
ZonFieldResult,
else => ZonFieldResult,
},
.sentinel = null,
}
});
}
/// Returns report struct field type that represents this target struct field type, `tgt_type`,
/// which is a slice. See `Report struct field types` in README.md
fn MakeReportSliceType(tgt_type: type) type
{
const tgt_type_info = @typeInfo(tgt_type);
if (tgt_type_info != .Pointer)
@compileError("fn MakeReportSliceType: `tgt_type` is " ++ @typeName(tgt_type) ++
" , expected a slice");
if (tgt_type_info.Pointer.size != .Slice)
@compileError("fn MakeReportSliceType: `tgt_type` is a Pointer: " ++ @typeName(tgt_type) ++
" , expected a slice");
// Only target slices of structs, arrays and slices are represented in the report struct
// with slices of ZonFieldResult.
// Slices of primitive types, such as integers, floats, etc., and even pointers that are not slices,
// are represented with a single ZonFieldResult field the report struct.
const ReportSliceChildType =
switch (@typeInfo(tgt_type_info.Pointer.child))
{
.Struct => MakeReportStructType(tgt_type_info.Pointer.child),
.Array => MakeReportArrayType(tgt_type_info.Pointer.child),
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
MakeReportSliceType(tgt_type_info.Pointer.child)
else
ZonFieldResult, // Slice elemetns are primitive pointers (not slices), though we actually don't support these target struct fields o_O
else => return ZonFieldResult // Slice elemetns are of a primitive type, so in the report we'll have a single ZonFieldResult
};
// We've got a 'fancier' slice in the target struct - its elements are either structs, arrays, or slices.
return @Type(.{
.Pointer =
.{
.size = .Slice,
.is_const = false,
.is_volatile = false,
.alignment = @alignOf(ReportSliceChildType), // TODO: SHOULDN'T IT BE SLICE ALIGNMENT, NOT SLICE ELEMENT ALIGNMENT? -- BUT HOW?
.address_space = .generic, // ? pub const AddressSpace = enum(u5) { // CPU address spaces. generic, gs, fs, ss, ...
.child = ReportSliceChildType,
.is_allowzero = false,
.sentinel = null,
}
});
}
/// Create and return an initialized instance of the report struct (of type T).
/// Struct fields are initialized with ZonFieldResult.not_filled, including nested structs and arrays.
/// `T` struct type. This is the type returned by MakeReportStructType function.
/// `allocr` allocator is there to be passed to `makeReportSlice`.
fn makeReportStruct(T: type) T
{
if (@typeInfo(T) != .Struct)
@compileError("fn makeReportStruct: `T` is " ++ @typeName(T) ++ " , expected a struct");
var res: T = undefined;
inline for (@typeInfo(T).Struct.fields) |fld|
if (!fld.is_comptime)
{
if (fld.type == ZonFieldResult) { @field(res, fld.name) = ZonFieldResult.not_filled; }
else
switch (@typeInfo(fld.type))
{
.Struct => @field(res, fld.name) = makeReportStruct(fld.type),
.Array => @field(res, fld.name) = makeReportArray(fld.type),
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
{ @field(res, fld.name) = makeReportSlice(fld.type); }
else
@compileError("fn makeReportStruct: field `" ++ fld.name ++ "` is a Pointer, but not a slice: " ++
@typeName(fld.type) ++ " , expected ZonFieldResult, struct, array or slice"),
else => @compileError("fn makeReportStruct: field `" ++ fld.name ++ "` is " ++
@typeName(fld.type) ++ " , expected ZonFieldResult, struct, array or slice")
}
};
return res;
}
/// Create and return an initialized instance of the report array (of type T).
/// Array elements are initialized to to ZonFieldResult.not_filled, including nested structs and arrays.
/// `T` array type. This is the type returned by MakeReportArrayType function.
/// `allocr` allocator is there to be passed to `makeReportSlice`.
fn makeReportArray(T: type) T
{
if (@typeInfo(T) != .Array)
@compileError("fn makeReportArray: `T` is " ++ @typeName(T) ++ " , expected an array");
var res: T = undefined;
if (@typeInfo(T).Array.child == ZonFieldResult)
{
for (&res) |*e| e.* = ZonFieldResult.not_filled;
return res;
}
// Array elements are NOT simple ZonFieldResult enums
const arr_elt_type_info = @typeInfo(@typeInfo(T).Array.child);
switch (arr_elt_type_info)
{
.Struct => { for (&res) |*e| e.* = makeReportStruct(@typeInfo(T).Array.child); },
.Array => { for (&res) |*e| e.* = makeReportArray(@typeInfo(T).Array.child); },
.Pointer => |ptr_info|
if (ptr_info.size == .Slice)
{ for (&res) |*e| e.* = makeReportSlice(@typeInfo(T).Array.child); }
else
@compileError("fn makeReportArray: array elemets are `Pointer`s, but not slices" ++
@typeName(@typeInfo(T).Array.child) ++
" , expected ZonFieldResult, struct, array or slice"),
else => @compileError("fn makeReportArray: array elemets are " ++
@typeName(@typeInfo(T).Array.child) ++
" , expected ZonFieldResult, struct, array or slice")
}
return res;
}
/// Create and return an initialized instance of the report slice (of type T).
/// Array elements are initialized to to ZonFieldResult.not_filled, including nested structs and arrays.
/// `T` slice type. This is the type returned by MakeReportSliceType function.
fn makeReportSlice(T: type) T
{
if (T == ZonFieldResult)
return ZonFieldResult.not_filled;
const tgt_type_info = @typeInfo(T);
if (tgt_type_info != .Pointer)
@compileError("fn makeReportSlice: `T` is " ++ @typeName(T) ++ " , expected a ZonFieldResult or a slice");
if (tgt_type_info.Pointer.size != .Slice)
@compileError("fn makeReportSlice: `T` is a Pointer: " ++ @typeName(T) ++ " , expected a slice");
return &.{};
}
/// Populate target (sub)struct with values from `ast`, starting with `struct_ast_fld_idx`.
/// If a field has no counterpart in `ast`, it's not going to be filled.
/// `ptr_tgt` Must be a pointer to a mutable (non-const) target struct instance.
/// `ast` Abstract syntax tree generated from the ZON source text.
/// `struct_ast_fld_idx` Index of the root node of the source (sub)tree in `ast`
/// `rept_filled_val` Value to be assigned to report struct fields, if the value is found in AST
/// `allocr` Optional allocator. May be null, but in this case target struct can't
/// contain slices, except for `[]const u8` - those will point to string values
/// within `ast.source` (or those slices have no counterparts in `ast` and are ignored).
/// `recursion_depth` Recursion level, on the first call should be 1. Incremented on subsequent calls
/// to `populateSlice`, `populateArray`, `populateStruct`.
fn populateStruct(ptr_tgt: anytype,
ast: std.zig.Ast,
struct_ast_fld_idx: std.zig.Ast.Node.Index,
rept_filled_val: ZonFieldResult,
allocr: ?std.mem.Allocator,
comptime recursion_depth: u32)
!MakeReportStructType(if (@typeInfo(@TypeOf(ptr_tgt)) != .Pointer or
@typeInfo(@TypeOf(ptr_tgt)).Pointer.is_const or
@typeInfo(@TypeOf(ptr_tgt)).Pointer.size != .One or
@typeInfo(@typeInfo(@TypeOf(ptr_tgt)).Pointer.child) != .Struct)
@compileError("fn populateStruct: `ptr_tgt` is " ++ @typeName(@TypeOf(ptr_tgt)) ++
" , expected a single-item pointer to a mutable (non-const) struct")
else
@typeInfo(@TypeOf(ptr_tgt)).Pointer.child)
{
if (recursion_depth > zon_fld_path_len_limit) // Limit recursion depth, for the sake of sanity
{
@compileLog("zon_fld_path_len_limit = ", zon_fld_path_len_limit);
@compileLog("recursion_depth = ", recursion_depth);
@compileError("fn populateStruct: recursion limit exceeded");
}
var buf: [2]std.zig.Ast.Node.Index = undefined;
const struct_init = ast.fullStructInit(&buf, struct_ast_fld_idx) orelse
{
if (struct_ast_fld_idx == ast.nodes.items(.data)[0].lhs) // Root element
{
std.log.warn("Zon root structure parsing failed, is it a struct?", .{});
}
else
{
const ast_fld_name = ast.tokenSlice(ast.firstToken(struct_ast_fld_idx) - 2);
std.log.warn("Zon field {s} parsing failed, is it a struct?", .{ ast_fld_name });
}
return ZonGetFieldsError.PathElementNotStruct;
};
var report = makeReportStruct(MakeReportStructType(@typeInfo(@TypeOf(ptr_tgt)).Pointer.child));
const tgt_type_info = @typeInfo(@TypeOf(ptr_tgt.*));
// This unrolls as many times as the number of fields in ptr_tgt.*
inline for (tgt_type_info.Struct.fields) |tgt_fld|
{
if (!tgt_fld.is_comptime) // Skip comptime fields - this check is comptime
{
// Initialize the field with ZonFieldResult.not_filled, including all the nested structs, arrays, etc.
for (struct_init.ast.fields) |ast_fld_idx|
{
const ast_fld_name = ast.tokenSlice(ast.firstToken(ast_fld_idx) - 2);
if (std.mem.eql(u8, tgt_fld.name, ast_fld_name))
switch (@typeInfo(tgt_fld.type))
{
.Int =>
{
@field(ptr_tgt.*, tgt_fld.name) = try getValueInt(tgt_fld.type, ast, ast_fld_idx);
@field(report, tgt_fld.name) = rept_filled_val; //ZonFieldResult.filled;
},
.Float =>
{
@field(ptr_tgt.*, tgt_fld.name) = try getValueFloat(tgt_fld.type, ast, ast_fld_idx);
@field(report, tgt_fld.name) = rept_filled_val; //ZonFieldResult.filled;
},
.Bool =>
{
@field(ptr_tgt.*, tgt_fld.name) = try getValueBool(ast, ast_fld_idx);
@field(report, tgt_fld.name) = rept_filled_val; //ZonFieldResult.filled;
},
.Struct =>
@field(report, tgt_fld.name) =
try populateStruct(&@field(ptr_tgt.*, tgt_fld.name), ast,
ast_fld_idx, ZonFieldResult.filled,
allocr, recursion_depth + 1),
.Array => // Target struct field is an array
@field(report, tgt_fld.name) =
try populateArray(&@field(ptr_tgt.*, tgt_fld.name), ast, ast_fld_idx,
allocr, recursion_depth + 1),
.Pointer => |ptr_info|
{
if (ptr_info.size == .Slice) // Target struct field is a slice
{
// `fn populateSlice()` returns its result via one of its arguments,
// `ptr_report`. This is because depending on the type of target slice elements,
// the result can be either a single ZonFieldResult enum (for primitive elements),
// or a slice of nested structs, arrays, slices that contain ZonFieldResult enums
// somewhere at the bottom.
// To be able to return the result, `ptr_report` must be a pointer to the var of
// the proper type.
const PopSliceResultType = MakeReportSliceType(tgt_fld.type);
var pop_slc_rslt = makeReportSlice(PopSliceResultType); // returns &.{} or ZonFieldResult.not_filled
// Pass a pointer to this slice field to `populateSlice`.
try populateSlice(&@field(ptr_tgt.*, tgt_fld.name), ast, ast_fld_idx,
allocr, &pop_slc_rslt, recursion_depth + 1);
@field(report, tgt_fld.name) = pop_slc_rslt;
}
else
std.log.warn("Struct field '" ++ tgt_fld.name ++ "' of pointer type " ++
tgt_fld.type ++ " found - not supported, skipping");
},
else => std.log.warn("Struct field '" ++ tgt_fld.name ++ "' of type " ++
tgt_fld.type ++ " found - not supported, skipping"),