-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathNeslib.Json.IO.pas
1730 lines (1462 loc) · 43.8 KB
/
Neslib.Json.IO.pas
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
unit Neslib.Json.IO;
{< Classes for reading and writing JSON. }
{$INCLUDE 'Neslib.inc'}
interface
uses
System.Classes,
System.SysUtils,
Neslib.Json.Types;
type
{ The current state of an IJsonReader. }
TJsonReaderState = (
{ The end of the JSON stream has been reached. }
EndOfStream,
{ The reader is positioned at a Null value. }
Null,
{ The reader is positioned at a Boolean value. }
Boolean,
{ The reader is positioned at an ordinal value. }
Ordinal,
{ The reader is positioned at a floating-point value. }
Float,
{ The reader is positioned at a string value. }
&String,
{ The reader is positioned at the name of a name/value pair in a dictionary. }
Name,
{ The reader is positioned at the start of an array. }
StartArray,
{ The reader is positioned at the end of an array. }
EndArray,
{ The reader is positioned at the start of a dictionary. }
StartDictionary,
{ The reader is positioned at the end of a dictionary. }
EndDictionary);
type
{ Exception type that is raised on parsing errors. }
EJsonParserError = class(Exception)
{$REGION 'Internal Declarations'}
private
FLineNumber: Integer;
FColumnNumber: Integer;
FPosition: Integer;
public
constructor Create(const AMsg: String; const ALineNumber,
AColumnNumber, APosition: Integer);
{$ENDREGION 'Internal Declarations'}
public
{ The line number of the error in the source text, starting at 1. }
property LineNumber: Integer read FLineNumber;
{ The column number of the error in the source text, starting at 1. }
property ColumnNumber: Integer read FColumnNumber;
{ The position of the error in the source text, starting at 0.
The position is the offset (in characters) from the beginning of the
text. }
property Position: Integer read FPosition;
end;
type
{ Interface for reading data in JSON format.
Implemented in TJsonReader. }
IJsonReader = interface
['{05F6A53B-9773-4047-99B0-4332C7C287CD}']
{ Reads the next piece of data from the JSON stream.
Parameters:
AState: is set to the current state of the reader. That is, it indicates
at what kind of value the reader is currently positioned. Depending
on AState, you use one of the Read* methods to read the actual
value.
Returns:
True if more data is available, or False if the end of the stream has
been reached.
Raises:
EJsonParserError if the JSON data is invalid. }
function Next(out AState: TJsonReaderState): Boolean;
{ Reads a Null value from the stream.
You should call this method if the AState parameter of the Next method
is set to Null.
Raises:
EJsonParserError if the reader is not positioned at a Null value. }
procedure ReadNull;
{ Reads a Boolean value from the stream.
You should call this method if the AState parameter of the Next method
is set to Boolean.
Returns:
The read value.
Raises:
EJsonParserError if the reader is not positioned at a Boolean value. }
function ReadBoolean: Boolean;
{ Reads an ordinal value from the stream.
You should call this method if the AState parameter of the Next method
is set to Ordinal.
Returns:
The read value.
Raises:
EJsonParserError if the reader is not positioned at an ordinal value. }
function ReadOrdinal: Int64;
{ Reads a floating-point value from the stream.
You should call this method if the AState parameter of the Next method
is set to Float.
Returns:
The read value.
Raises:
EJsonParserError if the reader is not positioned at a floating-point
value. }
function ReadFloat: Double;
{ Reads a string value from the stream.
You should call this method if the AState parameter of the Next method
is set to String.
Returns:
The read value.
Raises:
EJsonParserError if the reader is not positioned at a string value.
NOTE: Do NOT use this method to read dictionary names. Use ReadName
instead. }
function ReadString: JsonString;
{ Reads a dictionary name from the stream.
You should call this method if the AState parameter of the Next method
is set to Name.
Returns:
The read dictionary name.
Raises:
EJsonParserError if the reader is not positioned at a dictionary name. }
function ReadName: JsonString;
{ Consumes the "start array" token ([) from the stream.
You should call this method if the AState parameter of the Next method
is set to StartArray.
Raises:
EJsonParserError if the reader is not positioned at the start of an
array. }
procedure ReadStartArray;
{ Consumes the "end array" token (]) from the stream.
You should call this method if the AState parameter of the Next method
is set to EndArray.
Raises:
EJsonParserError if the reader is not positioned at the end of an
array. }
procedure ReadEndArray;
(*Consumes the "start dictionary" token ({) from the stream.
You should call this method if the AState parameter of the Next method
is set to StartDictionary.
Raises:
EJsonParserError if the reader is not positioned at the start of a
dictionary.*)
procedure ReadStartDictionary;
(*Consumes the "end dictionary" token (}) from the stream.
You should call this method if the AState parameter of the Next method
is set to EndDictionary.
Raises:
EJsonParserError if the reader is not positioned at the end of a
dictionary.*)
procedure ReadEndDictionary;
end;
type
{ Interface for writing data in JSON format.
Implemented in TJsonWriter. }
IJsonWriter = interface
['{B94DDA07-B67A-4C75-B3F7-FFD0BC788404}']
{ Writes a Null value. }
procedure WriteNull;
{ Writes a Boolean value.
Parameters:
AValue: the value to write. }
procedure WriteBoolean(const AValue: Boolean);
{ Writes an ordinal value.
Parameters:
AValue: the value to write. }
procedure WriteOrdinal(const AValue: Int64);
{ Writes a floating-point value.
Parameters:
AValue: the value to write. }
procedure WriteFloat(const AValue: Double);
{ Writes a string value.
Parameters:
AValue: the value to write.
NOTE: Do NOT use this method to write dictionary names. Use WriteName
instead. }
procedure WriteString(const AValue: JsonString);
{ Writes a dictionary name.
Parameters:
AValue: the dictionary name to write. }
procedure WriteName(const AName: JsonString);
{ Writes a "start array" token ([) }
procedure WriteStartArray;
{ Writes an "end array" token (]) }
procedure WriteEndArray;
(* Writes a "start dictionary" token ({) *)
procedure WriteStartDictionary;
(* Writes an "end dictionary" token (}) *)
procedure WriteEndDictionary;
{ Returns the written data in JSON format. }
function ToJson: JsonString;
end;
type
{ Class for reading data in JSON format.
Implements IJsonReader. }
TJsonReader = class(TInterfacedObject, IJsonReader)
{$REGION 'Internal Declarations'}
private type
TState = (TopLevel, &Array, DictionaryName, DictionaryValue);
private type
PContext = ^TContext;
TContext = record
public
State: TState;
HasElements: Boolean;
public
procedure Init(const AState: TState); inline;
end;
{$IFDEF JSON_STRING_INTERNING}
private
FStringInternPool: TJsonStringInternPool;
{$ENDIF}
private
FJson: JsonString;
FBuffer: PJsonChar;
FCurrent: PJsonChar;
FLineStart: PJsonChar;
FLineNumber: Integer;
FContextStack: TArray<TContext>;
FContextIndex: Integer;
FOrdValue: Int64;
FFloatValue: Double;
FStringValue: JsonString;
FContext: PContext;
FState: TJsonReaderState;
FBoolValue: Boolean;
private
procedure PushContext(const AState: TState);
procedure PopContext;
function ParseError(const AMsg: PResStringRec): EJsonParserError; overload;
function ParseError(const AMsg: String): EJsonParserError; overload;
procedure SkipWhitespace;
function ParseNumber: TJsonReaderState;
procedure ParseString;
procedure ParseUnquotedString;
procedure ParseEscapedString(const AStart, ACur: PJsonChar);
private
class function IsDelimiter(const AChar: JsonChar): Boolean; static; inline;
protected
{ IJsonReader }
function Next(out AState: TJsonReaderState): Boolean;
procedure ReadNull;
function ReadBoolean: Boolean;
function ReadOrdinal: Int64;
function ReadFloat: Double;
function ReadString: JsonString;
function ReadName: JsonString;
procedure ReadStartArray;
procedure ReadEndArray;
procedure ReadStartDictionary;
procedure ReadEndDictionary;
public
destructor Destroy; override;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a reader using a JSON formatted string to parse.
Parameters:
AJson: the JSON string to parse. }
constructor Create(const AJson: JsonString);
{ Creates a reader from a file.
Parameters:
AFilename: the name of the file to load.
Returns:
The reader. }
class function Load(const AFilename: String): IJsonReader; overload; static;
{ Creates a reader from a stream.
Parameters:
AStream: the stream to load.
Returns:
The reader. }
class function Load(const AStream: TStream): IJsonReader; overload; static;
end;
type
{ Class for writing data in JSON format.
Implements IJsonWriter. }
TJsonWriter = class(TInterfacedObject, IJsonWriter)
{$REGION 'Internal Declarations'}
private type
TState = (TopLevel, &Array, Dictionary);
private type
PContext = ^TContext;
TContext = record
public
Indent: Integer;
State: TState;
HasElements: Boolean;
public
procedure Init(const AParent: PContext; const AState: TState;
const AIndent: Integer); inline;
end;
private
FBuffer: PByte;
FSize: Integer;
FCapacity: Integer;
FContextStack: TArray<TContext>;
FContextIndex: Integer;
FContext: PContext;
FIndent: Integer;
FIndentation: TArray<JsonChar>;
FName: JsonString;
FLineBreak: JsonChar;
private
procedure PushContext(const AState: TState; const AIndent: Integer);
procedure PopContext;
procedure WriteStartValue;
procedure WriteQuotedString(const AValue: JsonString); inline;
procedure WriteEscapedString(const AValue: JsonString);
private
procedure Append(const AValue; const ASize: Integer); overload;
procedure Append(const AValue: JsonString); overload; inline;
procedure Append(const AValue: JsonChar); overload; inline;
procedure Append(const AValue: Int64); overload; inline;
protected
procedure WriteNull;
procedure WriteBoolean(const AValue: Boolean);
procedure WriteOrdinal(const AValue: Int64);
procedure WriteFloat(const AValue: Double);
procedure WriteString(const AValue: JsonString);
procedure WriteName(const AName: JsonString);
procedure WriteStartArray;
procedure WriteEndArray;
procedure WriteStartDictionary;
procedure WriteEndDictionary;
function ToJson: JsonString;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a new writer.
Parameters:
AIndent: flag indicating whether you want indented (or pretty-printed)
output. If True, nested values will be indented and line breaks will
be inserted. If False, then no line breaks and indentation will be
used. }
constructor Create(const AIndent: Boolean);
{ Destructor }
destructor Destroy; override;
end;
resourcestring
RS_JSON_UNEXPECTED_EOF = 'Unexpected end of JSON data.';
RS_JSON_UNEXPECTED_CHARACTER = 'Unexpected character in JSON data.';
RS_JSON_UNEXPECTED_COMMA = 'Unexpected comma in JSON data.';
RS_JSON_INVALID_STATE = 'JSON reader called in invalid state.';
RS_JSON_INVALID_NUMBER = 'Invalid number in JSON data.';
RS_JSON_INVALID_STRING = 'Invalid character JSON string.';
RS_JSON_CLOSE_BRACKET_EXPECTED = 'Close bracket ("]") expected in JSON data.';
RS_JSON_CLOSE_BRACE_EXPECTED = 'Curly close brace ("}") expected in JSON data.';
RS_JSON_DUPLICATE_COMMA = 'Duplicate comma (",") in JSON data.';
RS_JSON_COMMA_EXPECTED = 'Comma (",") expected in JSON data.';
RS_JSON_COLON_EXPECTED = 'Colon (":") expected in JSON data.';
RS_JSON_NAME_EXPECTED = 'Dictionary name expected in JSON data.';
RS_JSON_ILLEGAL_UNQUOTED_STRING = 'Unquoted string in JSON data only valid for dictionary names.';
RS_JSON_INVALID_CODEPOINT = 'Invalid Unicode codepoint in JSON string.';
{$REGION 'Internal Declarations'}
const
_FLAG_DELIMITER = $80; // Whitespace, ',', ':', '"', '{', '}', '[', ']'
const
_CHAR_BITS: array [#0..#127] of Byte = (
$8F, $80, $80, $80, $80, $80, $80, $80, // #$00-#$07
$80, $80, $80, $80, $80, $80, $80, $80, // #$08-#$0F
$80, $80, $80, $80, $80, $80, $80, $80, // #$10-#$17
$80, $80, $80, $80, $80, $80, $80, $80, // #$18-#$1F
$80, $00, $85, $00, $07, $00, $00, $00, // !"#$%&'
$00, $00, $00, $00, $88, $06, $06, $00, // ()*+,-./
$06, $06, $06, $06, $06, $06, $06, $06, // 01234567
$06, $06, $80, $00, $00, $00, $00, $00, // 89:;<=>?
$00, $07, $07, $07, $07, $07, $07, $07, // @ABCDEFG
$07, $07, $07, $07, $07, $07, $07, $07, // HIJKLMNO
$07, $07, $07, $07, $07, $07, $07, $07, // PQRSTUVW
$07, $07, $07, $83, $00, $84, $00, $07, // XYZ[\]^_
$00, $07, $07, $07, $07, $07, $07, $07, // `abcdefg
$07, $07, $07, $07, $07, $07, $07, $07, // hijklmno
$07, $07, $07, $07, $07, $07, $07, $07, // pqrstuvw
$07, $07, $07, $81, $00, $82, $00, $00); // xyz{|}~
{$ENDREGION 'Internal Declarations'}
implementation
uses
System.Math,
Neslib.Utf8,
Neslib.SysUtils,
Neslib.Hash;
const
// Character tokens and flags
TOKEN_INVALID = $00; // #0
TOKEN_START_DICT = $01; // '{'
TOKEN_END_DICT = $02; // '}'
TOKEN_START_ARRAY = $03; // '['
TOKEN_END_ARRAY = $04; // ']'
TOKEN_STRING = $05; // '"'
TOKEN_NUMBER = $06; // '0'-'9', '-', '.'
TOKEN_IDENTIFIER = $07; // '_', '$', 'a'..'z', 'A'..'Z'
TOKEN_COMMA = $08; // ','
TOKEN_EOF = $0F;
TOKEN_MASK = $0F;
type
TCharBuffer = record
private const
SIZE = 256;
private type
TBuffer = array [0..SIZE - 1] of JsonChar;
PBuffer = ^TBuffer;
private
FStatic: TBuffer;
FDynamic: PBuffer;
FCurrent: PJsonChar;
FCurrentEnd: PJsonChar;
FDynamicCount: Integer;
public
procedure Initialize; inline;
procedure Release; inline;
procedure Append(const AChar: JsonChar); inline;
function ToString: JsonString; inline;
end;
procedure TCharBuffer.Append(const AChar: JsonChar);
begin
if (FCurrent < FCurrentEnd) then
begin
FCurrent^ := AChar;
Inc(FCurrent);
Exit;
end;
ReallocMem(FDynamic, (FDynamicCount + 1) * SizeOf(TBuffer));
FCurrent := PJsonChar(FDynamic) + (FDynamicCount * SIZE);
FCurrentEnd := FCurrent + SIZE;
Inc(FDynamicCount);
FCurrent^ := AChar;
Inc(FCurrent);
end;
function TCharBuffer.ToString: JsonString;
var
I, StrIndex, TrailingLength: Integer;
Src: PBuffer;
Start: PJsonChar;
begin
if (FDynamic = nil) then
begin
Start := @FStatic;
SetString(Result, Start, FCurrent - Start);
Exit;
end;
TrailingLength := SIZE - (FCurrentEnd - FCurrent);
SetLength(Result, (FDynamicCount * SIZE) + TrailingLength);
Move(FStatic, Result[Low(JsonString)], SizeOf(TBuffer));
StrIndex := Low(JsonString) + SIZE;
Src := FDynamic;
for I := 0 to FDynamicCount - 2 do
begin
Move(Src^, Result[StrIndex], SizeOf(TBuffer));
Inc(Src);
Inc(StrIndex, SIZE);
end;
Move(Src^, Result[StrIndex], TrailingLength * SizeOf(JsonChar));
end;
procedure TCharBuffer.Initialize;
begin
FDynamic := nil;
FCurrent := @FStatic;
FCurrentEnd := FCurrent + SIZE;
FDynamicCount := 0;
end;
procedure TCharBuffer.Release;
begin
FreeMem(FDynamic);
end;
{ EJsonParserError }
constructor EJsonParserError.Create(const AMsg: String; const ALineNumber,
AColumnNumber, APosition: Integer);
begin
inherited CreateFmt('(%d:%d) %s', [ALineNumber, AColumnNumber, AMsg]);
FLineNumber := ALineNumber;
FColumnNumber := AColumnNumber;
FPosition := APosition;
end;
{ TJsonReader }
constructor TJsonReader.Create(const AJson: JsonString);
begin
inherited Create;
{$IFDEF JSON_STRING_INTERNING}
FStringInternPool := TJsonStringInternPool.Create;
{$ENDIF}
FJson := AJson;
FBuffer := PJsonChar(AJson);
FCurrent := FBuffer;
FLineStart := FBuffer;
FLineNumber := 1;
FContextIndex := -1;
PushContext(TState.TopLevel);
end;
destructor TJsonReader.Destroy;
begin
{$IFDEF JSON_STRING_INTERNING}
FStringInternPool.Free;
{$ENDIF}
inherited;
end;
class function TJsonReader.IsDelimiter(const AChar: JsonChar): Boolean;
begin
Result := (AChar < #$80) and ((_CHAR_BITS[AChar] and _FLAG_DELIMITER) <> 0);
end;
class function TJsonReader.Load(const AFilename: String): IJsonReader;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite);
try
Result := Load(Stream);
finally
Stream.Free;
end;
end;
class function TJsonReader.Load(const AStream: TStream): IJsonReader;
{$IFDEF JSON_UTF8}
var
Json: JsonString;
begin
if (AStream = nil) then
Exit(nil);
SetLength(Json, AStream.Size);
if (Json <> '') then
AStream.ReadBuffer(Json[Low(JsonString)], Length(Json));
{$ELSE}
var
Bytes: TBytes;
Json: JsonString;
begin
if (AStream = nil) then
Exit(nil);
SetLength(Bytes, AStream.Size);
if (Bytes <> nil) then
begin
AStream.ReadBuffer(Bytes, Length(Bytes));
Json := Utf8ToUtf16(@Bytes[0], Length(Bytes));
end;
{$ENDIF}
Result := TJsonReader.Create(Json);
end;
function TJsonReader.Next(out AState: TJsonReaderState): Boolean;
var
C: JsonChar;
HasComma, NeedComma: Boolean;
begin
Result := True;
HasComma := False;
Assert(Assigned(FContext));
NeedComma := (FContext.State <> TState.TopLevel) and (FContext.HasElements);
if (FContext.State = TState.DictionaryValue) then
begin
SkipWhitespace;
if (FCurrent^ <> ':' ) then
raise ParseError(@RS_JSON_COLON_EXPECTED);
NeedComma := False;
Inc(FCurrent);
end;
SkipWhitespace;
C := FCurrent^;
while True do
begin
case (_CHAR_BITS[C] and TOKEN_MASK) of
TOKEN_EOF:
begin
if (FContextIndex > 0) then
raise ParseError(@RS_JSON_UNEXPECTED_EOF);
FState := TJsonReaderState.EndOfStream;
Result := False;
Break;
end;
TOKEN_START_DICT:
begin
if (NeedComma) then
raise ParseError(@RS_JSON_COMMA_EXPECTED);
if (FContext.State = TState.DictionaryName) then
raise ParseError(@RS_JSON_NAME_EXPECTED);
FState := TJsonReaderState.StartDictionary;
Inc(FCurrent);
Break;
end;
TOKEN_END_DICT:
begin
if (FContext.State <> TState.DictionaryName) then
raise ParseError(@RS_JSON_UNEXPECTED_CHARACTER);
FState := TJsonReaderState.EndDictionary;
Inc(FCurrent);
Break;
end;
TOKEN_START_ARRAY:
begin
if (NeedComma) then
raise ParseError(@RS_JSON_COMMA_EXPECTED);
if (FContext.State = TState.DictionaryName) then
raise ParseError(@RS_JSON_NAME_EXPECTED);
FState := TJsonReaderState.StartArray;
Inc(FCurrent);
Break;
end;
TOKEN_END_ARRAY:
begin
if (FContext.State <> TState.&Array) then
raise ParseError(@RS_JSON_UNEXPECTED_CHARACTER);
FState := TJsonReaderState.EndArray;
Inc(FCurrent);
Break;
end;
TOKEN_STRING:
begin
if (NeedComma) then
raise ParseError(@RS_JSON_COMMA_EXPECTED);
if (FContext.State = TState.DictionaryName) then
FState := TJsonReaderState.Name
else
FState := TJsonReaderState.String;
ParseString;
Break;
end;
TOKEN_NUMBER:
begin
if (NeedComma) then
raise ParseError(@RS_JSON_COMMA_EXPECTED);
if (FContext.State = TState.DictionaryName) then
raise ParseError(@RS_JSON_NAME_EXPECTED);
FState := ParseNumber;
Break;
end;
TOKEN_IDENTIFIER:
begin
if (NeedComma) then
raise ParseError(@RS_JSON_COMMA_EXPECTED);
FState := TJsonReaderState.Name;
case C of
'I': if (FCurrent[1] = 'n') and (FCurrent[2] = 'f')
and (FCurrent[3] = 'i') and (FCurrent[4] = 'n')
and (FCurrent[5] = 'i') and (FCurrent[6] = 't')
and (FCurrent[7] = 'y') and IsDelimiter(FCurrent[8]) then
begin
FState := TJsonReaderState.Float;
FFloatValue := Infinity;
Inc(FCurrent, 8);
end;
'N': if (FCurrent[1] = 'a') and (FCurrent[2] = 'N')
and IsDelimiter(FCurrent[3]) then
begin
FState := TJsonReaderState.Float;
FFloatValue := NaN;
Inc(FCurrent, 3);
end;
'f': if (FCurrent[1] = 'a') and (FCurrent[2] = 'l')
and (FCurrent[3] = 's') and (FCurrent[4] = 'e')
and IsDelimiter(FCurrent[5]) then
begin
FState := TJsonReaderState.Boolean;
FBoolValue := False;
Inc(FCurrent, 5);
end;
'n': if (FCurrent[1] = 'u') and (FCurrent[2] = 'l')
and (FCurrent[3] = 'l') and IsDelimiter(FCurrent[4]) then
begin
FState := TJsonReaderState.Null;
Inc(FCurrent, 4);
end;
't': if (FCurrent[1] = 'r') and (FCurrent[2] = 'u')
and (FCurrent[3] = 'e') and IsDelimiter(FCurrent[4]) then
begin
FState := TJsonReaderState.Boolean;
FBoolValue := True;
Inc(FCurrent, 4);
end;
end;
if (FState = TJsonReaderState.Name) then
begin
if (FContext.State <> TState.DictionaryName) then
raise ParseError(@RS_JSON_ILLEGAL_UNQUOTED_STRING);
ParseUnquotedString;
end;
Break;
end;
TOKEN_COMMA:
begin
if (HasComma) then
raise ParseError(@RS_JSON_DUPLICATE_COMMA);
if (not NeedComma) then
raise ParseError(@RS_JSON_UNEXPECTED_COMMA);
Inc(FCurrent);
HasComma := True;
NeedComma := False;
SkipWhitespace;
C := FCurrent^;
end
else
raise ParseError(@RS_JSON_UNEXPECTED_CHARACTER);
end;
end;
AState := FState;
end;
function TJsonReader.ParseError(const AMsg: PResStringRec): EJsonParserError;
begin
Result := ParseError(LoadResString(AMsg));
end;
function TJsonReader.ParseError(const AMsg: String): EJsonParserError;
var
ColumnNumber, Position: Integer;
TextStart: PJsonChar;
begin
if (FCurrent = nil) then
begin
ColumnNumber := 1;
Position := 0;
end
else
begin
TextStart := FBuffer;
ColumnNumber := FCurrent - FLineStart + 1;
Position := FCurrent - TextStart;
end;
Result := EJsonParserError.Create(AMsg, FLineNumber, ColumnNumber, Position);
end;
procedure TJsonReader.ParseEscapedString(const AStart, ACur: PJsonChar);
var
Buf: TCharBuffer;
Cur: PJsonChar;
I: Integer;
C: JsonChar;
S: JsonString;
{$IFDEF JSON_UTF8}
Codepoint: UInt32;
{$ENDIF}
begin
{$IFDEF JSON_UTF8}
Codepoint := 0;
{$ENDIF}
Cur := ACur;
Buf.Initialize;
try
while True do
begin
C := Cur^;
Inc(Cur);
case C of
#0:
begin
FCurrent := Cur;
raise ParseError(@RS_JSON_INVALID_STRING);
end;
'\':
begin
C := Cur^;
Inc(Cur);
case C of
'"', '\', '/': Buf.Append(C);
'b': Buf.Append(#8);
't': Buf.Append(#9);
'n': Buf.Append(#10);
'f': Buf.Append(#12);
'r': Buf.Append(#13);
'u': begin
FCurrent := Cur;
SetLength(S, 5);
S[Low(JsonString) + 0] := '$';
if (Cur^ = #0) then
raise ParseError(@RS_JSON_INVALID_STRING);
S[Low(JsonString) + 1] := Cur^;
Inc(Cur);
if (Cur^ = #0) then
raise ParseError(@RS_JSON_INVALID_STRING);
S[Low(JsonString) + 2] := Cur^;
Inc(Cur);
if (Cur^ = #0) then
raise ParseError(@RS_JSON_INVALID_STRING);
S[Low(JsonString) + 3] := Cur^;
Inc(Cur);
if (Cur^ = #0) then
raise ParseError(@RS_JSON_INVALID_STRING);
S[Low(JsonString) + 4] := Cur^;
Inc(Cur);
I := StrToIntDef(S, -1);
if (I < 0) then
raise ParseError(@RS_JSON_INVALID_CODEPOINT);
{$IFDEF JSON_UTF8}
if (I < $80) then
Buf.Append(JsonChar(I))
else if (I < $800) then
begin
Buf.Append(JsonChar($C0 or (I shr 6)));
Buf.Append(JsonChar($80 or (I and $3F)));
end
else if (I >= $D800) and (I <= $DBFF) then
{ High Surrogate. Should be followed by Low Surrogate. }
Codepoint := I shl 10
else if (I >= $DC00) and (I <= $DFFF) then
begin
{ Low Surrogate. High Surrogate should have been parsed
already. }
Inc(Codepoint, I - $35FDC00);
Buf.Append(JsonChar($F0 or (Codepoint shr 18)));
Buf.Append(JsonChar($80 or ((Codepoint shr 12) and $3F)));
Buf.Append(JsonChar($80 or ((Codepoint shr 6) and $3F)));
Buf.Append(JsonChar($80 or (Codepoint and $3F)));
end
else
begin
Buf.Append(JsonChar($E0 or (I shr 12)));
Buf.Append(JsonChar($80 or ((I shr 6) and $3F)));
Buf.Append(JsonChar($80 or (I and $3F)));
end;
{$ELSE}
Buf.Append(JsonChar(I));
{$ENDIF}
end;
else
FCurrent := Cur - 1;
raise ParseError(@RS_JSON_INVALID_STRING);
end;
end;
'"':
begin
SetString(FStringValue, AStart, ACur - AStart);
FStringValue := FStringValue + Buf.ToString;
FCurrent := Cur;
Exit;
end;
else
Buf.Append(C);
end;
end;
finally
Buf.Release;
end;
end;
function TJsonReader.ParseNumber: TJsonReaderState;
{ Lexical grammar:
NumberLiteral: ['-'] DecimalLiteral
DecimalLiteral: 'Infinity'
| ['.'] DecimalDigits [ExponentPart]
| DecimalDigits '.' [DecimalDigits] [ExponentPart]
DecimalDigits: ('0'..'9')+
ExponentPart: ('e' | 'E') ['+' | '-'] DecimalDigits
There are 3 special values: Infinity, -Infinity and NaN.
The values Infinity and NaN are handled elsewhere (in Next), so here we only
need to handle -Infinity.
Note that, in contrast with the original specification, we allow numbers that
start with a '.' and the 3 special values. }
var
Power, Exponent: Integer;
IntegerPart: Int64;
Value: Double;
Cur: PJsonChar;
C: JsonChar;
IsNegative, IsNegativeExponent: Boolean;
begin
Cur := FCurrent;
{ NumberLiteral: ['-'] DecimalLiteral }
IntegerPart := 0;
IsNegative := False;