Debian Codegraph @

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

raw
1 {
2 This file is part of the Free Component Library
3
4 JSON source lexical scanner
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
16 {$I castleconf.inc} // hide useless Delphi hints/warnings
17
18 /// {$mode objfpc}
19 {$h+}
20 { $INLINE ON}
21
22 unit jsonscanner;
23
24 interface
25
26 uses SysUtils, Classes;
27
28 resourcestring
29 SErrInvalidCharacter = 'Invalid character at line %d, pos %d: ''%s''';
30 SUnterminatedComment = 'Unterminated comment at line %d, pos %d: ''%s''';
31 SErrOpenString = 'string exceeds end of line %d';
32
33 type
34
35 TJSONToken = (
36 tkEOF,
37 tkWhitespace,
38 tkString,
39 tkNumber,
40 tkTrue,
41 tkFalse,
42 tkNull,
43 // Simple (one-character) tokens
44 tkComma, // ','
45 tkColon, // ':'
46 tkCurlyBraceOpen, // '{'
47 tkCurlyBraceClose, // '}'
48 tkSquaredBraceOpen, // '['
49 tkSquaredBraceClose, // ']'
50 tkIdentifier, // Any Javascript identifier
51 tkComment,
52 tkUnknown
53 );
54
55 EScannerError = class(EParserError);
56
57 TJSONOption = (joUTF8, joStrict, joComments, joIgnoreTrailingComma, joIgnoreDuplicates, joBOMCheck);
58 TJSONOptions = set of TJSONOption;
59
60 Const
61 DefaultOptions = [joUTF8];
62
63 Type
64
65 { TJSONScanner }
66
67 TJSONScanner = class
68 private
69 FSource: RawByteString;
70 FCurPos : PAnsiChar; // Position inside total string
71 FCurRow: Integer;
72 FCurToken: TJSONToken;
73 FCurTokenString: RawByteString; // TODO string
74 FCurLine: PAnsiChar;
75 FTokenStr: PAnsiChar; // position inside FCurLine
76 FEOL : PAnsiChar; // EOL
77 FOptions : TJSONOptions;
78 function GetCurColumn: Integer; inline;
79 function GetCurLine: string;
80 function GetO(AIndex: TJSONOption): Boolean;
81 procedure SetO(AIndex: TJSONOption; AValue: Boolean);
82 protected
83 procedure Error(const Msg: string);overload;
84 procedure Error(const Msg: string; Const Args: array of const);overload;
85 // function DoFetchToken: TJSONToken; inline;
86 public
87 constructor Create(Source : TStream; AUseUTF8 : Boolean = True); overload; deprecated 'use options form instead';
88 constructor Create(Source: TStream; AOptions: TJSONOptions); overload;
89 constructor Create(const aSource : RawByteString; AUseUTF8 : Boolean = True); overload; deprecated 'use options form instead';
90 constructor Create(const aSource: RawByteString; AOptions: TJSONOptions); overload;
91
92 function FetchToken: TJSONToken;
93
94 property CurLine: string read GetCurLine;
95 property CurRow: Integer read FCurRow;
96 property CurColumn: Integer read GetCurColumn;
97
98 property CurToken: TJSONToken read FCurToken;
99 property CurTokenString: RawByteString read FCurTokenString;
100 // Use strict JSON: " for strings, object members are strings, not identifiers
101 Property Strict : Boolean Index joStrict Read GetO Write SetO ; ///deprecated 'use options instead';
102 // if set to TRUE, then strings will be converted to UTF8 ansistrings, not system codepage ansistrings.
103 Property UseUTF8 : Boolean index joUTF8 Read GetO Write SetO; /// deprecated 'Use options instead';
104 // Parsing options
105 Property Options : TJSONOptions Read FOptions Write FOptions;
106 end;
107
108 const
109 TokenInfos: array[TJSONToken] of string = (
110 'EOF',
111 'Whitespace',
112 'String',
113 'Number',
114 'True',
115 'False',
116 'Null',
117 ',',
118 ':',
119 '{',
120 '}',
121 '[',
122 ']',
123 'identifier',
124 'comment',
125 ''
126 );
127
128
129 implementation
130
131 constructor TJSONScanner.Create(Source : TStream; AUseUTF8 : Boolean = True);
132
133 Var
134 O : TJSONOptions;
135
136 begin
137 O:=DefaultOptions;
138 if AUseUTF8 then
139 Include(O,joUTF8)
140 else
141 Exclude(O,joUTF8);
142 Create(Source,O);
143 end;
144
145 constructor TJSONScanner.Create(Source: TStream; AOptions: TJSONOptions);
146
147 procedure SkipStreamBOM;
148 Var
149 OldPos : integer;
150 Header : array[0..3] of byte;
151 begin
152 OldPos := Source.Position;
153 FillChar(Header, SizeOf(Header), 0);
154 if Source.Read(Header, 3) = 3 then
155 if (Header[0]=$EF) and (Header[1]=$BB) and (Header[2]=$BF) then
156 exit;
157 Source.Position := OldPos;
158 end;
159
160
161 Var
162 S : RawByteString;
163
164 begin
165 if (joBOMCheck in aOptions) then
166 SkipStreamBom;
167 S:='';
168 SetLength(S,Source.Size-Source.Position);
169 if Length(S)>0 then
170 Source.ReadBuffer(S[1],Length(S));
171 Create(S,AOptions)
172 end;
173
174 constructor TJSONScanner.Create(const aSource : RawByteString; AUseUTF8 : Boolean = True);
175 Var
176 O : TJSONOptions;
177
178 begin
179 O:=DefaultOptions;
180 if AUseUTF8 then
181 Include(O,joUTF8)
182 else
183 Exclude(O,joUTF8);
184 Create(aSource,O);
185 end;
186
187 constructor TJSONScanner.Create(const aSource: RawByteString; AOptions: TJSONOptions);
188 begin
189 FSource:=aSource;
190 FCurPos:=PAnsiChar(FSource);
191 if FCurPos<>Nil then
192 FCurRow:=1;
193 FOptions:=AOptions;
194 end;
195
196 function TJSONScanner.GetCurColumn: Integer;
197 begin
198 Result := FTokenStr - FCurLine;
199 end;
200
201
202 procedure TJSONScanner.Error(const Msg: string);
203 begin
204 raise EScannerError.Create(Msg);
205 end;
206
207 procedure TJSONScanner.Error(const Msg: string; const Args: array of const);
208 begin
209 raise EScannerError.CreateFmt(Msg, Args);
210 end;
211
212 function TJSONScanner.FetchToken: TJSONToken;
213
214 (*
215 procedure dumpcurrent;
216
217 begin
218 Writeln('Start of line : ',FCurLine);
219 Writeln('Cur pos : ',FCurPos);
220 Writeln('Start of token : ',FTokenstr);
221 Writeln('End of line : ',FTokenstr);
222 end;
223 *)
224 function FetchLine: Boolean;
225
226
227 begin
228 Result:=(FCurPos<>Nil) and (FCurPos^<>#0);
229 if Result then
230 begin
231 FCurLine:=FCurPos;
232 FTokenStr:=FCurPos;
233 While Not (FCurPos^ in [#0,#10,#13]) do
234 Inc(FCurPos);
235 FEOL:=FCurPos;
236 If (FCurPos^<>#0) then
237 // While (FCurPos^<>#0) and (FCurPos^ in [#10,#13]) do
238 begin
239 if (FCurPos^=#13) and (FCurPos[1]=#10) then
240 Inc(FCurPos); // Skip CR-LF
241 Inc(FCurPos); // To start of next line
242 Inc(FCurRow); // Increase line index
243 end;
244 // Len:=FEOL-FTokenStr;
245 // FTokenStr:=FCurPos;
246 end
247 else
248 begin
249 FCurLine:=Nil;
250 FTokenStr:=nil;
251 end;
252 end;
253
254 var
255 TokenStart: PAnsiChar;
256 it : TJSONToken;
257 I : Integer;
258 OldLength, SectionLength, tstart,tcol, u1,u2: Integer;
259 C , c2: AnsiChar;
260 S : String[4];
261 Line : String;
262 IsStar,EOC: Boolean;
263
264 Procedure MaybeAppendUnicode;
265
266 Var
267 u : UTF8String;
268
269 begin
270 // if there is a leftover \u, append
271 if (u1<>0) then
272 begin
273 if (joUTF8 in Options) or (DefaultSystemCodePage=CP_UTF8) then
274 U:=Utf8Encode(WideString(WideChar(u1))) // ToDo: use faster function
275 else
276 U:=String(WideChar(u1)); // WideChar converts the encoding. Should it warn on loss?
277 FCurTokenString:=FCurTokenString+U;
278 OldLength:=Length(FCurTokenString);
279 u1:=0;
280 end;
281 end;
282
283
284 begin
285 if (FTokenStr = nil) or (FTokenStr=FEOL) then
286 begin
287 if not FetchLine then
288 begin
289 Result := tkEOF;
290 FCurToken := Result;
291 exit;
292 end;
293 end;
294 FCurTokenString := '';
295 case FTokenStr^ of
296 #0: // Empty line
297 begin
298 FetchLine;
299 Result := tkWhitespace;
300 end;
301 #9, ' ', #10, #13:
302 begin
303 Result := tkWhitespace;
304 repeat
305 if FTokenStr = FEOL then
306 begin
307 if not FetchLine then
308 begin
309 FCurToken := Result;
310 exit;
311 end
312 end
313 else
314 Inc(FTokenStr);
315 until not (FTokenStr[0] in [#9, ' ']);
316 end;
317 '"','''':
318 begin
319 C:=FTokenStr^;
320 If (C='''') and (joStrict in Options) then
321 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
322 Inc(FTokenStr);
323 TokenStart := FTokenStr;
324 OldLength := 0;
325 FCurTokenString := '';
326 u1:=0;
327 while not (FTokenStr^ in [#0,C]) do
328 begin
329 if (FTokenStr^='\') then
330 begin
331 // Save length
332 SectionLength := FTokenStr - TokenStart;
333 Inc(FTokenStr);
334 // Read escaped token
335 Case FTokenStr^ of
336 '"' : S:='"';
337 '''' : S:='''';
338 't' : S:=#9;
339 'b' : S:=#8;
340 'n' : S:=#10;
341 'r' : S:=#13;
342 'f' : S:=#12;
343 '\' : S:='\';
344 '/' : S:='/';
345 'u' : begin
346 u2:=0;
347 For I:=1 to 4 do
348 begin
349 Inc(FTokenStr);
350 c2:=FTokenStr^;
351 Case c2 of
352 '0'..'9': u2:=u2*16+ord(c2)-ord('0');
353 'A'..'F': u2:=u2*16+ord(c2)-ord('A')+10;
354 'a'..'f': u2:=u2*16+ord(c2)-ord('a')+10;
355 else
356 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
357 end;
358 end;
359 // ToDo: 4-bytes UTF16
360 if u1<>0 then
361 begin
362 if (joUTF8 in Options) or (DefaultSystemCodePage=CP_UTF8) then
363 S:=Utf8Encode(WideString(WideChar(u1)+WideChar(u2))) // ToDo: use faster function
364 else
365 S:=String(WideChar(u1)+WideChar(u2)); // WideChar converts the encoding. Should it warn on loss?
366 u1:=0;
367 end
368 else
369 begin
370 S:='';
371 u1:=u2;
372 end
373 end;
374 #0 : Error(SErrOpenString,[FCurRow]);
375 else
376 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
377 end;
378 I:=Length(S);
379 if (SectionLength+I>0) then
380 begin
381 // If length=1, we know it was not \uXX, but u1 can be nonzero, and we must first append it.
382 // example: \u00f8\"
383 if (I=1) and (u1<>0) then
384 MaybeAppendUnicode;
385 SetLength(FCurTokenString, OldLength + SectionLength+i);
386 if SectionLength > 0 then
387 Move(TokenStart^, FCurTokenString[OldLength + 1], SectionLength);
388 if I>0 then
389 Move(S[1],FCurTokenString[OldLength + SectionLength+1],i);
390 Inc(OldLength, SectionLength+I);
391 end;
392 // Next char
393 TokenStart := FTokenStr+1;
394 end
395 else if u1<>0 then
396 MaybeAppendUnicode;
397 if FTokenStr^ < #$20 then
398 if FTokenStr^ = #0 then Error(SErrOpenString,[FCurRow])
399 else if joStrict in Options then Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
400 Inc(FTokenStr);
401 end;
402 if FTokenStr^ = #0 then
403 Error(SErrOpenString,[FCurRow]);
404 if u1<>0 then
405 MaybeAppendUnicode;
406 SectionLength := FTokenStr - TokenStart;
407 SetLength(FCurTokenString, OldLength + SectionLength);
408 if SectionLength > 0 then
409 Move(TokenStart^, FCurTokenString[OldLength + 1], SectionLength);
410 Inc(FTokenStr);
411 Result := tkString;
412 end;
413 ',':
414 begin
415 Inc(FTokenStr);
416 Result := tkComma;
417 end;
418 '0'..'9','.','-':
419 begin
420 TokenStart := FTokenStr;
421 if FTokenStr^ = '-' then inc(FTokenStr);
422 case FTokenStr^ of
423 '1'..'9': Inc(FTokenStr);
424 '0': begin
425 Inc(FTokenStr);
426 if (joStrict in Options) and (FTokenStr^ in ['0'..'9']) then
427 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
428 end;
429 '.': if joStrict in Options then
430 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
431 else
432 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
433 end;
434 while true do
435 begin
436 case FTokenStr^ of
437 '0'..'9': inc(FTokenStr);
438 '.':
439 begin
440 case FTokenStr[1] of
441 '0'..'9': Inc(FTokenStr, 2);
442 'e', 'E': begin
443 if joStrict in Options then
444 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
445 Inc(FTokenStr);
446 end;
447 else Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
448 end;
449 while FTokenStr^ in ['0'..'9'] do
450 inc(FTokenStr);
451 break;
452 end;
453 else
454 break;
455 end;
456 end;
457 if FTokenStr^ in ['e', 'E'] then begin
458 Inc(FTokenStr);
459 if FTokenStr^ in ['-','+'] then
460 Inc(FTokenStr);
461 if not (FTokenStr^ in ['0'..'9']) then
462 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
463 repeat
464 Inc(FTokenStr);
465 until not (FTokenStr^ in ['0'..'9']);
466 end;
467 if {(FTokenStr<>FEOL) and }not (FTokenStr^ in [#13,#10,#0,'}',']',',',#9,' ']) then
468 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
469 SectionLength := FTokenStr - TokenStart;
470 FCurTokenString:='';
471 SetString(FCurTokenString, TokenStart, SectionLength);
472 If (FCurTokenString[1]='.') then
473 FCurTokenString:='0'+FCurTokenString;
474 Result := tkNumber;
475 end;
476 ':':
477 begin
478 Inc(FTokenStr);
479 Result := tkColon;
480 end;
481 '{':
482 begin
483 Inc(FTokenStr);
484 Result := tkCurlyBraceOpen;
485 end;
486 '}':
487 begin
488 Inc(FTokenStr);
489 Result := tkCurlyBraceClose;
490 end;
491 '[':
492 begin
493 Inc(FTokenStr);
494 Result := tkSquaredBraceOpen;
495 end;
496 ']':
497 begin
498 Inc(FTokenStr);
499 Result := tkSquaredBraceClose;
500 end;
501 '/' :
502 begin
503 if Not (joComments in Options) then
504 Error(SErrInvalidCharacter, [CurRow,CurCOlumn,FTokenStr[0]]);
505 TokenStart:=FTokenStr;
506 Inc(FTokenStr);
507 Case FTokenStr^ of
508 '/' : begin
509 FCurTokenString:='';
510 Inc(FTokenStr);
511 TokenStart:=FTokenStr;
512 SectionLength := PChar(FEOL)-TokenStart;
513 SetString(FCurTokenString, TokenStart, SectionLength);
514 FetchLine;
515 end;
516 '*' :
517 begin
518 IsStar:=False;
519 Inc(FTokenStr);
520 TokenStart:=FTokenStr;
521 Repeat
522 While (FTokenStr=FEOL) do
523 begin
524 SectionLength := (FTokenStr - TokenStart);
525 Line:='';
526 SetString(Line, TokenStart, SectionLength);
527 FCurtokenString:=FCurtokenString+Line+sLineBreak;
528 if not fetchLine then
529 Error(SUnterminatedComment, [CurRow,CurCOlumn,FTokenStr[0]]);
530 TokenStart:=FTokenStr;
531 end;
532 IsStar:=FTokenStr^='*';
533 Inc(FTokenStr);
534 EOC:=(isStar and (FTokenStr^='/'));
535 Until EOC;
536 if EOC then
537 begin
538 SectionLength := (FTokenStr - TokenStart-1);
539 Line:='';
540 SetString(Line, TokenStart, SectionLength);
541 FCurtokenString:=FCurtokenString+Line;
542 Inc(FTokenStr);
543 end;
544 end;
545 else
546 Error(SErrInvalidCharacter, [CurRow,CurCOlumn,FTokenStr[0]]);
547 end;
548 Result:=tkComment;
549 end;
550 'a'..'z','A'..'Z','_':
551 begin
552 tstart:=CurRow;
553 Tcol:=CurColumn;
554 TokenStart := FTokenStr;
555 Result:=tkIdentifier;
556 case TokenStart^ of
557 't': if (TokenStart[1] = 'r') and (TokenStart[2] = 'u') and (TokenStart[3] = 'e') then
558 Result:=tkTrue;
559 'f': if (TokenStart[1] = 'a') and (TokenStart[2] = 'l') and (TokenStart[3] = 's') and (TokenStart[4] = 'e') then
560 Result:=tkFalse;
561 'n': if (TokenStart[1] = 'u') and (TokenStart[2] = 'l') and (TokenStart[3] = 'l') then
562 Result:=tkNull;
563 end;
564 if result <> tkIdentifier then inc(FTokenStr, length(TokenInfos[result]) - 1);
565 repeat
566 Inc(FTokenStr);
567 until not (FTokenStr^ in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
568 SectionLength := FTokenStr - TokenStart;
569 FCurTokenString:='';
570 SetString(FCurTokenString, TokenStart, SectionLength);
571 if (result = tkIdentifier) or (SectionLength <> length(TokenInfos[result])) then begin
572 if (joStrict in Options) then
573 Error(SErrInvalidCharacter, [tStart,tcol,TokenStart[0]]);
574 for it := tkTrue to tkNull do
575 if CompareText(CurTokenString, TokenInfos[it]) = 0 then
576 begin
577 Result := it;
578 FCurToken := Result;
579 exit;
580 end;
581 end;
582 end;
583 else
584 begin
585 Result := tkEOF;
586 Error(SErrInvalidCharacter, [CurRow,CurColumn,FTokenStr[0]]);
587 end;
588 end;
589 FCurToken := Result;
590 end;
591
592 {function TJSONScanner.FetchToken: TJSONToken;
593
594 begin
595 Result:=DoFetchToken;
596 end;}
597
598 function TJSONScanner.GetCurLine: string;
599 begin
600 Result:='';
601 if FCurLine<>Nil then
602 begin
603 SetLength(Result,FEOL-FCurLine);
604 if Length(Result)>0 then
605 Move(FCurLine^,Result[1],Length(Result));
606 end;
607 end;
608
609 function TJSONScanner.GetO(AIndex: TJSONOption): Boolean;
610 begin
611 Result:=AIndex in FOptions;
612 end;
613
614 procedure TJSONScanner.SetO(AIndex: TJSONOption; AValue: Boolean);
615 begin
616 If AValue then
617 Include(Foptions,AIndex)
618 else
619 Exclude(Foptions,AIndex)
620 end;
621
622 end.