-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathJsonFox.prg
More file actions
2448 lines (2203 loc) · 65.8 KB
/
JsonFox.prg
File metadata and controls
2448 lines (2203 loc) · 65.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
* JSONFox Constants
*!* #Define T_NONE 'ÿ'
#Define T_NONE 0
#Define T_EOT chr(4)
#Define T_LBRACE 1
#Define T_RBRACE 2
#Define T_LBRACKET 3
#Define T_RBRACKET 4
#Define T_COMMA 5
#Define T_COLON 6
#Define T_TRUE 7
#Define T_FALSE 8
#Define T_NULL 9
#Define T_NUMBER 10
#Define T_KEY 11
#Define T_STRING 12
#Define T_LINE 13
#Define T_INTEGER 14
#Define T_FLOAT 15
#Define T_VALUE 16
#Define T_EOF 17
#Define T_BOOLEAN 18
#Define CR Chr(13)
#Define LF Chr(10)
#Define CRLF CR + LF
#Define T_TAB Chr(9)
#Define INTEGER_MAX_CAPACITY 2147483647
* ── src\jsonutils.prg ── *
&& ======================================================================== &&
&& Class utils
&& JSON Utilities
&& ======================================================================== &&
define class jsonutils as custom
EscapeOptionalChars = .t.
oRegEx = .null.
dimension aPattern[8, 2]
function init
this.oRegEx = createobject("VBScript.RegExp")
this.oRegEx.global = .t.
&& Match a date format in the following pattern
&& "YYYY-MM-DD"
this.aPattern[1,1] = "^\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01])$"
this.aPattern[1,2] = .f.
&& Match a date and time format in the following pattern
&& "YYYY-MM-DD HH:MM:SS"
this.aPattern[2,1] = "^\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|0?[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$"
this.aPattern[2,2] = .f.
&& Match ISO 8601 date and time formats that include a time zone offset
&& "YYYY-MM-DDTHH:MM:SSZ" OR "YYYY-MM-DDTHH:MM:SS+HH:MM" OR "YYYY-MM-DDTHH:MM:SS-HH:MM"
this.aPattern[3,1] = "^(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})(\:(\d{2}))?(Z|[+-](\d{2})\:(\d{2}))?$"
this.aPattern[3,2] = .f.
&& Match a date and time format in ISO 8601 combined with a single-character time zone identifier
&& "YYYY-MM-DDTHH:MM(:SS)?.SSS(W)"
this.aPattern[4,1] = "^(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})(\:(\d{2}))?[.](\d{3})(\w{1})$"
this.aPattern[4,2] = .f.
&& "DD/MM/YYYY" OR "DD-MM-YYYY"
this.aPattern[5,1] = "^([0-2][0-9]|(3)[0-1])[\/-](((0)[0-9])|((1)[0-2]))[\/-]\d{4}$"
this.aPattern[5,2] = .t.
&& "DD/MM/YYYY HH:MM:SS" or "DD-MM-YYYY HH:MM:SS"
this.aPattern[06,1] = "^([0-2][0-9]|(3)[0-1])[\/-](((0)[0-9])|((1)[0-2]))[\/-]\d{4} (00|0?[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$"
this.aPattern[06,2] = .t.
&& "DD/MM/YY" or "DD-MM-YY"
this.aPattern[07,1] = "^([0-2][0-9]|(3)[0-1])[\/-](((0)[0-9])|((1)[0-2]))[\/-]\d{2}$"
this.aPattern[07,2] = .t.
&& "DD/MM/YY HH:MM:SS" or "DD-MM-YY HH:MM:SS"
this.aPattern[08,1] = "^([0-2][0-9]|(3)[0-1])[\/-](((0)[0-9])|((1)[0-2]))[\/-]\d{2} (00|0?[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$"
this.aPattern[08,2] = .t.
endfunc
&& ======================================================================== &&
&& Function GetValue
&& ======================================================================== &&
function getValue as string
lparameters tcvalue as string, tctype as character, tlParseUTF8 as Boolean, tlTrimChars as Boolean
do case
case tctype $ "CDTBGMQVWX"
do case
case tctype == 'D'
tcvalue = '"' + strtran(dtoc(tcvalue), '.', '-') + '"'
case tctype == 'T'
tcvalue = '"' + strtran(ttoc(tcvalue), '.', '-') + '"'
case tctype == 'X'
tcvalue = "null"
otherwise
tcvalue = this.getString(iif(tlTrimChars, alltrim(tcvalue), tcvalue), tlParseUTF8)
endcase
case tctype $ "YFIN"
if this.HasDecimals(tcvalue)
tcvalue = strtran(alltrim(transform(tcvalue, "@T")), ',', '.')
else
tcvalue = strtran(alltrim(transform(tcvalue)), ',', '.')
endif
case tctype == 'L'
tcvalue = iif(tcvalue, "true", "false")
endcase
return tcvalue
endfunc
function HasDecimals(tnValue, tnTolerance)
if pcount() < 2
tnTolerance = 0.0000001
endif
return abs(tnValue - int(tnValue)) > tnTolerance
endfunc
&& ======================================================================== &&
&& Function CheckString
&& Check the string content in case it is a date or datetime.
&& String itself or string date / datetime format.
&& ======================================================================== &&
function CheckString(tcString)
if !isdigit(left(tcString, 1)) and !isdigit(right(tcString, 1))
return tcString
endif
* We try to identify a date format
local i
for i = 1 to alen(this.aPattern, 1)
this.oRegEx.pattern = this.aPattern[i, 1]
if this.oRegEx.Test(tcString)
return evl(this.formatDate(tcString, this.aPattern[i, 2]), tcString)
endif
endfor
* It is a normal String
return tcString
endfunc
&& ======================================================================== &&
&& Function FormatDate
&& return a valid date or datetime date type.
&& ======================================================================== &&
function formatDate as variant
lparameters tcDate as string, tlUseDMY as Boolean
local lDate
lDate = .null.
&& IRODG 20210313 ISSUE # 14
do case
case 'T' $ tcDate && JavaScript or ISO 8601 format.
do case
case '+' $ tcDate
tcDate = getwordnum(tcDate, 1, '+')
case at('-', tcDate, 3) > 0
tcDate = substr(tcDate, 1, at('-', tcDate, 3)-1)
otherwise
endcase
try
setDateAct = set('Date')
set date ymd
lDate = ctot('^'+tcDate)
catch
lDate = {//::}
finally
set date &setDateAct
endtry
case occurs(':', tcDate) >= 2 && VFP Date Time Format. 'YYYY-mm-dd HH:mm:ss' and also 'dd-mm-yyyy hh:mm:ss'
try
setDateAct = set('Date')
* set date ymd
&& (DCA) - 12/09/2023 - Also verify if the DateTime is DMY Format
if !tlUseDMY
set date ymd
else
set date dmy
endif
lDate = ctot(tcDate)
catch
lDate = {//::}
finally
set date &setDateAct
endtry
otherwise
try
setDateAct = set('Date')
if !tlUseDMY
set date ymd
else
set date dmy
endif
lDate = ctod(tcDate)
catch
lDate = {//}
finally
set date &setDateAct
endtry
endcase
return lDate
&& IRODG 20210313 ISSUE # 14
endfunc
&& ======================================================================== &&
&& Function GetString
&& ======================================================================== &&
&& ======================================================================== &&
&& Function GetString
&& ======================================================================== &&
function getString as string
lparameters tcString as string, tlParseUTF8 as Boolean
local llEscapeOptionalChars
* Obtener la configuraci�n de escape opcional desde la clase
llEscapeOptionalChars = this.EscapeOptionalChars
* Validar par�metro de entrada
tcString = iif(vartype(tcString) != "C", "", tcString)
* ESCAPES OBLIGATORIOS seg�n el est�ndar RFC 8259
tcString = strtran(tcString, '\', '\\' ) && Barra invertida
tcString = strtran(tcString, chr(8), '\b' ) && Backspace
tcString = strtran(tcString, chr(9), '\t' ) && Tabulaci�n
tcString = strtran(tcString, chr(10), '\n' ) && Nueva l�nea
tcString = strtran(tcString, chr(12), '\f' ) && Form feed
tcString = strtran(tcString, chr(13), '\r' ) && Retorno de carro
* Manejo de comillas
if left(alltrim(tcString), 1) == '"' and right(alltrim(tcString),1) == '"'
tcString = substr(tcString, 2, len(tcString)-2)
endif
tcString = strtran(tcString, '"', '\"' ) && Comillas dobles (obligatorio)
* Escapar TODOS los caracteres > 127 autom�ticamente
local i, nChar, lcChar, lcResult
lcResult = ""
for i=1 to len(tcString)
lcChar = substr(tcString,i,1)
nChar = asc(lcChar)
if nChar > 127
* convertir a escape Unicode \uXXXX
lcResult = lcResult + '\u' + right('0000' + transform(nChar, '@0'), 4)
else
lcResult = lcResult + lcChar
endif
next
tcString = lcResult
* ESCAPES OPCIONALES
if tlParseUTF8
* Caracteres especiales
tcString = strtran(tcString,"&","\u0026")
tcString = strtran(tcString,"+","\u002b")
tcString = strtran(tcString,"-","\u002d")
tcString = strtran(tcString,"#","\u0023")
tcString = strtran(tcString,"%","\u0025")
endif
* A�adir comillas si no las tiene
LOCAL lnLen, lcLastChar, lcPrevChar
lnLen = LEN(tcString)
lcLastChar = RIGHT(tcString, 1)
lcPrevChar = IIF(lnLen > 1, SUBSTR(tcString, lnLen-1, 1), "")
* Verificar si inicia con comilla y termina con comilla NO escapada
IF LEFT(tcString, 1) != '"' OR lcLastChar != '"' OR lcPrevChar = "\"
RETURN '"' + tcString + '"'
ENDIF
return tcString
endfunc
&& ======================================================================== &&
&& Function CheckProp
&& Check the object property name for invalid format (replace space with '_')
&& ======================================================================== &&
function checkprop(tcprop as string) as string
local lcfinalprop, i, lcchar
lcfinalprop = ''
for i = 1 to len(tcprop)
lcchar = substr(tcprop, i, 1)
if (i = 1 and isdigit(lcchar)) or (!isalpha(lcchar) and !isdigit(lcchar))
lcfinalprop = lcfinalprop + "_"
else
lcfinalprop = lcfinalprop + lcchar
endif
endfor
return alltrim(lcfinalprop)
endfunc
function tokenTypeToStr(tnType)
do case
case tnType = 0
return 'EOF'
case tnType = 1
return 'LBRACE'
case tnType = 2
return 'RBRACE'
case tnType = 3
return 'LBRACKET'
case tnType = 4
return 'RBRACKET'
case tnType = 5
return 'COMMA'
case tnType = 6
return 'COLON'
case tnType = 7
return 'TRUE'
case tnType = 8
return 'FALSE'
case tnType = 9
return 'NULL'
case tnType = 10
return 'NUMBER'
case tnType = 11
return 'KEY'
case tnType = 12
return 'STRING'
case tnType = 13
return 'LINE'
case tnType = 14
return 'INTEGER'
case tnType = 15
return 'FLOAT'
case tnType = 16
return 'VALUE'
case tnType = 17
return 'EOF'
case tnType = 18
return 'BOOLEAN'
endcase
endfunc
enddefine
* ── src\tokenizer.prg ── *
* Tokenizer
define class Tokenizer as custom
hidden source
hidden start
hidden current
hidden letters
hidden hexLetters
hidden line
hidden capacity
hidden length
dimension tokens[1]
sourceLen = 0
oUtils = .null.
function init(tcSource)
with this
.length = 1
.capacity = 0
&& IRODG 11/08/2023 Inicio
* We remove possible invalid characters from the input source.
tcSource = strtran(tcSource, chr(0))
tcSource = strtran(tcSource, chr(10))
tcSource = strtran(tcSource, chr(13))
&& IRODG 11/08/2023 Fin
.source = tcSource
.start = 0
.current = 1
.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
.hexLetters = 'abcdefABCDEF'
.line = 1
.sourceLen = len(tcSource)
endwith
endfunc
hidden function advance
with this
.current = .current + 1
return substr(.source, .current-1, 1)
endwith
endfunc
hidden function peek
with this
if .isAtEnd()
return '�'
endif
return substr(.source, .current, 1)
endwith
endfunc
hidden function peekNext
with this
if (.current + 1) > .sourceLen
return '�'
endif
return substr(.source, .current+1, 1)
endwith
endfunc
hidden function skipWhitespace
with this
local ch
do while inlist(.peek(), chr(9), chr(10), chr(13), chr(32))
ch = .advance()
if ch == chr(10)
.line = .line + 1
endif
enddo
endwith
endfunc
hidden function identifier
with this
local lexeme
do while at(.peek(), .letters) > 0
.advance()
enddo
lexeme = substr(.source, .start, .current-.start)
if inlist(lexeme, "true", "false", "null")
return .addToken(iif(lexeme == 'null', T_NULL, T_BOOLEAN), lexeme)
else
.showError(.line, "Lexer Error: Unexpected identifier '" + lexeme + "'")
endif
endwith
endfunc
hidden function number(tChar as Character)
with this
local lexeme, isNegative
lexeme = ''
isNegative = tChar == '-'
do while isdigit(.peek())
.advance()
enddo
if .peek() == '.' and isdigit(.peekNext())
.advance() && eat the dot '.'
do while isdigit(.peek())
.advance()
enddo
endif
&& Check if number is a Scientific Notation
if lower(.peek()) == "e"
.advance() && eat 'e' or 'E'
&& Optional sign
if .peek() == '+' or .peek() == '-'
.advance()
endif
&& Must have at least one digit
if !isdigit(.peek())
&& Error: malformed scientific notation
.showError(.line, "Invalid scientific notation")
return
endif
do while isdigit(.peek())
.advance()
enddo
endif
lexeme = substr(.source, .start, .current-.start)
return .addToken(T_NUMBER, lexeme)
endwith
endfunc
hidden function string
with this
local lexeme, ch
do while !.isAtEnd()
ch = .peek()
do case
case ch == '\' and inlist(.peekNext(), '\', '/', 'n', 'r', 't', '"', "'")
.advance()
case ch = '"'
.advance()
exit
case ch == ',' and inlist(.peekNext(), '"', "'") and type('This._anyType_') == 'C' and alltrim(this._anyType_) == 'anyType'
.advance()
exit
endcase
.advance()
enddo
lexeme = substr(.source, .start+1, .current-.start-2)
.escapeCharacters(@lexeme)
.checkUnicodeFormat(@lexeme)
return .addToken(T_STRING, lexeme)
endwith
endfunc
hidden function currency
with this
local lexeme, isNegative
lexeme = ''
isNegative = (.peek() == '-')
if isNegative
.advance()
endif
do while isdigit(.peek())
.advance()
enddo
* Loop while there is a comma ','
do while .t.
if .peek() == ',' and isdigit(.peekNext())
.advance() && eat the comma ','
do while isdigit(.peek())
.advance()
enddo
else
exit
endif
enddo
* Check for decimal part
if .peek() == '.' and isdigit(.peekNext())
.advance() && eat the dot '.'
do while isdigit(.peek())
.advance()
enddo
endif
lexeme = substr(.source, .start+1, .current-.start)
return .addToken(T_NUMBER, strtran(lexeme, ','))
endwith
endfunc
procedure escapeCharacters(tcLexeme)
if len(tcLexeme) < 100
local lcResult, i, lcChar, lcNextChar
lcResult = ""
i = 1
do while i <= len(tcLexeme)
lcChar = substr(tcLexeme, i, 1)
if lcChar == "\" and i < len(tcLexeme)
lcNextChar = substr(tcLexeme, i + 1, 1)
do case
case lcNextChar == "\"
lcResult = lcResult + "\"
case lcNextChar == "/"
lcResult = lcResult + "/"
case lcNextChar == "n"
lcResult = lcResult + chr(10)
case lcNextChar == "r"
lcResult = lcResult + chr(13)
case lcNextChar == "t"
lcResult = lcResult + chr(9)
case lcNextChar == '"'
lcResult = lcResult + '"'
case lcNextChar == "'"
lcResult = lcResult + "'"
otherwise
* Si no es una secuencia de escape conocida, mantener ambos caracteres
lcResult = lcResult + "\" + lcNextChar
endcase
i = i + 2 && Avanzar 2 caracteres
else
lcResult = lcResult + lcChar
i = i + 1 && avanzar un car�cter
endif
enddo
tcLexeme = lcResult
else
tcLexeme = strtran(tcLexeme, '\\', '\')
tcLexeme = strtran(tcLexeme, '\/', '/')
tcLexeme = strtran(tcLexeme, '\n', chr(10))
tcLexeme = strtran(tcLexeme, '\r', chr(13))
tcLexeme = strtran(tcLexeme, '\t', chr(9))
tcLexeme = strtran(tcLexeme, '\"', '"')
tcLexeme = strtran(tcLexeme, "\'", "'")
endif
endproc
procedure checkUnicodeFormat(tcLexeme)
* Look for unicode format
** This conversion is better (in performance) than Regular Expressions.
&& IRODG 09/10/2023 Inicio
local lcUnicode, lcConversion, lbReplace, lnPos
lnPos = 1
do while .t.
lbReplace = .f.
lcUnicode = substr(tcLexeme, at('\u', tcLexeme, lnPos), 6)
if len(lcUnicode) == 6
lbReplace = .t.
else
lcUnicode = substr(tcLexeme, at('\U', tcLexeme, lnPos), 6)
if len(lcUnicode) == 6
lbReplace = .t.
endif
endif
if lbReplace
tcLexeme = strtran(tcLexeme, lcUnicode, strtran(strconv(lcUnicode,16), chr(0)))
else
exit
endif
enddo
&& IRODG 09/10/2023 Fin
endproc
function scanTokens
with this
dimension .tokens[1]
do while !.isAtEnd()
.skipWhitespace()
.start = .current
.scanToken()
enddo
.addToken(T_EOF, "")
.capacity = .length-1
* Shrink array
dimension .tokens[.capacity]
local loTokens
loTokens = createobject("Empty")
addproperty(loTokens, "tokens["+alltrim(str(.capacity))+"]", null)
* Crear una copia de los tokens
local i
for i = 1 to .capacity
* Si los tokens son objetos, crear copias profundas
if type('.tokens[i]') = 'O'
loTokens.tokens[i] = createobject("Empty")
=addproperty(loTokens.tokens[i], "type", .tokens[i].type)
=addproperty(loTokens.tokens[i], "value", .tokens[i].value)
=addproperty(loTokens.tokens[i], "line", .tokens[i].line)
else
loTokens.tokens[i] = .tokens[i]
endif
next
.CleanUp()
return loTokens
endwith
endfunc
hidden function scanToken
with this
local ch
ch = .advance()
do case
case ch == '{'
return .addToken(T_LBRACE, ch)
case ch == '}'
return .addToken(T_RBRACE, ch)
case ch == '['
return .addToken(T_LBRACKET, ch)
case ch == ']'
return .addToken(T_RBRACKET, ch)
case ch == ':'
return .addToken(T_COLON, ch)
case ch == ','
return .addToken(T_COMMA, ch)
case ch == '"'
return .string()
case ch == '$'
return .currency()
otherwise
if isdigit(ch) or (ch == '-' and isdigit(.peek()))
return .number(ch)
endif
if at(ch, .letters) > 0
return .identifier()
endif
.showError(.line, "Unknown character ['" + transform(ch) + "'], ascii: [" + transform(asc(ch)) + "]")
endcase
endwith
endfunc
hidden function addToken(tnTokenType, tcTokenValue)
with this
.checkCapacity()
local loToken
loToken = createobject("Empty")
=addproperty(loToken, "type", tnTokenType)
=addproperty(loToken, "value", tcTokenValue)
=addproperty(loToken, "line", .line)
.tokens[.length] = loToken
.length = .length + 1
endwith
endfunc
hidden function checkCapacity
with this
if .capacity < .length + 1
if empty(.capacity)
.capacity = 8
else
.capacity = .capacity * 2
endif
dimension .tokens[.capacity]
endif
endwith
endfunc
function showError(tnLine, tcMessage)
error "SYNTAX ERROR: (" + transform(tnLine) + ":" + transform(this.current) + ")" + tcMessage
endfunc
function isAtEnd
with this
return .current > .sourceLen
endwith
endfunc
function tokenStr(toToken)
local lcType, lcValue, loUtils
loUtils = iif(vartype(this.oUtils) == 'O', this.oUtils, _screen.jsonUtils)
lcType = loUtils.tokenTypeToStr(toToken.type)
lcValue = alltrim(transform(toToken.value))
return "Token(" + lcType + ", '" + lcValue + "') at Line(" + alltrim(str(toToken.line)) + ")"
endfunc
function CleanUp
with this
* Liberar el array de tokens
if type('this.tokens', 1) == 'A' and alen(this.tokens) > 1
local i
for i = 1 to alen(this.tokens)
if type('this.tokens[i]') = 'O'
* Liberar propiedades del objeto token
this.tokens[i] = .null.
endif
next
* Redimensionar el array a tama�o m�nimo
dimension this.tokens[1]
this.tokens[1] = .null.
endif
* Liberar otras variables que puedan ocupar mucha memoria
this.source = ""
this.sourceLen = 0
this.capacity = 0
this.length = 1
endwith
return .t.
endfunc
enddefine
* ── src\parser.prg ── *
&& ======================================================================== &&
&& JsonParser
&& EBNF Grammar
&& object = '{' kvp | { ',' kvp } '}'
&& kvp = KEY ':' value
&& value = STRING | NUMBER | BOOLEAN | array | object | null
&& array = '[' value | { ',' value } ']'
&& ======================================================================== &&
define class Parser as custom
Hidden current
Hidden previous
Hidden peek
hidden problematicFields
hidden tokenCollection
hidden lUseArrayObjects
oUtils = .null.
function init(toScanner, tlUseArrayObjects)
this.tokenCollection = toScanner.scanTokens()
this.current = 1
this.lUseArrayObjects = IIF(PCOUNT() > 1, tlUseArrayObjects, .F.)
this.problematicFields = createobject("Collection")
this.problematicFields.Add("messages", "messages")
this.problematicFields.Add("update", "update")
endfunc
function Parse
private JSONUtils
JSONUtils = iif(vartype(this.oUtils) == 'O', this.oUtils, _screen.jsonUtils)
local loParsedObject
loParsedObject = this.value()
this.CleanUp()
return loParsedObject
endfunc
&& ======================================================================== &&
&& Function Object
&& EBNF -> object = '{' kvp ( ',' kvp )* '}'
&& kvp = KEY ':' value
&& ======================================================================== &&
hidden function object as object
local loObj, loPair, lcMacro
loObj = createobject('Empty')
if !this.check(T_RBRACE)
loPair = this.kvp()
this.addKeyValuePair(@loObj, @loPair)
do while this.match(T_COMMA)
loPair = this.kvp()
this.addKeyValuePair(@loObj, @loPair)
enddo
endif
this.consume(T_RBRACE, "Expect '}' after JSON body.")
return loObj
endfunc
&& ======================================================================== &&
&& Function Kvp
&& EBNF -> kvp = KEY ':' value
&& ======================================================================== &&
hidden function kvp(toObj)
local loPair, lvValue
loPair = CreateObject('Empty')
=AddProperty(loPair, 'key', '')
this.consume(T_STRING, "Expect key name")
loPair.key = JSONUtils.CheckProp(this.previous.value)
this.consume(T_COLON, "Expect ':' after key element.")
lvValue = this.value()
if this.lUseArrayObjects
=AddProperty(loPair, 'value', lvValue)
else
If Type('lvValue', 1) != 'A'
=AddProperty(loPair, 'value', lvValue)
Else
=AddProperty(loPair, 'value[1]', .Null.)
Acopy(lvValue, loPair.value)
endif
endif
Return loPair
EndFunc
Hidden function addKeyValuePair(toObject, toPair)
local lAddObject
lAddObject = .f.
if this.lUseArrayObjects
=AddProperty(toObject, toPair.key, toPair.value)
else
If Type('toPair.value', 1) != 'A'
=AddProperty(toObject, toPair.key, toPair.value)
else
lAddObject = .t.
endif
endif
if lAddObject
local lcMacro
if this.problematicFields.GetKey(toPair.key) > 0
local lcArrayName
lcArrayName = toPair.key + "_array"
lcMacro = "AddProperty(toObject, '" + lcArrayName + "[1]', .null.)"
&lcMacro
lcMacro = "Acopy(toPair.value, toObject." + lcArrayName + ")"
&lcMacro
=addproperty(toObject, "_specialArray_" + lcArrayName, toPair.key)
else
Local lcMacro
lcMacro = "AddProperty(toObject, '" + toPair.key + "[1]', .Null.)"
&lcMacro
lcMacro = "Acopy(toPair.value, toObject." + toPair.key + ")"
&lcMacro
endif
endif
EndFunc
&& ======================================================================== &&
&& Function Value
&& EBNF -> value = STRING | NUMBER | BOOLEAN | array | object | NULL
&& ======================================================================== &&
hidden function value
do case
case this.match(T_STRING)
return JSONUtils.CheckString(this.previous.value)
case this.match(T_NUMBER)
Local lcValue, lcPoint
lcValue = this.previous.value
lcPoint = Set("Point")
If lcPoint != '.'
lcValue = Strtran(lcValue, '.', lcPoint)
EndIf
return iif(at(lcPoint, lcValue) > 0, evaluate(lcValue), int(Val(lcValue)))
case this.match(T_BOOLEAN)
return (this.previous.value == 'true')
case this.match(T_LBRACE)
return this.object()
case this.match(T_LBRACKET)
if this.lUseArrayObjects
return this.array()
endif
return @this.array()
case this.match(T_NULL)
return .null.
otherwise
error "Parser Error: Unknown token value: '" + JSONUtils.tokenTypeToStr(this.peek.type) + "'"
EndCase
endfunc
&& ======================================================================== &&
&& Function Array
&& EBNF -> array = '[' value | { ',' value } ']'
&& ======================================================================== &&
hidden function array
local laArray
if this.lUseArrayObjects
laArray = createobject("TParserInternalArrayCollectionBased")
else
laArray = createobject("TParserInternalArray")
endif
If !this.check(T_RBRACKET)
laArray.Push(this.value())
do while this.match(T_COMMA)
laArray.Push(this.value())
enddo
endif
this.consume(T_RBRACKET, "Expect ']' after array elements.")
if this.lUseArrayObjects
return laArray
endif
return @laArray.getArray()
endfunc
Function match(tnTokenType)
If this.check(tnTokenType)
this.advance()
Return .t.
EndIf
Return .f.
EndFunc
Hidden Function consume(tnTokenType, tcMessage)
If this.check(tnTokenType)
Return this.advance()
EndIf
if empty(tcMessage)
tcMessage = "Parser Error: expected token '" + JSONUtils.tokenTypeToStr(tnTokenType) + "' got = '" + JSONUtils.tokenTypeToStr(this.peek.type) + "'"
endif
error tcMessage
endfunc
Hidden Function check(tnTokenType)
If this.isAtEnd()
Return .f.
EndIf
Return this.peek.type == tnTokenType
EndFunc
Hidden Function advance
If !this.isAtEnd()
this.current = this.current + 1
EndIf
Return this.tokenCollection.tokens[this.current-1]
endfunc
Hidden Function isAtEnd
Return this.peek.type == T_EOF
endfunc
Hidden Function peek_access
Return this.tokenCollection.tokens[this.current]
endfunc
Hidden Function previous_access
Return this.tokenCollection.tokens[this.current-1]
endfunc
function CleanUp
with this
.TokenCollection = .null.
.current = 0
.previous = .null.
.peek = .null.
endwith
endfunc
EndDefine
* ============================================================ *
* TParserInternalArray
* ============================================================ *
Define Class TParserInternalArray As Custom
Dimension aCustomArray[1]
nIndex = 0