-
Notifications
You must be signed in to change notification settings - Fork 9
/
stream.nt
804 lines (756 loc) · 29 KB
/
stream.nt
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
module std.json.stream;
macro import std.json.macro;
macro import std.macro.assert;
macro import std.macro.easymacro;
macro import std.macro.quasiquoting;
import std.error;
import std.json;
import std.stream;
/**
* A thing that can appear in a JSON stream.
*/
alias JsonToken = (
string |
nullptr_t |
bool |
int |
// double |
:arrayStart |
:arrayEnd |
:objectStart |
:objectEnd |
:comma |
:colon
);
///
string toString(JsonToken token) {
return token.case(
string s: "\"$s\"",
nullptr_t: "null",
bool b: "$b",
int i: "$i",
:comma: ",",
:colon: ":",
:arrayStart: "[",
:arrayEnd: "]",
:objectStart: "{",
:objectEnd: "}",
);
}
/**
* This error represents a problem while decoding JSON.
*/
class DecodeError : Error
{
override string toString() => "DecodeError($(this.message))";
}
/**
* Convert byte data into a stream of JSON tokens.
* The data arrives as a stream of byte arrays, usually representing
* read or receive calls.
*/
class JsonLexer : Source!JsonToken
{
private Source!(ubyte[]) source;
private ubyte[] buffer;
this(this.source) { }
override (JsonToken | :else | Error) get() {
import std.string : atoi;
(void | Error | fail :else) getMore() {
buffer ~= source.get.case(Error err: return err, :else: return :else);
}
bool isDigit(char ch) => ch >= '0' && ch <= '9';
void drop(int len = 1) { buffer = buffer[len .. $]; }
(bool | Error | fail :else) startswith(string cmp) {
for (i, ch in cmp) {
if (i == buffer.length) getMore?;
if (buffer[i] != cast(ubyte) ch)
return false;
}
return true;
}
while (true) {
if (buffer.empty) getMore?;
alias front = cast(char) buffer[0];
if (front == ' ' || front == '\r' || front == '\n') {
drop;
continue;
}
if (front == ',') { drop; return :comma; }
if (front == ':') { drop; return :colon; }
if (front == '{') { drop; return :objectStart; }
if (front == '}') { drop; return :objectEnd; }
if (front == '[') { drop; return :arrayStart; }
if (front == ']') { drop; return :arrayEnd; }
if (isDigit(front)) {
mut int len = 1;
while (true) {
if (len == buffer.length) getMore.case(:else: break, Error err: return err);
if (isDigit(cast(char) buffer[len])) {
len++;
continue;
}
break;
}
auto result = atoi((cast(char*) buffer.ptr)[0 .. len]);
drop(len);
return result;
}
if (startswith("true")?) {
drop(4);
return true;
}
if (startswith("false")?) {
drop(5);
return false;
}
if (startswith("null")?) {
drop(4);
return null;
}
if (front == '"') {
drop;
mut bool escaped = false;
mut string result;
while (true) {
if (buffer.empty) getMore?;
if (escaped) {
drop;
escaped = false;
continue;
}
if (front == '\\') {
drop;
escaped = true;
continue;
}
if (front == '"') {
drop;
break;
}
result ~= front;
drop;
}
return result;
}
return new DecodeError("Invalid content in JSON text: $((cast(char*) buffer.ptr)[0 .. buffer.length])", __RANGE__);
}
}
}
///
unittest
{
auto source = new StringSource(`{"a": 3, "b": [4, 5, 6], "c": "Hello World"}`);
auto source = new JsonLexer(source);
mut JsonToken[] tokens;
// while (auto token = source.get? else break) {
while (true) {
auto token = source.get.case(:else: break, Error: assert(false));
tokens ~= token;
}
assert(tokens == [
:objectStart,
"a", :colon, 3, :comma,
"b", :colon, :arrayStart,
4, :comma, 5, :comma, 6,
:arrayEnd, :comma,
"c", :colon, "Hello World",
:objectEnd,
]);
}
/**
* Convert a stream of JSON tokens into byte data.
* Note that the produced byte blocks are not very efficient; you will
* probably want to feed them through a flushable buffer sink before
* putting them in a socket.
*/
class JsonPrinter : Sink!JsonToken
{
Sink!(ubyte[]) sink;
this(this.sink) {}
override (void | Error) put(JsonToken token) {
(void | Error) put(string s) {
// TODO array cast
sink.put((cast(ubyte*) s.ptr)[0 .. s.length])?;
}
token.case {
string s:
// this is a very silly way to do it.
// TODO improve, for instance skip from escaped character to escaped character
put(`"`)?;
for (i, ch in s) {
if (ch == '"' || ch == '\\')
put("\\")?;
put(s[i .. i + 1])?;
}
put(`"`)?;
nullptr_t: put("null")?;
bool b: put("true" if b else "false")?;
int i: put("$i")?;
:comma: put(",")?;
:colon: put(":")?;
:arrayStart: put("[")?;
:arrayEnd: put("]")?;
:objectStart: put("{")?;
:objectEnd: put("}")?;
}
}
}
///
unittest
{
JsonToken[] tokens = [
:objectStart,
"a", :colon, 3, :comma,
"b", :colon, :arrayStart,
4, :comma, 5, :comma, 6,
:arrayEnd, :comma,
"c", :colon, "Hello World",
:objectEnd,
];
auto stringSink = new StringSink;
auto jsonSink = new JsonPrinter(stringSink);
for (token in tokens) jsonSink.put(token).case(Error: assert(false));
assert(stringSink.content == `{"a":3,"b":[4,5,6],"c":"Hello World"}`);
}
/**
* Convert a JSON value into a stream of JSON tokens.
*/
class JsonValueSource : Source!JsonToken
{
alias StackEntry = (
JSONValue |
JSONValue[], bool needComma |
(string key, JSONValue value)[], bool needComma |
JSONValue, (string key, JSONValue value)[], bool needColon);
StackEntry mut[] stack;
this(JSONValue value) {
this.stack ~= value;
}
StackEntry head() => this.stack[$ - 1];
void pop() {
this.stack = this.stack[0 .. $ - 1];
}
override (JsonToken | :else | Error) get() {
if (this.stack.empty)
return :else;
JsonToken transform(JSONValue value) {
value.value.case {
:false:
return false;
:true:
return true;
int i:
return i;
string s:
return s;
JSONValue[] array:
this.stack ~= (array, needComma=false);
return :arrayStart;
(string key, JSONValue value)[] obj:
this.stack ~= (obj, needComma=false);
return :objectStart;
}
}
head.case {
JSONValue value:
pop;
return transform(value);
(JSONValue[] array, bool needComma):
if (array.empty) {
pop;
return :arrayEnd;
} else if (needComma) {
this.stack[$ - 1] = (array, needComma=false);
return :comma;
} else {
auto nextValue = array[0];
this.stack[$ - 1] = (array[1 .. $], needComma=true);
return nextValue.transform;
}
((string key, JSONValue value)[] obj, bool needComma):
if (obj.empty) {
pop;
return :objectEnd;
} else if (needComma) {
this.stack[$ - 1] = (obj, needComma=false);
return :comma;
} else {
auto nextEntry = obj[0];
this.stack[$ - 1] = (nextEntry.value, obj[1 .. $], needColon=true);
return nextEntry.key;
}
(JSONValue nextValue, (string key, JSONValue value)[] obj, bool needColon):
if (needColon) {
this.stack[$ - 1] = (nextValue, obj, needColon=false);
return :colon;
} else {
this.stack[$ - 1] = (obj, needComma=true);
return nextValue.transform;
}
}
}
}
///
unittest
{
auto value = JSONValue({"a": 3, "b": [4, 5, 6], "c": "Hello World"});
auto source = new JsonValueSource(value);
mut JsonToken[] tokens;
// TODO
// while let (auto token = source.get? else break) {
while (true) {
auto token = source.get.case(:else: break, Error: assert(false));
tokens ~= token;
}
assert(tokens == [
:objectStart,
"a", :colon, 3, :comma,
"b", :colon, :arrayStart,
4, :comma, 5, :comma, 6,
:arrayEnd, :comma,
"c", :colon, "Hello World",
:objectEnd,
]);
}
/**
* Convert a stream of JSON tokens into a JSON value.
*/
class JsonValueSink : Sink!JsonToken
{
(JSONValue | :nothing) value;
(
:array, JSONValue[] |
:objectKey, (string, JSONValue)[] |
:objectValue, string key, (string, JSONValue)[]
) mut[] stack;
bool done() => value != :nothing && stack.empty;
this() {
this.value = :nothing;
}
override (void | Error) put(JsonToken token) {
(void | Error) set(JSONValue value) {
if (this.value != :nothing)
return new DecodeError("successive values in stream: $(token) after $(this.value)", __RANGE__);
this.value = value;
}
(void | Error) flush() {
JSONValue value = this.value.case(:nothing: return new DecodeError(
"invalid token order: got '$(token.toString)' but no value beforehand", __RANGE__));
this.stack[$ - 1].case {
(:array, JSONValue[] values):
stack[$ - 1] = (:array, values ~ value);
this.value = :nothing;
(:objectKey, (string, JSONValue)[]):
return new DecodeError(
"invalid token order: got '$(token.toString)' but expected object key", __RANGE__);
(:objectValue, string key, (string, JSONValue)[] values):
stack[stack.length - 1] = (:objectKey, values ~ (key, value));
this.value = :nothing;
}
}
token.case {
string s: set(JSONValue(s))?;
nullptr_t: set(JSONValue(null))?;
bool b: set(JSONValue(b))?;
int i: set(JSONValue(i))?;
// double d: set(JSONValue(d))?;
:arrayStart:
if (this.value != :nothing)
return new DecodeError("array immediately following value in stream", __RANGE__);
this.stack ~= (:array, null);
:comma:
flush?;
:arrayEnd:
if (this.value != :nothing) flush?;
this.stack[$ - 1].case {
(:array, JSONValue[] values):
this.value = JSONValue(values);
(:objectKey, (string, JSONValue)[]):
return new DecodeError("invalid token order: got ']' but expected object key", __RANGE__);
(:objectValue, string key, (string, JSONValue)[]):
return new DecodeError("invalid token order: got ']' but expected object value", __RANGE__);
}
this.stack = this.stack[0 .. $ - 1];
:objectStart:
if (this.value != :nothing)
return new DecodeError("object immediately following value in stream", __RANGE__);
this.stack ~= (:objectKey, null);
:objectEnd:
if (this.value != :nothing) flush?;
this.stack[$ - 1].case {
(:array, JSONValue[]):
return new DecodeError("invalid token order: got '}' but expected array value", __RANGE__);
(:objectKey, (string, JSONValue)[] values):
this.value = JSONValue(values);
(:objectValue, string key, (string, JSONValue)[]):
return new DecodeError("invalid token order: got '}' but expected object value", __RANGE__);
}
this.stack = this.stack[0 .. $ - 1];
:colon:
this.stack[$ - 1].case {
(:array, JSONValue[] values):
return new DecodeError("invalid token order: got ':' but expected array member", __RANGE__);
(:objectKey, (string, JSONValue)[] values):
JSONValue keyValue = this.value.case(:nothing: return new DecodeError(
"invalid token order: got ':' but expected object key", __RANGE__));
/*string key = keyValue.value.case(
string s: s,
default: return new DecodeError("invalid syntax: string expected before ':'", __RANGE__));*/
(string | fail DecodeError) key() {
keyValue.value.case {
string s: return s;
default: return new DecodeError(
"invalid syntax: string expected before ':'", __RANGE__);
}
}
stack[$ - 1] = (:objectValue, key?, values);
this.value = :nothing;
(:objectValue, string key, (string, JSONValue)[]):
return new DecodeError("invalid token order: got '$key:' but expected object value", __RANGE__);
}
}
}
}
/**
* Encode a value as a JSON token stream.
*/
(void | Error) encode(T)(T value, Sink!JsonToken sink) {
macro {
import neat.array;
import neat.struct_;
import neat.types;
import neat.util : NullPointer;
auto T = type("T")?;
if (T.instanceOf(Integer) || T.instanceOf(Long) || T.instanceOf(Short) || T.instanceOf(Boolean)) {
code { sink.put(value)?; }
} else if (T.instanceOf(NullPointer)) {
code { sink.put(null)?; }
} else if (T.same(type("JSONValue")?)) {
code {
auto source = new JsonValueSource(value);
while (true) {
// TODO sink.put(source.get.case(:else: break)?)?;
sink.put(source.get.case(:else: break, Error err: return err))?;
}
}
} else if (auto array_ = T.instanceOf(Array)) {
if (array_.elementType.instanceOf(Character)) {
code { sink.put(value)?; }
} else {
code {
sink.put(:arrayStart)?;
for (i, entry in value) {
if (i > 0) sink.put(:comma)?;
.encode(entry, sink)?;
}
sink.put(:arrayEnd)?;
}
}
} else if (auto struct_ = T.instanceOf(Struct)) {
code { sink.put(:objectStart)?; }
for (i, member in struct_.members) {
auto name = compiler.astIdentifier(member.name, __RANGE__);
auto nameStr = compiler.astStringLiteral(member.name, __RANGE__);
if (i > 0) code {
sink.put(:comma)?;
}
code {
sink.put($nameStr)?;
sink.put(:colon)?;
.encode(value.$name, sink)?;
}
}
code { sink.put(:objectEnd)?; }
} else {
return __RANGE__.fail("Don't know how to encode $(T.toString)");
}
}
}
///
unittest {
auto sink = new JsonValueSink;
5.encode(sink).case(Error: assert(false));
assert(sink.value == JSONValue(5));
}
///
unittest {
auto sink = new JsonValueSink;
[2, 3].encode(sink).case(Error: assert(false));
assert(sink.value == JSONValue([2, 3]));
}
///
unittest {
struct S {
int a;
string[] b;
bool c;
}
auto sink = new JsonValueSink;
S(2, ["foo", "bar"], false).encode(sink).case(Error: assert(false));
assert(sink.value == JSONValue({"a": 2, "b": ["foo", "bar"], "c": false}));
}
///
unittest {
auto sink = new JsonValueSink;
JSONValue({"a": 3}).encode(sink).case(Error: assert(false));
assert(sink.value == JSONValue({"a": 3}));
}
/**
* Decode a value from a JSON token stream.
*/
(T | Error) decode(T)(Source!JsonToken source) {
auto token = source.get? else return new DecodeError("end of input reached while decoding", __RANGE__);
return decodeWithToken!T(source, token);
}
///
unittest
{
auto source((JSONValue | string) a) => a.case(
JSONValue a: new JsonValueSource(a),
string s: new JsonLexer(new StringSource(s)));
assert(JSONValue(5).source.decode!int == 5);
assert(JSONValue(true).source.decode!bool == true);
assert(JSONValue("foo").source.decode!string == "foo");
assert(JSONValue([]).source.decode!(int[]) == []);
assert(JSONValue([2, 3, 4]).source.decode!(int[]) == [2, 3, 4]);
assert(JSONValue(["foo", "bar"]).source.decode!(string[]) == ["foo", "bar"]);
assert(`5`.source.decode!int == 5);
assert(`true`.source.decode!bool == true);
assert(`"foo"`.source.decode!string == "foo");
assert(`[]`.source.decode!(int[]) == []);
assert(`[2, 3, 4]`.source.decode!(int[]) == [2, 3, 4]);
assert(`["foo", "bar"]`.source.decode!(string[]) == ["foo", "bar"]);
assert(`{"a": 3}`.source.decode!JSONValue == JSONValue({"a": 3}));
struct S {
int a;
string[] b;
bool c;
string toString() => "S($a, $b, $c)";
}
assert(JSONValue({"a": 2, "b": ["foo", "bar"], "c": false}).source.decode!S == S(2, ["foo", "bar"], false));
assert(`{"a": 2, "b": ["foo", "bar"], "c": false}`.source.decode!S == S(2, ["foo", "bar"], false));
struct T {
int a = 5;
string toString() => "T(a=$a)";
}
assert(`{"b": {"c": [5], "d": "6"}}`.source.decode!T == T(5));
}
private (T | Error) decodeWithToken(T)(Source!JsonToken source, JsonToken token) {
macro {
import neat.array;
import neat.struct_;
import neat.types;
import neat.util : ASTSymbolHelper;
auto T = type("T")?;
if (T.instanceOf(Integer) || T.instanceOf(Long) || T.instanceOf(Short)) {
code {
token.case {
int i: return cast(T) i;
default: return new DecodeError("expected integer, but got $(token.toString)", __RANGE__);
}
}
} else if (T.instanceOf(Boolean)) {
code {
token.case {
bool b: return b;
default: return new DecodeError("expected boolean, but got $(token.toString)", __RANGE__);
}
}
} else if (T.same(type("JSONValue")?)) {
code {
auto sink = new JsonValueSink;
sink.put(token)?;
while (!sink.done) {
// TODO
// sink.put(source.get.case(:else: return new DecodeError(
// "ran out of content while decoding JSONValue", __RANGE__))?)?;
sink.put(source.get.case(Error err: return err, :else: return new DecodeError(
"ran out of content while decoding JSONValue", __RANGE__)))?;
}
return sink.value.case(:nothing: assert(false));
}
} else if (auto array_ = T.instanceOf(Array)) {
auto astElementType = new ASTSymbolHelper(array_.elementType);
if (array_.elementType.instanceOf(Character)) {
code {
token.case {
string s: return s;
default: return new DecodeError("expected string, but got $(token.toString)", __RANGE__);
}
}
} else {
code {
if (token != :arrayStart)
return new DecodeError("expected '[', but got $(token.toString)", __RANGE__);
mut T result;
while (true) {
auto token = source.get? else
return new DecodeError("end of input reached while decoding", __RANGE__);
if (token == :arrayEnd) break;
if (result.empty) {
result ~= .decodeWithToken!($astElementType)(source, token)?;
} else {
if (token != :comma)
return new DecodeError("expected ',', not $(token.toString)", __RANGE__);
result ~= .decode!($astElementType)(source)?;
}
}
return result;
}
}
} else if (auto struct_ = T.instanceOf(Struct)) {
code {
if (token != :objectStart)
return new DecodeError("expected '{', but got $(token.toString)", __RANGE__);
}
mut ASTSymbol[] args;
for (i, member in struct_.members) {
auto astName = compiler.astStringLiteral(member.name, __RANGE__);
auto astFieldType = new ASTSymbolHelper(member.type);
auto astField = compiler.astIdentifier("field$i", __RANGE__);
code { mut ($astFieldType | :none) $astField = :none; }
// TODO
// if let((Expression expr, LocRange range) = member.default_?) {
if let((Expression expr, LocRange range) pair = member.default_?) {
auto astExpr = new ASTSymbolHelper(pair.expr, pair.range);
args ~= compiler.$expr $astField.case(:none: $astExpr);
} else {
args ~= compiler.$expr
$astField.case(:none: return new DecodeError("missing field $($astName)", __RANGE__));
}
}
code {
// TODO single mode variable
mut bool startOfObject = true;
mut bool expectSeparator = false;
mut (string | :none) lastKey = :none;
while (true) {
auto token = source.get? else
return new DecodeError("end of input reached while decoding", __RANGE__);
token.case {
:objectEnd:
if (!expectSeparator && !startOfObject)
return new DecodeError("expected object key, but got '}'", __RANGE__);
break;
:comma:
if (expectSeparator) expectSeparator = false;
else return new DecodeError("unexpected ','", __RANGE__);
continue;
string key:
if (expectSeparator)
return new DecodeError("expected ',', but got '$(token.toString)'", __RANGE__);
if (lastKey != :none)
return new DecodeError("expected ':', but got '$(token.toString)'", __RANGE__);
lastKey = key;
continue;
:colon:
if (expectSeparator)
return new DecodeError("expected ',', but got '$(token.toString)'", __RANGE__);
string key = lastKey.case(:none: return new DecodeError(
"expected object key, but got '$(token.toString)'", __RANGE__));
lastKey = :none;
startOfObject = false;
macro {
for (i, member in struct_.members) {
auto astFieldType = new ASTSymbolHelper(member.type);
auto astField = compiler.astIdentifier("field$i", __RANGE__);
auto nameStr = compiler.astStringLiteral(member.name, __RANGE__);
code {
if (key == $nameStr) {
$astField = .decode!($astFieldType)(source)?;
expectSeparator = true;
continue;
}
}
}
}
// Ignore unknown keys in JSON
source.skipValue?;
expectSeparator = true;
continue;
default:
return new DecodeError("expected object key, but got '$(token.toString)'", __RANGE__);
}
}
}
auto call = compiler.(astCall(astIdentifier("T", __RANGE__), args, __RANGE__));
code { return $call; }
} else {
return __RANGE__.fail("Don't know how to decode $(T.toString)");
}
}
}
private (void | Error) skipValue(Source!JsonToken source) {
return source.skipValueWithToken(source.nextToken?);
}
private (void | Error) skipValueWithToken(Source!JsonToken source, JsonToken token) {
token.case {
string: return;
nullptr_t: return;
bool: return;
int: return;
// double: return;
:arrayStart:
auto token = source.nextToken?;
if (token == :arrayEnd) return;
source.skipValueWithToken(token)?;
while (true) {
auto token = source.nextToken?;
if (token == :arrayEnd) return;
if (token != :comma) return new DecodeError("expected ',' but got '$(token.toString)'", __RANGE__);
source.skipValue?;
}
:arrayEnd:
return new DecodeError("unexpected ']' in stream", __RANGE__);
:objectStart:
(void | Error) skipObjectMember(JsonToken token) {
token.case {
string: {}
default: return new DecodeError("expected object key, but got '$(token.toString)'", __RANGE__);
}
auto token = source.nextToken?;
if (token != :colon)
return new DecodeError("expected ':', but got '$(token.toString)'", __RANGE__);
source.skipValue?;
}
auto token = source.nextToken?;
if (token == :objectEnd) return;
skipObjectMember(token)?;
while (true) {
auto token = source.nextToken?;
if (token == :objectEnd) return;
if (token != :comma) return new DecodeError("expected ',' but got '$(token.toString)'", __RANGE__);
skipObjectMember(source.nextToken?)?;
}
:objectEnd:
return new DecodeError("unexpected '}' in stream", __RANGE__);
:comma:
return new DecodeError("unexpected ',' in stream", __RANGE__);
:colon:
return new DecodeError("unexpected ':' in stream", __RANGE__);
}
}
private (JsonToken | Error) nextToken(Source!JsonToken source) {
return source.get
.case(:else: new DecodeError("end of stream reached", __RANGE__));
}
private class StringSource : Source!(ubyte[]) {
bool empty;
string content;
this(this.content) { this.empty = false; }
override (ubyte[] | :else | Error) get() {
if (empty) return :else;
empty = true;
mut ubyte[] cast_;
for (ch in content) cast_ ~= cast(ubyte) ch;
return cast_;
}
}
private class StringSink : Sink!(ubyte[]) {
string content;
this() { }
override (void | Error) put(ubyte[] data) {
for (b in data) content ~= cast(char) b;
}
}