-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathjsonstream.pas
More file actions
2622 lines (2294 loc) · 61.8 KB
/
jsonstream.pas
File metadata and controls
2622 lines (2294 loc) · 61.8 KB
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
// JsonStream Pascal Implementation v1.0
//
// Copyright 2021 Philip Zander
//
// 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.
//
// Changelog:
// 2022-02-08: Release version 1.0.2
// - Fixes a rarely triggered off-by-one error
// 2021-12-23: Release version 1.0.1
// - Fixes assertion failure on skipping boolean value
// 2021-10-18: Release version 1.0.0
unit jsonstream;
{$ifdef FPC}
{$mode Delphi}
{$endif}
interface
uses
SysUtils, Classes;
type
TJsonString = string;
TJsonChar = char;
PJsonChar = ^TJsonChar;
TJsonFeature = (jfJson5);
TJsonFeatures = set of TJsonFeature;
TJsonState = (
jsError,
jsEOF,
jsDict,
jsDictEnd,
jsList,
jsListEnd,
jsNumber,
jsBoolean,
jsNull,
jsString,
jsKey
);
TJsonError = (
jeNoError = 0,
jeInvalidToken,
jeInvalidNumber,
jeUnexpectedToken,
jeTrailingComma,
jeUnexpectedEOF,
jeInvalidEscapeSequence,
jeNestingTooDeep
);
// Internal types
TJsonToken = (
jtUnknown, jtEOF, jtDict, jtDictEnd, jtList, jtListEnd, jtComma, jtColon,
jtNumber, jtDoubleQuote, jtSingleQuote, jtFalse, jtTrue, jtNull,
jtSingleLineComment, jtMultiLineComment
);
TJsonInternalState = (
jisInitial,
jisError,
jisEOF,
jisListHead,
jisAfterListItem,
jisListItem,
jisDictHead,
jisDictItem,
jisAfterDictItem,
jisDictKey,
jisAfterDictKey,
jisDictValue,
jisNumber,
jisBoolean,
jisNull,
jisString
);
TJsonStringMode = (
jsmDoubleQuoted,
jsmSingleQuoted,
jsmUnquoted
);
{ TJsonReader }
TJsonReader = class
protected
// === Parsing options ===
FFeatures: TJsonFeatures;
// === Input ===
FStream: TStream;
FBuf: array[0..1023] of TJsonChar;
// Length of FBuf
FLen: Integer;
// Position within FBuf
FPos: Integer;
// Offset of FBuf within the stream (only used for error information)
FOffset: SizeInt;
// === Tokenizer ===
// Current token type (at FBuf[FPos])
FToken: TJsonToken;
// == Stack machine ===
FStack: array of TJsonInternalState;
FState: TJsonState;
// === Number parsing ===
// FNumber contains the normalized decimal form of the number.
// I.e. Skips any leading zeroes and contains no decimal point, and may be
// followed by an exponent.
//
// Satisfies this regex: [-]?(0|[1-9][0-9])*(e[-]?[0-9]+)?
//
// Note that we have to store the digits in a string because
// decimal-to-binary floating-point conversions turn out to be *very*
// intricate. Up to 768 decimal digits may be required to accurately
// determine what the closest double precision value is, and JSON places no
// limit on the number of digits. We don't deal with this ourselves, we just
// pass it to the runtime and assume it handles it correctly.
//
// https://www.exploringbinary.com/17-digits-gets-you-there-once-youve-found-your-way/
FNumber: TJsonString;
// True = number could be parsed but is technically not a valid JSON number
FNumberErr: Boolean;
// === String parsing ===
// Delimiter of the current string (double-quote, single-quote, or word
// boundary)
FStringMode: TJsonStringMode;
// If an error occurred during Str() or Key(), the part that has been read
// is temporarily stored here between successive calls.
FSavedStr: TJsonString;
// True if we reached the end of the string
FStringEnd: Boolean;
// If Proceed was called after a string error: Tell string routines to
// ignore the error.
FStrIgnoreError: Boolean;
// Temporary storage for decoded escape sequences.
FEscapeSequence: TJsonString;
// Nesting depth of structures (lists + dicts), e.g. "[[" would be depth 2.
// This is different from Length(FStack) because FStack contains internal
// nodes such as jisDictValue etc.. This is checked against MaxNestingDepth
// and an error is generated if the maximum nesting depth is exceeded. The
// purpose of this is to guarantee an upper bound on memory consumption that
// doesn't grow linearly with the input in the worst case.
FNestingDepth: Integer;
FMaxNestingDepth: Integer;
// === Error recovery ===
// Stack depth up until which we must pop after an error.
FPopUntil: Integer;
// Stack depth up until which a skip was issued.
FSkipUntil: Integer;
// Whether current item should be skipped upon next call to Advance.
FSkip: Boolean;
// === Error information ===
FLastError: TJsonError;
FLastErrorMessage: TJsonString;
FLastErrorPosition:SizeInt;
// Tokenizer
procedure GetToken;
// Stack machine
function StackTop: TJsonInternalState;
procedure StackPush(State: TJsonInternalState);
function StackPop: TJsonInternalState;
procedure Reduce;
// Parsing helpers
procedure RefillBuffer(LookAhead: Integer = 1);
procedure SkipSpace;
procedure SkipGarbage;
procedure SkipSingleLineComment;
procedure SkipMultiLineComment;
function MatchString(const Str: TJsonString): Boolean;
procedure ParseNumber;
procedure FinalizeNumber;
// Skip helpers
procedure SkipNumber;
procedure SkipBoolean;
procedure SkipNull;
procedure SkipString;
procedure SkipKey;
// Key/Str helpers
function StrBufInternal(out Buf; BufSize: SizeInt): SizeInt;
function StrInternal(out S: TJsonString): Boolean;
// Other internal functions
function InternalAdvance: TJsonState;
function InternalProceed: Boolean;
procedure InvalidOrUnexpectedToken(const Msg: TJsonString);
function AcceptValue: boolean;
function AcceptKey: boolean;
procedure SetLastError(Error: TJsonError; const Msg: string);
public
// Construct a TJsonReader object. The input will be read from Stream. Pass
// [jfJson5] as Features to create a JSON5 parser instead of a regular JSON
// parser. You can specify a maximum allowable nesting depth with
// MaxNestingDepth. If this depth is exceeded, the parser will abort.
constructor Create(
Stream: TStream; Features: TJsonFeatures=[];
MaxNestingDepth: Integer=MaxInt
);
// === General traversal ===
// Move to the next element and return the new parse state.
function Advance: TJsonState;
// Return the current parse state.
function State: TJsonState;
// Skip current element. If the element is a list or a dict, then all its
// children will be skipped.
procedure Skip;
// === Acceptor functions for specific elements ===
// Returns true iff the current element is a dict entry and stores its key
// in K. If true is returned, then the key is stored in K and the reader
// is automatically advanced to the corresponding value.
// If false is returned, the current element is either not a key or an error
// ocurred during decoding (such as an invalid escape sequence or premature
// end of file) and the contents of K are undefined.
// If an error occured, you may call Proceed() to ignore it and call Key()
// again. This function only returns true once per element.
function Key(out K: TJsonString): Boolean;
// This function is like Key, except that it does not return the full key,
// but only reads part of it. This is intended for situations where the key
// could be very large and it would not be efficient to allocate it in
// memory its entirety. The semantics are the same as the read() syscall
// on Unix: Up to BufSize bytes are read and stored in Buf.
// Return value:
// > 0: The number of bytes actually read.
// = 0: Indicates the end of the key.
// < 0: An error occurred (invalid escape sequence or missing trailing ")
// or the value is not a key.
// If an error occurred, you can call Proceed() to ignore it and try to
// continue reading.
function KeyBuf(out Buf; BufSize: SizeInt): SizeInt;
// Returns true iff the current element is a valid string value.
// If true is returned, then the decoded string value is stored in S.
// If false is returned, the current element is either not a string or an
// error occurred during decoding (such as an invalid escape sequence or
// premature end of file) and the contents of S are undefined.
// If an error occurred, you may call Proceed() to ignore it and call Str()
// again. This function only returns true once per element.
function Str(out S: TJsonString): Boolean;
// This function is like Str, except that it does not return the full string,
// but only reads part of it. This is intended for situations where the
// string could be very large ind it would not be efficient to allocate it
// in memory in its entirety. The semantics are the same as the read()
// syscall on Unix: Up to BufSize bytes are read and stored in Buf.
// Return value:
// > 0: The number of bytes actually read.
// = 0: Indicates the end of the string.
// < 0: An error occurred (invalid escape sequence or missing trailing ")
// or the value is not a string.
// If an error occurred, you can call Proceed() to ignore it and try to
// continue reading.
function StrBuf(out Buf; BufSize: SizeInt): SizeInt;
// Returns true iff the current element is a number that can be exactly
// represented by an integer and returns its value in Num. This function only
// return true once per element.
function Number(out Num: Integer): Boolean; overload;
// Returns true iff the current element is a number that can be exactly
// represented by an integer and returns its value in Num. This function only
// return true once per element.
function Number(out Num: Cardinal): Boolean; overload;
// Returns true iff the current element is a number that can be exactly
// represented by an int64 and returns its value in Num. This function only
// returns true once per element.
function Number(out Num: Int64): Boolean; overload;
// Returns true iff the current element is a number that can be exactly
// represented by an uint64 and returns its value in Num. This function only
// returns true once per element.
function Number(out Num: UInt64): Boolean; overload;
// Returns true iff the current element is a number and returns its value
// in Num. If the number exceeds the representable precision or range of a
// double precision float, it will be rounded to the closest approximation.
// This function only returns true once per element.
function Number(out Num: Double): Boolean; overload;
// Returns true iff the current element is a boolean and returns its value
// in bool. This function only returns true once per element.
function Bool(out Bool: Boolean): Boolean;
// Returns true iff the current element is a null value. This function only
// returns true once per element.
function Null: Boolean;
// Returns true iff the current element is a dict. If true is returned,
// then the next element will be the first child of the dict.
function Dict: Boolean;
// Returns true iff the current element is a list. If true is returned,
// then the next element will be the first child of the list.
function List: Boolean;
// Returns true if the last operation resulted in an error. You can then
// check the LastError and LastErrorMessage functions to learn more about
// the error. You can call Proceed to try to recover from the error and
// continue parsing. Otherwise no further tokens will be consumed and all
// open elements will be closed.
function Error: Boolean;
// === Error handling ===
// Proceed after a parse error. If this is not called after an error is
// encountered, no further tokens in the file will be processed.
function Proceed: Boolean;
// Return last error code. A return value of 0 means that there was no
// error. A return value other than 0 indicates that there was an error.
function LastError: TJsonError;
// Return error message for last error.
function LastErrorMessage: TJsonString;
// Location of the last error
function LastErrorPosition: SizeInt;
end;
{ TJsonWriter }
EJsonWriterError = class(Exception);
EJsonWriterUnsupportedValue = class(EJsonWriterError);
EJsonWriterSyntaxError = class(EJsonWriterError);
TJsonWriter = class
protected
FStream: TStream;
FNeedComma: Boolean;
FNeedColon: Boolean;
FStructEmpty: Boolean;
FWritingString: Boolean;
FLevel: Integer;
FFeatures: TJsonFeatures;
FPrettyPrint: Boolean;
FIndentation: string;
FStack: array of TJsonInternalState;
procedure WriteSeparator(Indent: Boolean = true);
procedure Write(const S: TJsonString);
procedure WriteBuf(const Buf; BufSize: SizeInt);
procedure StrBufInternal(const Buf; BufSize: SizeInt; IsKey: Boolean);
procedure ValueBegin(const Kind: string);
procedure ValueEnd;
procedure KeyBegin;
procedure KeyEnd;
function StackTop: TJsonInternalState;
procedure StackPush(State: TJsonInternalState);
function StackPop: TJsonInternalState;
public
constructor Create(
Stream: TStream; Features: TJsonFeatures=[];
PrettyPrint: Boolean=false; const Indentation: string=' '
);
procedure Key(const K: TJsonString);
// Streaming equivalent of the Key() method. See StrBuf().
procedure KeyBuf(const Buf; BufSize: SizeInt);
procedure Str(const S: TJsonString);
// Streaming equivalent of the Str() method. To indicate the end of the
// string, call once with BufSize set to 0.
// Note: To write an empty string, you have to call the method twice:
// StrBuf(..., 0); // Write 0 bytes
// StrBuf(..., 0); // Signal end of string
procedure StrBuf(const Buf; BufSize: SizeInt);
procedure Number(Num: Integer); overload;
procedure Number(Num: Cardinal); overload;
procedure Number(Num: Int64); overload;
procedure Number(Num: UInt64); overload;
// Write number if hexadecimal format, if possible. This required jfJson5 to
// be included in Features. If jfJson5 is not included in Features, a
// decimal number will be written, instead.
procedure NumberHex(Num: UInt64); overload;
procedure Number(Num: Double); overload;
procedure Bool(Bool: Boolean);
procedure Null;
procedure Dict;
procedure DictEnd;
procedure List;
procedure ListEnd;
end;
implementation
uses
math
{$ifdef FPC}
{$ifndef MSWINDOWS}
, cwstring
{$endif}
{$endif}
;
type
TJsonCharArray =
array[0..High(SizeInt) div sizeof(TJsonChar) - 1] of TJsonChar;
{ TJsonReader }
constructor TJsonReader.Create(Stream: TStream; Features: TJsonFeatures;
MaxNestingDepth: integer);
begin
FStream := Stream;
FLen := 0;
FPos := 0;
FPopUntil := -1;
FSkipUntil := MaxInt;
FSkip := false;
FSavedStr := '';
FFeatures := Features;
FLastError := jeNoError;
FLastErrorPosition := 0;
FMaxNestingDepth := MaxNestingDepth;
StackPush(jisInitial);
Advance;
end;
procedure TJsonReader.RefillBuffer(LookAhead: Integer);
var
Delta: LongInt;
begin
if FPos + LookAhead > FLen then
begin
assert(FPos <= FLen);
if Flen > FPos then
Move(FBuf[FPos], FBuf[0], FLen - FPos);
Inc(FOffset, FPos);
FLen := FLen - FPos;
FPos := 0;
repeat
Delta := FStream.Read(FBuf[Flen], length(FBuf) - FLen);
if Delta <= 0 then
break;
Inc(FLen, Delta);
until FPos + LookAhead <= FLen;
end;
assert((FPos < FLen) or (FLen = 0));
end;
type
TSetOfChar = set of char;
procedure SkipCharSet(Reader: TJsonReader; Chars: TSetOfChar);
begin
repeat
while (Reader.FPos < Reader.FLen) and (Reader.FBuf[Reader.FPos] in Chars) do
Inc(Reader.FPos);
if Reader.FPos < Reader.FLen then
break;
Reader.RefillBuffer;
until Reader.FLen <= 0;
end;
procedure TJsonReader.SkipSpace;
begin
SkipCharSet(self, [' ', #9, #13, #10]);
end;
procedure TJsonReader.SkipGarbage;
begin
SkipCharSet(self, [#0..#32]);
end;
procedure TJsonReader.SkipSingleLineComment;
begin
SkipCharSet(Self, [#0..#255] - [#10, #13]);
end;
procedure TJsonReader.SkipMultiLineComment;
begin
while true do
begin
SkipCharSet(Self, [#0..#255] - ['*']);
Inc(FPos);
RefillBuffer;
if FLen <= 0 then
break;
if FBuf[FPos] = '/' then
begin
Inc(FPos);
break;
end;
end;
end;
procedure TJsonReader.SkipNumber;
begin
if FState <> jsNumber then
Exit;
FNumber := '';
FSkip := false;
StackPop;
Reduce;
end;
procedure TJsonReader.SkipNull;
begin
Null;
end;
procedure TJsonReader.SkipBoolean;
begin
StackPop;
Reduce;
FSkip := false;
end;
procedure TJsonReader.SkipString;
var
Buf: array[0..1024] of TJsonChar;
n: SizeInt;
begin
repeat
n := StrBufInternal(Buf, sizeof(Buf));
until n <= 0;
FSkip := false;
end;
procedure TJsonReader.SkipKey;
begin
SkipString;
end;
const
WordBoundaryChars: set of TJsonChar =
[#0..#32, '[', ']', '{', '}', ':', ',', ';', '"', '/'];
function TJsonReader.MatchString(const Str: TJsonString): Boolean;
var
i: Integer;
begin
Result := false;
// +1 because we need to check if the character after the string as a word
// boundary
RefillBuffer(Length(Str) + 1);
if FLen < length(Str) then
exit;
for i := 0 to length(Str) - 1 do
if FBuf[FPos + i] <> Str[i + 1] then
exit;
if (FLen > length(Str)) and
not (FBuf[FPos + length(Str)] in WordBoundaryChars) then
exit;
Result := true;
end;
const
sInfinity = 'Infinity';
sNaN = 'NaN';
procedure TJsonReader.ParseNumber;
var
Buf: array[0..768-1 + 1 { sign }] of TJsonChar;
i, n: Integer;
Exponent: Integer;
LeadingZeroes: Integer;
TmpExp: Integer;
TmpExpSign: Integer;
label
Finalize;
function SkipZero: Integer;
var
j: Integer;
begin
Result := 0;
while (FBuf[FPos] = '0') do
begin
for j := FPos to FLen - 1 do
begin
if FBuf[FPos] <> '0' then
break;
Inc(Result);
Inc(FPos);
end;
RefillBuffer;
end;
end;
function ReadDigits(Digits: TSetOfChar=['0'..'9']): Integer;
var
j: Integer;
begin
Result := 0;
while (FLen > 0) and (FBuf[FPos] in Digits) do
begin
for j := FPos to FLen - 1 do
begin
if not (FBuf[FPos] in Digits) then
break;
if n < sizeof(Buf) then
begin
Buf[n] := FBuf[FPos];
Inc(n);
end;
Inc(FPos);
Inc(Result);
end;
RefillBuffer;
end;
end;
begin
n := 0;
Exponent := 0;
FNumber := '';
FNumberErr := false;
RefillBuffer(2);
// Hex number (JSON5)
if (jfJson5 in FFeatures) and (FBuf[FPos] = '0') and (FPos + 1 < FLen) and
(FBuf[FPos + 1] in ['x', 'X']) then
begin
Inc(FPos, 2);
RefillBuffer;
Buf[n] := '$';
Inc(n);
if (ReadDigits(['0'..'9', 'a'..'f', 'A'..'F']) <= 0) then
begin
FNumberErr := true;
SetLastError(jeInvalidNumber, 'Invalid hexadecimal number.');
end;
goto Finalize;
end;
// NaN
if (jfJson5 in FFeatures) and MatchString(sNaN) then
begin
Move(sNaN[1], Buf[n], Length(sNaN));
Inc(FPos, Length(sNaN));
Inc(n, Length(sNaN));
goto Finalize;
end;
// Sign
if FBuf[FPos] in ['-','+'] then
begin
// Leading + not allowed by JSON
if (FBuf[FPos] = '+') and not (jfJson5 in FFeatures) then
begin
FNumberErr := true;
SetLastError(jeInvalidNumber, 'Number has leading `+`.');
end;
if (FBuf[FPos] = '-') then
begin
Buf[n] := FBuf[FPos];
Inc(n);
end;
Inc(FPos);
RefillBuffer;
end;
// Infinity
if (jfJson5 in FFeatures) and MatchString(sInfinity) then
begin
Move(sInfinity[1], Buf[n], Length(sInfinity));
Inc(FPos, Length(sInfinity));
Inc(n, Length(sInfinity));
goto Finalize;
end;
// Decimal number
LeadingZeroes := SkipZero;
RefillBuffer;
// JSON does not allow leading zeroes
if (LeadingZeroes > 1) or
(LeadingZeroes > 0) and (FLen >= 0) and (FBuf[FPos] in ['0'..'9']) then
begin
FNumberErr := true;
SetLastError(jeInvalidNumber, 'Number has leading zeroes.');
end;
if (LeadingZeroes > 0) and
not ((FLen >= 0) and (FBuf[FPos] in ['0'..'9'])) then
begin
if (FLen >= 0) and (FBuf[FPos] = '.') then
begin
// 0.something
Inc(FPos);
RefillBuffer;
// JSON requires digit after decimal point
if (FLen < 0) or not (FBuf[FPos] in ['0'..'9']) then
begin
FNumberErr := true;
SetLastError(jeInvalidNumber, 'Expected digit after decimal point.');
end;
Exponent := -SkipZero;
Exponent := Exponent - ReadDigits;
end
else
begin
// Just 0
Buf[0] := '0';
n := 1;
end;
end
else
begin
// JSON number must have a digit before the decimal point (except in JSON5)
if (ReadDigits <= 0) and not (jfJson5 in FFeatures) then
FNumberErr := true;
if FBuf[FPos] = '.' then
begin
Inc(FPos);
RefillBuffer;
// JSON (but not JSON5) requires digit after decimal point
if ((FLen < 0) or not (FBuf[FPos] in ['0'..'9'])) and
not (jfJson5 in FFeatures) then
begin
FNumberErr := true;
SetLastError(jeInvalidNumber, 'Expected digit after decimal point.');
end;
Exponent := -ReadDigits;
end;
end;
if FBuf[FPos] in ['e', 'E'] then
begin
Inc(FPos);
RefillBuffer;
TmpExp := 0;
TmpExpSign := +1;
if (FBuf[FPos] in ['-', '+']) then
begin
if FBuf[FPos] = '-' then
TmpExpSign := -1;
Inc(FPos);
RefillBuffer;
end;
SkipZero;
for i := FPos to FLen - 1 do
begin
if not (FBuf[FPos] in ['0'..'9']) then
break;
// The exponent range for double is something like -324 to +308, i.e. the
// exponent will never have more than 3 digits. We just want to make sure
// we don't overflow for pathological inputs. Truncating the exponent is
// not a problem as values exceeding the possible exponent range will be
// rounded to -INF or +INF, anyway.
if TmpExp < 10000 then
TmpExp := TmpExp * 10 + (ord(FBuf[FPos]) - ord('0'));
Inc(FPos);
end;
Exponent := Exponent + TmpExpSign * TmpExp;
end;
Finalize:
FNumber := Copy(Buf, 1, n);
if Exponent <> 0 then
FNumber := FNumber + 'e' + IntToStr(Exponent);
// Check if there is garbage at the end
RefillBuffer;
if (FLen > 0) and not (FBuf[FPos] in WordBoundaryChars) then
begin
StackPop; // Was never a number to begin with
StackPush(jisNull);
StackPush(jisError);
FState := jsError;
SetLastError(jeInvalidToken, 'Invalid token.');
// Skip rest of token
repeat
while (FPos < FLen) and not (FBuf[FPos] in WordBoundaryChars) do
Inc(FPos);
RefillBuffer;
until (FPos < FLen) or (FLen <= 0);
exit;
end;
if FNumberErr then
begin
FState := jsError;
StackPush(jisError);
end
end;
procedure TJsonReader.GetToken;
begin
SkipSpace;
if FLen <= 0 then
begin
FToken := jtEOF;
Exit;
end;
assert(FPos < FLen);
FToken := jtUnknown;
case FBuf[FPos] of
'{': FToken := jtDict;
'}': FToken := jtDictEnd;
'[': FToken := jtList;
']': FToken := jtListEnd;
',': FToken := jtComma;
':': FToken := jtColon;
'0'..'9', '-', '+':
FToken := jtNumber;
'.': if (jfJson5 in FFeatures) then
FToken := jtNumber;
'I': if (jfJson5 in FFeatures) and MatchString('Infinity') then
FToken := jtNumber;
'N': if (jfJson5 in FFeatures) and MatchString('NaN') then
FToken := jtNumber;
'"': FToken := jtDoubleQuote;
'''': if jfJson5 in FFeatures then
FToken := jtSingleQuote;
'/': if jfJson5 in FFeatures then
begin
RefillBuffer(1);
if FBuf[FPos + 1] = '/' then
FToken := jtSingleLineComment
else if FBuf[FPos + 1] = '*' then
FToken := jtMultiLineComment;
end;
't': if MatchString('true') then
FToken := jtTrue;
'f': if MatchString('false') then
FToken := jtFalse;
'n': if MatchString('null') then
FToken := jtNull;
end;
end;
function TJsonReader.StackTop: TJsonInternalState;
begin
assert(Length(FStack) > 0);
Result := FStack[High(FStack)];
end;
procedure TJsonReader.StackPush(State: TJsonInternalState);
begin
SetLength(FStack, Length(FStack) + 1);
FStack[High(FStack)] := State;
end;
function TJsonReader.StackPop: TJsonInternalState;
begin
assert(Length(FStack) > 0);
Result := FStack[High(FStack)];
SetLength(FStack, Length(FStack) - 1);
end;
procedure TJsonReader.Reduce;
begin
assert(Length(FStack) > 0);
while true do
case StackTop of
jisDictKey:
begin
StackPop;
StackPush(jisAfterDictKey);
end;
jisString:
begin
StackPop;
end;
jisDictValue:
begin
StackPop;
StackPop;
StackPush(jisAfterDictItem);
end;
jisListHead, jisListItem:
begin
StackPop;
StackPush(jisAfterListItem);
end
else
break;
end;
end;
function TJsonReader.Advance: TJsonState;
var
NewSkip: Integer;
BeenSkipping: Boolean;
begin
if StackTop in [jisListHead, jisDictHead] then
NewSkip := High(FStack) - 1
else
NewSkip := High(FStack);
if FSkip and (NewSkip < FSkipUntil) then
FSkipUntil := NewSkip;
while true do
begin
case InternalAdvance of
jsError:
break;
end;
if High(FStack) <= FSkipUntil then
begin
BeenSkipping := FSkipUntil < MaxInt;
FSkipUntil := MaxInt;
// When skipping from inside a structure like this:
//
// [
// *Skip*
//
// After skipping, we still get the closing ]. But the user who called
// Skip() is not interested in this token, so we have to eat it.
if BeenSkipping and (StackTop in [jisAfterListItem, jisAfterDictItem])then
InternalAdvance;
break;
end;
end;
Result := FState;
FSkip := Result in [jsDict, jsKey, jsList, jsNumber, jsString, jsBoolean, jsNull];
end;
function TJsonReader.State: TJsonState;
begin
Result := FState;
end;
function TJsonReader.InternalAdvance: TJsonState;
label
start;
var
PoppedItem: TJsonInternalState;
begin