Debian Codegraph @

src/compatibility/delphi-only/fcl-json/jsonreader.pas

raw
1 {
2 This file is part of the Free Component Library
3
4 JSON SAX-like Reader
5 Copyright (c) 2007 by Michael Van Canneyt [email protected]
6
7 See the file COPYING.FPC, included in this distribution,
8 for details about the copyright.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 **********************************************************************}
15 unit jsonreader;
16
17 {$I fcl-json.inc}
18
19 interface
20
21 uses
22 Classes, SysUtils, fpJSON, jsonscanner, CastleUtils;
23
24 Type
25
26 { TBaseJSONReader }
27
28 TBaseJSONReader = Class(TObject)
29 Private
30 FScanner : TJSONScanner;
31 function GetO(AIndex: TJSONOption): Boolean;
32 function GetOptions: TJSONOptions; inline;
33 procedure SetO(AIndex: TJSONOption; AValue: Boolean);
34 procedure SetOptions(AValue: TJSONOptions);
35 Protected
36 procedure DoError(const Msg: String);
37 Procedure DoParse(AtCurrent,AllowEOF: Boolean);
38 function GetNextToken: TJSONToken;
39 function CurrentTokenString: RawByteString;
40 function CurrentToken: TJSONToken; inline;
41
42 Procedure KeyValue(Const AKey : TJSONStringType); virtual; abstract;
43 Procedure StringValue(Const AValue : TJSONStringType);virtual; abstract;
44 Procedure NullValue; virtual; abstract;
45 Procedure FloatValue(Const AValue : Double); virtual; abstract;
46 Procedure BooleanValue(Const AValue : Boolean); virtual; abstract;
47 Procedure NumberValue(Const AValue : TJSONStringType); virtual; abstract;
48 Procedure IntegerValue(Const AValue : integer); virtual; abstract;
49 Procedure Int64Value(Const AValue : int64); virtual; abstract;
50 Procedure QWordValue(Const AValue : QWord); virtual; abstract;
51 Procedure StartArray; virtual; abstract;
52 Procedure StartObject; virtual; abstract;
53 Procedure EndArray; virtual; abstract;
54 Procedure EndObject; virtual; abstract;
55
56 Procedure ParseArray;
57 Procedure ParseObject;
58 Procedure ParseNumber;
59 Procedure DoExecute;
60 Property Scanner : TJSONScanner read FScanner;
61 Public
62 Constructor Create(Source : TStream; AUseUTF8 : Boolean = True); overload;deprecated 'use options form instead';
63 Constructor Create(Const Source : RawByteString; AUseUTF8 : Boolean = True); overload;deprecated 'use options form instead';
64 constructor Create(Source: TStream; AOptions: TJSONOptions); overload;
65 constructor Create(const Source: RawByteString; AOptions: TJSONOptions); overload;
66 destructor Destroy();override;
67 // Parsing options
68 Property Options : TJSONOptions Read GetOptions Write SetOptions;
69 end;
70
71 TOnJSONBoolean = Procedure (Sender : TObject; Const AValue : Boolean) of object;
72 TOnJSONFloat = Procedure (Sender : TObject; Const AValue : TJSONFloat) of object;
73 TOnJSONInt64 = Procedure (Sender : TObject; Const AValue : Int64) of object;
74 TOnJSONQWord = Procedure (Sender : TObject; Const AValue : QWord) of object;
75 TOnJSONInteger = Procedure (Sender : TObject; Const AValue : Integer) of object;
76 TOnJSONString = Procedure (Sender : TObject; Const AValue : TJSONStringType) of Object;
77 TOnJSONKey = Procedure (Sender : TObject; Const AKey : TJSONStringType) of Object;
78
79
80 { TJSONEventReader }
81
82 TJSONEventReader = Class(TBaseJSONReader)
83 Private
84 FOnBooleanValue: TOnJSONBoolean;
85 FOnEndArray: TNotifyEvent;
86 FOnEndObject: TNotifyEvent;
87 FOnFloatValue: TOnJSONFloat;
88 FOnInt64Value: TOnJSONInt64;
89 FOnIntegerValue: TOnJSONInteger;
90 FOnKeyName: TOnJSONKey;
91 FOnNullValue: TNotifyEvent;
92 FOnNumberValue: TOnJSONString;
93 FOnQWordValue: TOnJSONQWord;
94 FOnStartArray: TNotifyEvent;
95 FOnStartObject: TNotifyEvent;
96 FOnStringValue: TOnJSONString;
97 Protected
98 Procedure KeyValue(Const AKey : TJSONStringType); override;
99 Procedure StringValue(Const AValue : TJSONStringType);override;
100 Procedure NullValue; override;
101 Procedure FloatValue(Const AValue : Double); override;
102 Procedure BooleanValue(Const AValue : Boolean); override;
103 Procedure NumberValue(Const AValue : TJSONStringType); override;
104 Procedure IntegerValue(Const AValue : integer); override;
105 Procedure Int64Value(Const AValue : int64); override;
106 Procedure QWordValue(Const AValue : QWord); override;
107 Procedure StartArray; override;
108 Procedure StartObject; override;
109 Procedure EndArray; override;
110 Procedure EndObject; override;
111 Public
112 Procedure Execute;
113 Property OnNullValue : TNotifyEvent Read FOnNullValue Write FOnNullValue;
114 Property OnBooleanValue : TOnJSONBoolean Read FOnBooleanValue Write FOnBooleanValue;
115 Property OnNumberValue : TOnJSONString Read FOnNumberValue Write FOnNumberValue;
116 Property OnFloatValue : TOnJSONFloat Read FOnFloatValue Write FOnFloatValue;
117 Property OnIntegerValue : TOnJSONInteger Read FOnIntegerValue Write FOnIntegerValue;
118 Property OnInt64Value : TOnJSONInt64 Read FOnInt64Value Write FOnInt64Value;
119 Property OnQWordValue : TOnJSONQWord Read FOnQWordValue Write FOnQWordValue;
120 Property OnStringValue : TOnJSONString Read FOnStringValue Write FOnStringValue;
121 Property OnKeyName : TOnJSONKey Read FOnKeyName Write FOnKeyName;
122 Property OnStartObject : TNotifyEvent Read FOnStartObject Write FOnStartObject;
123 Property OnEndObject : TNotifyEvent Read FOnEndObject Write FOnEndObject;
124 Property OnStartArray : TNotifyEvent Read FOnStartArray Write FOnStartArray;
125 Property OnEndArray : TNotifyEvent Read FOnEndArray Write FOnEndArray;
126 end;
127
128 IJSONConsumer = Interface ['{60F9D640-2A69-4AAB-8EE1-0DB6DC614D27}']
129 Procedure NullValue;
130 Procedure BooleanValue (const AValue : Boolean);
131 Procedure NumberValue (const AValue : TJSONStringType);
132 Procedure FloatValue (const AValue : TJSONFloat);
133 Procedure Int64Value (const AValue : Int64);
134 Procedure QWordValue (const AValue : QWord);
135 Procedure IntegerValue(const AValue : Integer) ;
136 Procedure StringValue(const AValue : TJSONStringType) ;
137 Procedure KeyName(const AKey : TJSONStringType);
138 Procedure StartObject;
139 Procedure EndObject;
140 Procedure StartArray;
141 Procedure EndArray;
142 end;
143
144 { TJSONConsumerReader }
145
146 TJSONConsumerReader = Class(TBaseJSONReader)
147 Private
148 FConsumer: IJSONConsumer;
149 Protected
150 Procedure KeyValue(Const AKey : TJSONStringType); override;
151 Procedure StringValue(Const AValue : TJSONStringType);override;
152 Procedure NullValue; override;
153 Procedure FloatValue(Const AValue : Double); override;
154 Procedure BooleanValue(Const AValue : Boolean); override;
155 Procedure NumberValue(Const AValue : TJSONStringType); override;
156 Procedure IntegerValue(Const AValue : integer); override;
157 Procedure Int64Value(Const AValue : int64); override;
158 Procedure QWordValue(Const AValue : QWord); override;
159 Procedure StartArray; override;
160 Procedure StartObject; override;
161 Procedure EndArray; override;
162 Procedure EndObject; override;
163 Public
164 Procedure Execute;
165 Property Consumer : IJSONConsumer Read FConsumer Write FConsumer;
166 end;
167
168 EJSONParser = Class(EParserError);
169
170 implementation
171
172 Resourcestring
173 SErrUnexpectedEOF = 'Unexpected EOF encountered.';
174 SErrUnexpectedToken = 'Unexpected token (%s) encountered.';
175 SErrExpectedColon = 'Expected colon (:), got token "%s".';
176 //SErrEmptyElement = 'Empty element encountered.';
177 SErrExpectedElementName = 'Expected element name, got token "%s"';
178 SExpectedCommaorBraceClose = 'Expected comma (,) or square bracket (]), got token "%s".';
179 SErrInvalidNumber = 'Number is not an integer or real number: %s';
180 SErrNoScanner = 'No scanner. No source specified ?';
181 SErrorAt = 'Error at line %d, Pos %d: ';
182 SErrGarbageFound = 'Expected EOF, but got %s';
183
184 { TBaseJSONReader }
185
186
187 Procedure TBaseJSONReader.DoExecute;
188
189 begin
190 if (FScanner=Nil) then
191 DoError(SErrNoScanner);
192 DoParse(False,True);
193 if joStrict in Options then
194 begin
195 Repeat
196 GetNextToken;
197 Until CurrentToken<>tkWhiteSpace;
198 If CurrentToken<>tkEOF then
199 DoError(Format(SErrGarbageFound,[CurrentTokenString]));
200 end;
201 end;
202
203 {
204 Consume next token and convert to JSON data structure.
205 If AtCurrent is true, the current token is used. If false,
206 a token is gotten from the scanner.
207 If AllowEOF is false, encountering a tkEOF will result in an exception.
208 }
209
210 function TBaseJSONReader.CurrentToken: TJSONToken;
211
212 begin
213 Result:=FScanner.CurToken;
214 end;
215
216 function TBaseJSONReader.CurrentTokenString: RawByteString;
217
218 begin
219 If CurrentToken in [tkString,tkIdentifier,tkNumber,tkComment] then
220 Result:=FScanner.CurTokenString
221 else
222 Result:=TokenInfos[CurrentToken];
223 end;
224
225 procedure TBaseJSONReader.DoParse(AtCurrent, AllowEOF: Boolean);
226
227 var
228 T : TJSONToken;
229
230 begin
231 If not AtCurrent then
232 T:=GetNextToken
233 else
234 T:=FScanner.CurToken;
235 Case T of
236 tkEof : If Not AllowEof then
237 DoError(SErrUnexpectedEOF);
238 tkNull : NullValue;
239 tkTrue,
240 tkFalse : BooleanValue(t=tkTrue);
241 tkString : ///if (joUTF8 in Options) and (DefaultSystemCodePage<>CP_UTF8) then
242 /// StringValue(TJSONStringType(UTF8Decode(CurrentTokenString)))
243 ///else
244 StringValue(CurrentTokenString);
245 tkCurlyBraceOpen :
246 ParseObject;
247 tkCurlyBraceClose :
248 DoError(SErrUnexpectedToken);
249 tkSQuaredBraceOpen :
250 ParseArray;
251 tkSQuaredBraceClose :
252 DoError(SErrUnexpectedToken);
253 tkNumber :
254 ParseNumber;
255 tkComma :
256 DoError(SErrUnexpectedToken);
257 tkIdentifier :
258 DoError(SErrUnexpectedToken);
259 else
260 // Do nothing
261 end;
262 end;
263
264
265 // Creates the correct JSON number type, based on the current token.
266 procedure TBaseJSONReader.ParseNumber;
267
268 Var
269 I : Integer;
270 I64 : Int64;
271 QW : QWord;
272 F : TJSONFloat;
273 S : String;
274
275 begin
276 S:=CurrentTokenString;
277 NumberValue(S);
278 I:=0;
279 if TryStrToUInt64(S,QW) then
280 begin
281 if QW>qword(high(Int64)) then
282 QWordValue(QW)
283 else
284 if QW>MaxInt then
285 begin
286 I64 := QW;
287 Int64Value(I64);
288 end
289 else
290 begin
291 I:=QW;
292 IntegerValue(I);
293 end
294 end
295 else
296 begin
297 If TryStrToInt64(S,I64) then
298 if (I64>Maxint) or (I64<-MaxInt) then
299 Int64Value(I64)
300 Else
301 begin
302 I:=I64;
303 IntegerValue(I);
304 end
305 else
306 begin
307 I:=0;
308 Val(S,F,I);
309 If (I<>0) then
310 DoError(SErrInvalidNumber);
311 FloatValue(F);
312 end;
313 end;
314 end;
315
316 function TBaseJSONReader.GetO(AIndex: TJSONOption): Boolean;
317 begin
318 Result:=AIndex in Options;
319 end;
320
321 function TBaseJSONReader.GetOptions: TJSONOptions;
322 begin
323 Result:=FScanner.Options
324 end;
325
326 procedure TBaseJSONReader.SetO(AIndex: TJSONOption; AValue: Boolean);
327 begin
328 if aValue then
329 FScanner.Options:=FScanner.Options+[AINdex]
330 else
331 FScanner.Options:=FScanner.Options-[AINdex]
332 end;
333
334 procedure TBaseJSONReader.SetOptions(AValue: TJSONOptions);
335 begin
336 FScanner.Options:=AValue;
337 end;
338
339
340 // Current token is {, on exit current token is }
341 Procedure TBaseJSONReader.ParseObject;
342
343 Var
344 T : TJSONtoken;
345 LastComma : Boolean;
346 S : TJSONStringType;
347
348 begin
349 LastComma:=False;
350 StartObject;
351 T:=GetNextToken;
352 While T<>tkCurlyBraceClose do
353 begin
354 If (T<>tkString) and (T<>tkIdentifier) then
355 DoError(SErrExpectedElementName);
356 S:=CurrentTokenString;
357 KeyValue(S);
358 // Writeln(S);
359 T:=GetNextToken;
360 If (T<>tkColon) then
361 DoError(SErrExpectedColon);
362 DoParse(False,False);
363 T:=GetNextToken;
364 If Not (T in [tkComma,tkCurlyBraceClose]) then
365 DoError(SExpectedCommaorBraceClose);
366 If T=tkComma then
367 begin
368 T:=GetNextToken;
369 LastComma:=(t=tkCurlyBraceClose);
370 end;
371 end;
372 If LastComma and ((joStrict in Options) or not (joIgnoreTrailingComma in Options)) then // Test for ,} case
373 DoError(SErrUnExpectedToken);
374 EndObject;
375 end;
376
377 // Current token is [, on exit current token is ]
378 Procedure TBaseJSONReader.ParseArray;
379
380 Var
381 T : TJSONtoken;
382 LastComma : Boolean;
383 S : TJSONOPTions;
384
385 begin
386 StartArray;
387 LastComma:=False;
388 Repeat
389 T:=GetNextToken;
390 If (T<>tkSquaredBraceClose) then
391 begin
392 DoParse(True,False);
393 T:=GetNextToken;
394 If Not (T in [tkComma,tkSquaredBraceClose]) then
395 DoError(SExpectedCommaorBraceClose);
396 LastComma:=(t=TkComma);
397 end;
398 Until (T=tkSquaredBraceClose);
399 S:=Options;
400 If LastComma and ((joStrict in S) or not (joIgnoreTrailingComma in S)) then // Test for ,] case
401 DoError(SErrUnExpectedToken);
402 EndArray;
403 end;
404
405 // Get next token, discarding whitespace
406 function TBaseJSONReader.GetNextToken: TJSONToken;
407
408 begin
409 Repeat
410 Result:=FScanner.FetchToken;
411 Until (Not (Result in [tkComment,tkWhiteSpace]));
412 end;
413
414 procedure TBaseJSONReader.DoError(const Msg: String);
415
416 Var
417 S : String;
418
419 begin
420 S:=Format(Msg,[CurrentTokenString]);
421 S:=Format(SErrorAt,[FScanner.CurRow,FSCanner.CurColumn])+S;
422 Raise EJSONParser.Create(S);
423 end;
424
425 constructor TBaseJSONReader.Create(Source: TStream; AUseUTF8 : Boolean = True);
426 begin
427 Inherited Create;
428 FScanner:=TJSONScanner.Create(Source,[joUTF8]);
429 if AUseUTF8 then
430 Options:=Options + [joUTF8];
431 end;
432
433 constructor TBaseJSONReader.Create(const Source: RawByteString; AUseUTF8 : Boolean = True);
434 begin
435 Inherited Create;
436 FScanner:=TJSONScanner.Create(Source,[joUTF8]);
437 if AUseUTF8 then
438 Options:=Options + [joUTF8];
439 end;
440
441 constructor TBaseJSONReader.Create(Source: TStream; AOptions: TJSONOptions);
442 begin
443 FScanner:=TJSONScanner.Create(Source,AOptions);
444 end;
445
446 constructor TBaseJSONReader.Create(const Source: RawByteString; AOptions: TJSONOptions);
447 begin
448 FScanner:=TJSONScanner.Create(Source,AOptions);
449 end;
450
451 destructor TBaseJSONReader.Destroy();
452 begin
453 FreeAndNil(FScanner);
454 inherited Destroy();
455 end;
456
457 { TJSONReader }
458
459 procedure TJSONEventReader.KeyValue(const AKey: TJSONStringType);
460 begin
461 if Assigned(FOnKeyName) then
462 FOnKeyName(Self,AKey);
463 end;
464
465 procedure TJSONEventReader.StringValue(const AValue: TJSONStringType);
466 begin
467 if Assigned(FOnStringValue) then
468 FOnStringValue(Self,AValue);
469 end;
470
471 procedure TJSONEventReader.NullValue;
472 begin
473 if Assigned(FOnNullValue) then
474 FOnNullValue(Self);
475 end;
476
477 procedure TJSONEventReader.FloatValue(const AValue: Double);
478 begin
479 if Assigned(FOnFloatValue) then
480 FOnFloatValue(Self,AValue);
481 end;
482
483 procedure TJSONEventReader.BooleanValue(const AValue: Boolean);
484 begin
485 if Assigned(FOnBooleanValue) then
486 FOnBooleanValue(Self,AValue);
487 end;
488
489 procedure TJSONEventReader.NumberValue(const AValue: TJSONStringType);
490 begin
491 if Assigned(FOnNumberValue) then
492 FOnNumberValue(Self,AValue);
493 end;
494
495 procedure TJSONEventReader.IntegerValue(const AValue: integer);
496 begin
497 if Assigned(FOnIntegerValue) then
498 FOnIntegerValue(Self,AValue);
499
500 end;
501
502 procedure TJSONEventReader.Int64Value(const AValue: int64);
503 begin
504 if Assigned(FOnInt64Value) then
505 FOnInt64Value(Self,AValue);
506
507 end;
508
509 procedure TJSONEventReader.QWordValue(const AValue: QWord);
510 begin
511 if Assigned(FOnQWordValue) then
512 FOnQWordValue(Self,AValue);
513 end;
514
515 procedure TJSONEventReader.StartArray;
516 begin
517 If Assigned(FOnStartArray) then
518 FOnStartArray(Self);
519 end;
520
521 procedure TJSONEventReader.StartObject;
522 begin
523 if Assigned(FOnStartObject) then
524 FOnStartObject(Self);
525 end;
526
527 procedure TJSONEventReader.EndArray;
528 begin
529 If Assigned(FOnEndArray) then
530 FOnEndArray(Self);
531 end;
532
533 procedure TJSONEventReader.EndObject;
534 begin
535 If Assigned(FOnEndObject) then
536 FOnEndObject(Self);
537 end;
538
539 procedure TJSONEventReader.Execute;
540 begin
541 DoExecute;
542 end;
543
544 { TJSONConsumerReader }
545
546 procedure TJSONConsumerReader.KeyValue(const AKey: TJSONStringType);
547 begin
548 If Assigned(FConsumer) then
549 FConsumer.KeyName(Akey)
550 end;
551
552 procedure TJSONConsumerReader.StringValue(const AValue: TJSONStringType);
553 begin
554 If Assigned(FConsumer) then
555 FConsumer.StringValue(AValue);
556 end;
557
558 procedure TJSONConsumerReader.NullValue;
559 begin
560 If Assigned(FConsumer) then
561 FConsumer.NullValue;
562 end;
563
564 procedure TJSONConsumerReader.FloatValue(const AValue: Double);
565 begin
566 If Assigned(FConsumer) then
567 FConsumer.FloatValue(AValue);
568 end;
569
570 procedure TJSONConsumerReader.BooleanValue(const AValue: Boolean);
571 begin
572 If Assigned(FConsumer) then
573 FConsumer.BooleanValue(AValue);
574 end;
575
576 procedure TJSONConsumerReader.NumberValue(const AValue: TJSONStringType);
577 begin
578 If Assigned(FConsumer) then
579 FConsumer.NumberValue(AValue);
580 end;
581
582 procedure TJSONConsumerReader.IntegerValue(const AValue: integer);
583 begin
584 If Assigned(FConsumer) then
585 FConsumer.IntegerValue(AValue);
586 end;
587
588 procedure TJSONConsumerReader.Int64Value(const AValue: int64);
589 begin
590 If Assigned(FConsumer) then
591 FConsumer.Int64Value(AValue);
592 end;
593
594 procedure TJSONConsumerReader.QWordValue(const AValue: QWord);
595 begin
596 If Assigned(FConsumer) then
597 FConsumer.QWordValue(AValue);
598 end;
599
600 procedure TJSONConsumerReader.StartArray;
601 begin
602 if Assigned(FConsumer) then
603 FConsumer.StartArray;
604 end;
605
606 procedure TJSONConsumerReader.StartObject;
607 begin
608 if Assigned(FConsumer) then
609 FConsumer.StartObject;
610 end;
611
612 procedure TJSONConsumerReader.EndArray;
613 begin
614 if Assigned(FConsumer) then
615 FConsumer.EndArray;
616 end;
617
618 procedure TJSONConsumerReader.EndObject;
619 begin
620 if Assigned(FConsumer) then
621 FConsumer.EndObject;
622 end;
623
624 procedure TJSONConsumerReader.Execute;
625 begin
626 DoExecute;
627 end;
628
629
630 end.
631