-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.pas
More file actions
5103 lines (4780 loc) · 144 KB
/
parser.pas
File metadata and controls
5103 lines (4780 loc) · 144 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
{******************************************************************************
Plan9Basic Interpreter Engine
MIT License
Copyright (c) 2026 André Murta
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.
******************************************************************************}
unit parser;
interface
uses
System.SysUtils, System.Character, System.StrUtils,
System.Generics.Collections, System.TypInfo,
UnitUtils, lexer, exec;
const
// Local registers string representation for intermediate code generation
// Functions have 3 local registers (@3 @4 @5) for internal use
LOCAL_REG_STR = '3 4 5';
type
//program status
TBasStatus = (BasReady, BasRunning, BasTerminated);
//BASIC source code compiling results
TCompResult = (
compOk, compLabel, compVariable, compFunction, compDupFunction, compDupVar,
compFncParm, compUnbalancedIfElse, compUnbalancedCases, compMispCaseElse,
compMispElse, compMispElseIf
);
//User created functions
TFunctionData = record
funcSignature: String; //Function signature 'name@...'
Entry: Integer; //Function entry point
ArgCount: Word; //Total of arguments
ArgType: Array[0..MAXLOCALS] of TExprKind; //Type of each argument
end;
TUserFunctionsDictionary = TDictionary<String, TFunctionData>; //Type for the user functions dictionary
TStrList = TList<String>; //Type for a list of strings
//************
//TBasicParser
//************
//
//Process the tokens extracted by the lexer validating them semantically.
//If parsing completes OK, a list with the intermediate code instructions
//is produced to the compiler class.
//
TBasicParser = class
private
status: TBasStatus;
TMPOutput: TStringTokens;
forCnt, ifCnt, whileCnt, repeatCnt, selectCnt, doCnt, fError: Integer;
forVarStack: array[0..MAXSTACK] of String; //Stack to track FOR loop control variables
inFunction: Boolean;
lastFunc: TBasToken; //Info about the current function
selType: array[0..MAXSTACK] of TExprKind; //Last SELECT/CASE type
//Used to check if the last select has a CASE ELSE statement
selCaseElse: array[0..MAXSTACK] of Boolean;
errCompStr: array [TCompResult] of String; //preprocessing errors list
FGlobalVars: TStrList;
FDoubleCloseConsumed: Boolean; // JSON: tracks ]] token consumption for nested arrays
//Indirect pointer array
procedure ParsePointerArrayNumGet();
procedure ParsePointerArrayStrGet();
procedure ParsePointerArrayPtrGet();
//Indirect call manager
procedure ParseIndirectCall(CallType: TExprKind);
//--------------------------------------------------------------
//Logic expressions
//--------------------------------------------------------------
procedure NextLogicExpression();
procedure NextLogicArith();
procedure NextLogicValue();
function IsLogicalGrouping(): Boolean; // Lookahead helper for parenthesized expressions
//--------------------------------------------------------------
//Pointer expressions
//--------------------------------------------------------------
procedure NextPointerExpression();
//--------------------------------------------------------------
//Numerical expressions
//--------------------------------------------------------------
procedure NextNumericExpression();
procedure NextArith();
procedure NextFactor();
procedure NextValue();
//--------------------------------------------------------------
//String expressions
//--------------------------------------------------------------
procedure NextStringExpression();
procedure NextStringValue();
//--------------------------------------------------------------
// JSON literal parsing support
//--------------------------------------------------------------
procedure ParseJsonArray(); // Parses JSON array literal [...]
procedure ParseJsonObject(); // Parses JSON object literal {...}
procedure ParseJsonValue(); // Parses a single JSON value (for array elements)
procedure ParseJsonKeyValue(); // Parses a key-value pair (for object properties)
function EscapeJsonString(const s: String): String; // Escapes string for intermediate code
//--------------------------------------------------------------
function GetError(): Boolean;
procedure AssignNum(); //Numeric assignment
procedure AssignStr(); //String assignment
procedure AssignPtr(); //Pointer assignment
procedure AssignPointerArrayNum(); //id#[...] = numeric expression
procedure AssignPointerArrayStr(); //id#$[...] = string expression
procedure AssignPointerArrayPtr(); //id##[...] = pointer expression
procedure ParseData(); //DATA
procedure ParseRead(); //READ
procedure ParseRefreshRate(); //REFRESHRATE
procedure ParseRestore(); //RESTORE
procedure ParseFunction(); //FUNCTION
procedure ParseEndFunction(); //ENDFUNCTION
procedure ParseReturn(); //RETURN
procedure ParseUnassignedNumFunction(); //fnc(...)
procedure ParseUnassignedStrFunction(); //fnc$(...)
procedure ParseUnassignedPtrFunction(); //fnc#(...)
procedure ParseNext(); //NEXT
procedure ParseFor(); //FOR [ .. NEXT]
procedure ParseIf(); //IF
procedure ParseElse(); //ELSE
procedure ParseEndif(); //ENDIF
procedure ParseWhile(); //WHILE
procedure ParseEndWhile(); //ENDWHILE
procedure ParseRepeat(); //REPEAT
procedure ParseUntil(); //UNTIL
procedure ParseDo(); //DO [WHILE|UNTIL]
procedure ParseLoop(); //LOOP [WHILE|UNTIL]
procedure ParseBreak(); //BREAK
procedure ParseContinue(); //CONTINUE
procedure ParsePrint(); //PRINT
procedure ParsePrintLn(); //PRINTLN
procedure ParseEnd(); //END
procedure ParseInput(); //INPUT
procedure ParseCls(); //CLS
procedure ParseSelect(); //SELECT
procedure ParseCase(); //CASE
procedure ParseEndSelect(); //ENDSELECT
procedure ParseLabel(); //integer beginning a line
procedure ParseGoto(); //GOTO
procedure ParseGosub(); //GOSUB
procedure ParseOn(); //ON
//Debug commands
procedure ParseAssert(); //ASSERT
procedure ParseBreakpoint(); //BREAKPOINT
procedure ParseDump(); //DUMP
procedure ParseTrace(); //TRACE
procedure ParseTraceOn(); //TRACEON
procedure ParseTraceOff(); //TRACEOFF
procedure ParseWatch(); //WATCH
procedure ParseUnwatch(); //UNWATCH
procedure NextCommand();
function SafeRound(d: Double; imin, imax: Integer): Integer;
function GetParams(): String;
procedure ClearCounts();
function CheckCounters(): Boolean;
function ExpressionKind(tok: TBasToken): TExprKind;
procedure Clear();
procedure Emmit(s: String);
procedure NextInstruction();
procedure SetError(err: String);
public
UserFunctionsTable: TUserFunctionsDictionary; //UDFs table
LibFunctionsTable: TFunctionsDictionary; //All functions available
errPos, errLine: Integer;
lastErr: String;
lexer: TBasicLexer; //lexer
exec: TExec; //stack machine
constructor Create();
destructor Destroy(); override;
function Compile(input: PChar; debug: TStrList; var INTOutput, ASMOutput: TStringTokens; var libFuncs: TFunctionsDictionary): Integer;
function ProcessPostfixCode(PostFix: TStringTokens; var ASMOutput: TStringTokens; var libFuncs: TFunctionsDictionary; debug: TStrList): Integer;
property Error: String read lastErr;
property ErrorPos: Integer read errPos;
property ErrorLine: Integer read errLine;
property CompileStatus: TBasStatus read status;
property GlobalVars: TStrList read FGlobalVars;
end;
//*********
//TCompiler
//*********
//
//Executes a series of passes through the intermediate code produced by the
//parser and generates the final assembly instructions to be executed by the
//stack machine.
//
TCompiler = class
private
compResult: TCompResult; //The result of the intermediate code compilation
postfixCode: TStringTokens; //Intermediate code to analyze
errLine: Integer;
asmLexer: TAsmLexer; //Postfix tokenizer
FGlobalVars: TStrList; //Keep track of global variables
//List with entry points for all function available to the program (UDFs and
//imported)
ProgramFunctions: TFunctionsDictionary;
//Table to hold UDFs data
//Used in classes TBasic and TBasicParser
UserFunctionsTable: TUserFunctionsDictionary;
//List to hold the contents of each DATA statement at the source code
DataStmts: TDataItems;
//--------------------------------------------------------------------------
//Compiler methods
//--------------------------------------------------------------------------
procedure AssignLabels(); //label declarations
procedure AssignTokens(); //label each token in the intermediary code
procedure AssignCommas(); //relationship between BASIC source and instructions
procedure EnumVarsFuncs(); //position of globals, locals, functions
procedure AssignIfCRLF(); //one line IF
procedure AssignIf(); //multiline IF
procedure AssignBreak(); //BREAK
procedure AssignContinue(); //CONTINUE
procedure AssignRepeat(); //REPEAT
procedure AssignWhile(); //WHILE
procedure AssignDo(); //DO...LOOP
procedure AssignFuncs(); //functions entry points
procedure SkipFuncs(); //additional functions processing
procedure AssignData(); //Find the position of each DATA command at the source
procedure AssignSelect(); //SELECT .. CASE
//--------------------------------------------------------------------------
procedure FindErrline();
function StrItem(str: String; value: TAsmToken): TStringToken;
public
ErrDetail: String; //Detailed error message (includes variable/function name)
constructor Create();
destructor Destroy(); override;
function Compile(source: TStringTokens; funcs: TFunctionsDictionary): TCompResult;
function ReturnRegisteredFunctions: TUserFunctionsDictionary;
function RegisterFuncData(source: String; out Signature: String; out ParamCount: Word; out ParamType: Array of TExprKind): Boolean;
end;
implementation
{ TBasicParser }
procedure TBasicParser.AssignNum();
var
s: String;
begin
s := lexer.CurrS(); //variable to store numerical expression result.
if lexer.NextTok() <> btkEqual then
begin
status := BasTerminated;
SetError('Expected numeric assignment');
Exit;
end;
lexer.Advance; //skip identifier
lexer.Advance(); //skip '=' or ':=' operator
NextNumericExpression(); //numeric expression
Emmit('POPSTORE @' + s); //store at the indicated var
end;
procedure TBasicParser.AssignPointerArrayNum();
var
s: String;
i: Integer;
begin
i := 0;
s := lexer.CurrS();
Emmit('PUSH# @'+s);
Inc(i);
lexer.Advance(); //skips the '['
if ExpressionKind(lexer.CurrTok) <> TExprKind.ekNumber then
begin
Status := BasTerminated;
SetError('Numeric expression expected');
Exit();
end;
NextNumericExpression();
Inc(i);
if (lexer.CurrTok() <> btkComma) and (lexer.CurrTok() <> btkSquareClose) then
begin
Status := BasTerminated;
SetError('] expected');
Exit();
end;
if lexer.CurrTok() <> btkSquareClose then
repeat
lexer.Advance();
NextNumericExpression();
Inc(i);
until lexer.CurrTok() <> btkComma;
if lexer.CurrTok() <> btkSquareClose then
begin
Status := BasTerminated;
SetError('] expected');
Exit();
end;
lexer.Advance(); //skip the ']'
if lexer.CurrTok() <> btkEqual then
begin
status := BasTerminated;
SetError('Expected numeric assignment');
Exit();
end;
lexer.Advance(); //skip the '='
NextNumericExpression(); //numeric expression
Inc(i);
Emmit('PUSHC '+IntToStr(i));
Emmit('CALLEX# "narr_set#@#'+System.StrUtils.DupeString('n',i-1)+'"'); //store at the indicated var
Emmit('POP'); //discard the returned pointer (stack cleanup)
end;
procedure TBasicParser.AssignPointerArrayPtr();
var
s: String;
i: Integer;
begin
i := 0;
s := lexer.CurrS().Substring(0, lexer.CurrS().Length-1);
Emmit('PUSH# @'+s);
Inc(i);
lexer.Advance(); //skips the '['
if ExpressionKind(lexer.CurrTok) <> TExprKind.ekNumber then
begin
Status := BasTerminated;
SetError('Numeric expression expected');
Exit();
end;
NextNumericExpression();
Inc(i);
if (lexer.CurrTok() <> btkComma) and (lexer.CurrTok() <> btkSquareClose) then
begin
Status := BasTerminated;
SetError('] expected');
Exit();
end;
if lexer.CurrTok() <> btkSquareClose then
repeat
lexer.Advance();
NextNumericExpression();
Inc(i);
until lexer.CurrTok() <> btkComma;
if lexer.CurrTok() <> btkSquareClose then
begin
s := lexer.CurrS();
Status := BasTerminated;
SetError('] expected');
Exit();
end;
lexer.Advance(); //skip the ']'
if lexer.CurrTok() <> btkEqual then
begin
status := BasTerminated;
SetError('Expected numeric assignment');
Exit();
end;
lexer.Advance(); //skip the '='
NextPointerExpression(); //pointer expression
Inc(i);
Emmit('PUSHC '+IntToStr(i));
Emmit('CALLEX# "parr_set#@#'+System.StrUtils.DupeString('n',i-2)+'#"'); //store at the indicated var
Emmit('POP'); //discard the returned pointer (stack cleanup)
end;
procedure TBasicParser.AssignPointerArrayStr();
var
s: String;
i: Integer;
begin
i := 0;
s := lexer.CurrS().Substring(0, lexer.CurrS().Length-1);
Emmit('PUSH# @'+s);
Inc(i);
lexer.Advance(); //skips the '['
if ExpressionKind(lexer.CurrTok) <> TExprKind.ekNumber then
begin
Status := BasTerminated;
SetError('Numeric expression expected');
Exit();
end;
NextNumericExpression();
Inc(i);
if (lexer.CurrTok() <> btkComma) and (lexer.CurrTok() <> btkSquareClose) then
begin
Status := BasTerminated;
SetError('] expected');
Exit();
end;
if lexer.CurrTok() <> btkSquareClose then
repeat
lexer.Advance();
NextNumericExpression();
Inc(i);
until lexer.CurrTok() <> btkComma;
if lexer.CurrTok() <> btkSquareClose then
begin
s := lexer.CurrS();
Status := BasTerminated;
SetError('] expected');
Exit();
end;
lexer.Advance(); //skip the ']'
if lexer.CurrTok() <> btkEqual then
begin
status := BasTerminated;
SetError('Expected numeric assignment');
Exit();
end;
lexer.Advance(); //skip the '='
NextStringExpression(); //string expression
Inc(i);
Emmit('PUSHC '+IntToStr(i));
Emmit('CALLEX# "sarr_set#@#'+System.StrUtils.DupeString('n',i-2)+'$"'); //store at the indicated var
Emmit('POP'); //discard the returned pointer (stack cleanup)
end;
procedure TBasicParser.AssignPtr();
var
s: String;
begin
s := lexer.CurrS().ToLower(); //save pointer identifier name
if lexer.NextTok = btkEqual then // ptr# = ...
begin
lexer.Advance(); //skip the pointer identifier
lexer.Advance(); //skip the '=' operator
// JSON SUPPORT - Check for JSON literal syntax
case lexer.CurrTok() of
btkSquareOpen: // JSON array literal [...]
begin
ParseJsonArray();
Emmit('POPSTORE# @' + s);
end;
btkCurlyOpen: // JSON object literal {...}
begin
ParseJsonObject();
Emmit('POPSTORE# @' + s);
end;
else
begin
// Regular pointer expression
NextPointerExpression();
Emmit('POPSTORE# @' + s);
end;
end;
end
else
begin
status := BasTerminated;
SetError('Expected a pointer assignment');
Exit();
end;
end;
//All possible string attributions
procedure TBasicParser.AssignStr();
var
s: String;
begin
s := lexer.CurrS();
if lexer.CurrTok() = btkCharArray then //var$[[index]] = expression$
begin
Emmit('PUSH$ @'+s);
lexer.Advance(); //skip variable
NextNumericExpression(); //numerical index between brackets [ ]
//Store the index at internal register (0)
Emmit('POPSTORE @0');
if lexer.CurrTok() <> btkDoubleSquareClose then
begin
status := BasTerminated;
SetError(']] expected');
Exit();
end;
if lexer.NextTok <> btkEqual then
begin
status := BasTerminated;
SetError('Expected char assignment');
Exit();
end;
lexer.Advance(); //skip square close
Emmit('PUSH @0'); //get index back on the stack
lexer.Advance(); //skip the assignment token
NextStringExpression(); //assignment
Emmit('PUSHC 3');
Emmit('CALLEX$ "chr$@$n$" ');
Emmit('POPSTORE$ @' + s);
end
else if lexer.CurrTok() = btkStrArray then //var$[index] = expression$
begin
Emmit('PUSH$ @'+s);
lexer.Advance(); //skip variable
NextNumericExpression(); //numerical index between brackets [ ]
//Store the index at internal register (0)
Emmit('POPSTORE @0');
if lexer.CurrTok() <> btkSquareClose then
begin
status := BasTerminated;
SetError('] expected');
Exit();
end;
if lexer.NextTok <> btkEqual then
begin
status := BasTerminated;
SetError('Expected line assignment');
Exit();
end;
lexer.Advance(); //skip the ']'
Emmit('PUSH @0'); //get index back on the stack
lexer.Advance(); //skip the '='
NextStringExpression(); //attribution
Emmit('PUSHC 3');
Emmit('CALLEX$ "line$@$n$" ');
Emmit('POPSTORE$ @' + s);
end
else
begin
if lexer.NextTok <> btkEqual then
begin
status := BasTerminated;
SetError('Expected string assignment');
Exit;
end;
lexer.Advance(); //skip square close
lexer.Advance(); //skip '=' operator
NextStringExpression(); //String expression
Emmit('POPSTORE$ @' + s); //store at the indicated var
end;
end;
//------------------------------------------------------------------------------
// JSON SUPPORT - Helper function to escape strings for intermediate code
//------------------------------------------------------------------------------
function TBasicParser.EscapeJsonString(const s: String): String;
var
i: Integer;
ch: Char;
begin
Result := '';
for i := 1 to Length(s) do
begin
ch := s[i];
case ch of
'"': Result := Result + '\"';
'\': Result := Result + '\\';
#10: Result := Result + '\n';
#13: Result := Result + '\r';
#9: Result := Result + '\t';
else Result := Result + ch;
end;
end;
end;
//------------------------------------------------------------------------------
// JSON SUPPORT - Parse JSON array literal [...]
//------------------------------------------------------------------------------
procedure TBasicParser.ParseJsonArray();
begin
// Create empty JSON array
Emmit('PUSHC 0'); // 0 arguments for json_array#()
Emmit('CALLEX# "json_array#@" ');
lexer.Advance(); // Skip '['
// Skip any newlines after opening bracket
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Handle empty array []
if lexer.CurrTok() = btkSquareClose then
begin
lexer.Advance(); // Skip ']'
Exit;
end;
// Parse first element
ParseJsonValue();
if GetError then Exit; // Propagate error from nested parse
// Skip any newlines after element
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Parse remaining elements
while lexer.CurrTok() = btkComma do
begin
lexer.Advance(); // Skip ','
// Skip any newlines after comma
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Check for trailing comma (comma followed by ])
if lexer.CurrTok() = btkSquareClose then
begin
status := BasTerminated;
SetError('Trailing comma not allowed in JSON array');
Exit;
end;
ParseJsonValue();
if GetError then Exit; // Propagate error from nested parse
// Skip any newlines after element
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
end;
// Expect closing bracket - handle both ] and ]] tokens
// The lexer combines ]] into btkDoubleSquareClose (used for str$[[index]])
// For nested JSON arrays, we need to handle this specially
if lexer.CurrTok() = btkSquareClose then
begin
lexer.Advance(); // Normal case: single ]
end
else if lexer.CurrTok() = btkDoubleSquareClose then
begin
// ]] token: represents two closing brackets
// Use flag to track consumption - first consumer doesn't advance,
// second consumer advances past the entire ]] token
if FDoubleCloseConsumed then
begin
lexer.Advance(); // Second consumer: advance past ]]
FDoubleCloseConsumed := False;
end
else
FDoubleCloseConsumed := True; // First consumer: mark as consumed, don't advance
end
else
begin
status := BasTerminated;
if lexer.CurrTok() = btkCurlyClose then
SetError('Mismatched bracket: found "}" but expected "]" in JSON array')
else if lexer.CurrTok() = btkNull then
SetError('Unexpected end of program inside JSON array - missing "]"')
else
SetError('] expected in JSON array, found "' + lexer.CurrS() + '"');
Exit;
end;
end;
//------------------------------------------------------------------------------
// JSON SUPPORT - Parse JSON object literal {...}
//------------------------------------------------------------------------------
procedure TBasicParser.ParseJsonObject();
begin
// Create empty JSON object
Emmit('PUSHC 0'); // 0 arguments for json_object#()
Emmit('CALLEX# "json_object#@" ');
lexer.Advance(); // Skip '{'
// Skip any newlines after opening brace
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Handle empty object {}
if lexer.CurrTok() = btkCurlyClose then
begin
lexer.Advance(); // Skip '}'
Exit;
end;
// Parse first key-value pair
ParseJsonKeyValue();
if GetError then Exit; // Propagate error from nested parse
// Skip any newlines after key-value pair
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Parse remaining pairs
while lexer.CurrTok() = btkComma do
begin
lexer.Advance(); // Skip ','
// Skip any newlines after comma
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Check for trailing comma (comma followed by })
if lexer.CurrTok() = btkCurlyClose then
begin
status := BasTerminated;
SetError('Trailing comma not allowed in JSON object');
Exit;
end;
ParseJsonKeyValue();
if GetError then Exit; // Propagate error from nested parse
// Skip any newlines after key-value pair
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
end;
// Expect closing brace
if lexer.CurrTok() <> btkCurlyClose then
begin
status := BasTerminated;
if lexer.CurrTok() = btkSquareClose then
SetError('Mismatched bracket: found "]" but expected "}" in JSON object')
else if lexer.CurrTok() = btkNull then
SetError('Unexpected end of program inside JSON object - missing "}"')
else if lexer.CurrTok() = btkString then
SetError('Missing comma before key "' + lexer.CurrS() + '" in JSON object')
else
SetError('} expected in JSON object, found "' + lexer.CurrS() + '"');
Exit;
end;
lexer.Advance(); // Skip '}'
end;
//------------------------------------------------------------------------------
// JSON SUPPORT - Parse a single JSON value (for array elements)
//------------------------------------------------------------------------------
procedure TBasicParser.ParseJsonValue();
var
st: String;
begin
case lexer.CurrTok() of
btkSquareOpen: // Nested array [...]
begin
ParseJsonArray();
// Array is on stack, push it to parent array
Emmit('PUSHC 2');
Emmit('CALLEX# "json_push#@##" ');
end;
btkCurlyOpen: // Nested object {...}
begin
ParseJsonObject();
// Object is on stack, push it to parent array
Emmit('PUSHC 2');
Emmit('CALLEX# "json_push#@##" ');
end;
btkString: // String literal "..."
begin
st := lexer.CurrS();
Emmit('PUSHC$ "' + EscapeJsonString(st) + '"');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushs#@#$" ');
lexer.Advance();
end;
btkInteger, btkFloat: // Numeric literal
begin
Emmit('PUSHC ' + TUtils.FloatToStr2(lexer.CurrN));
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushn#@#n" ');
lexer.Advance();
end;
btkMinus: // Negative number
begin
lexer.Advance();
if (lexer.CurrTok() = btkInteger) or (lexer.CurrTok() = btkFloat) then
begin
Emmit('PUSHC ' + TUtils.FloatToStr2(-lexer.CurrN));
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushn#@#n" ');
lexer.Advance();
end
else
begin
status := BasTerminated;
SetError('Number expected after minus in JSON');
Exit;
end;
end;
btkTrue: // true keyword
begin
Emmit('PUSHC 1');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushb#@#n" ');
lexer.Advance();
end;
btkFalse: // false keyword
begin
Emmit('PUSHC 0');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushb#@#n" ');
lexer.Advance();
end;
btkJsonNull: // null keyword
begin
Emmit('PUSHC 1');
Emmit('CALLEX# "json_pushnull#@#" ');
lexer.Advance();
end;
btkIdentifier: // Numeric variable
begin
Emmit('PUSH @' + lexer.CurrS().ToLower());
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushn#@#n" ');
lexer.Advance();
end;
btkStrIdentifier: // String variable
begin
Emmit('PUSH$ @' + lexer.CurrS().ToLower());
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushs#@#$" ');
lexer.Advance();
end;
btkPointerIdentifier: // Pointer variable (nested JSON)
begin
Emmit('PUSH# @' + lexer.CurrS().ToLower());
Emmit('PUSHC 2');
Emmit('CALLEX# "json_push#@##" ');
lexer.Advance();
end;
btkNumFunction: // Numeric function call
begin
st := LowerCase(lexer.CurrS());
lexer.Advance();
Emmit('CALLEX "'+st+'@'+GetParams+'" ');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushn#@#n" ');
end;
btkStrFunction: // String function call
begin
st := LowerCase(lexer.CurrS());
lexer.Advance();
Emmit('CALLEX$ "'+st+'@'+GetParams+'" ');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_pushs#@#$" ');
end;
btkPointerFunction: // Pointer function call
begin
st := LowerCase(lexer.CurrS());
lexer.Advance();
Emmit('CALLEX# "'+st+'@'+GetParams+'" ');
Emmit('PUSHC 2');
Emmit('CALLEX# "json_push#@##" ');
end;
btkCRLF: // Unexpected newline
begin
status := BasTerminated;
SetError('Unexpected end of line - JSON value expected');
Exit;
end;
btkComma: // Unexpected comma (e.g., [1,,2])
begin
status := BasTerminated;
SetError('Unexpected comma - JSON value expected');
Exit;
end;
btkSquareClose: // Unexpected ] (e.g., [1,])
begin
status := BasTerminated;
SetError('Unexpected "]" - JSON value expected (trailing comma?)');
Exit;
end;
btkCurlyClose: // Unexpected }
begin
status := BasTerminated;
SetError('Unexpected "}" - JSON value expected (trailing comma?)');
Exit;
end;
btkNull: // End of program
begin
status := BasTerminated;
SetError('Unexpected end of program inside JSON literal');
Exit;
end;
else
begin
status := BasTerminated;
SetError('Invalid JSON value: "' + lexer.CurrS() + '"');
Exit;
end;
end;
end;
//------------------------------------------------------------------------------
// JSON SUPPORT - Parse a key-value pair (for object properties)
//------------------------------------------------------------------------------
procedure TBasicParser.ParseJsonKeyValue();
var
keyStr, st: String;
begin
// Key must be a string literal
if lexer.CurrTok() <> btkString then
begin
status := BasTerminated;
if lexer.CurrTok() = btkIdentifier then
SetError('JSON object key must be a quoted string, not identifier "' + lexer.CurrS() + '"')
else if lexer.CurrTok() = btkInteger then
SetError('JSON object key must be a quoted string, not a number')
else if lexer.CurrTok() = btkCurlyClose then
SetError('Unexpected "}" - expected key or trailing comma not allowed')
else
SetError('String key expected in JSON object, found "' + lexer.CurrS() + '"');
Exit;
end;
keyStr := lexer.CurrS();
lexer.Advance(); // Skip key
// Expect colon
if lexer.CurrTok() <> btkColon then
begin
status := BasTerminated;
if lexer.CurrTok() = btkComma then
SetError('Missing value for key "' + keyStr + '" - found comma instead of colon')
else if lexer.CurrTok() = btkEqual then
SetError('Use ":" not "=" after key "' + keyStr + '" in JSON object')
else
SetError('":" expected after key "' + keyStr + '" in JSON object');
Exit;
end;
lexer.Advance(); // Skip ':'
// Skip any newlines after colon
while lexer.CurrTok() = btkCRLF do
lexer.Advance();
// Parse value based on its type
case lexer.CurrTok() of
btkSquareOpen: // Nested array
begin
Emmit('PUSHC$ "' + EscapeJsonString(keyStr) + '"'); // Push key FIRST
ParseJsonArray(); // Then parse array (pushes array pointer)
if GetError then Exit; // Propagate error from nested parse
Emmit('PUSHC 3');
Emmit('CALLEX# "json_set#@#$#" ');
end;
btkCurlyOpen: // Nested object
begin
Emmit('PUSHC$ "' + EscapeJsonString(keyStr) + '"'); // Push key FIRST
ParseJsonObject(); // Then parse object (pushes object pointer)
if GetError then Exit; // Propagate error from nested parse
Emmit('PUSHC 3');
Emmit('CALLEX# "json_set#@#$#" ');
end;
btkString: // String value
begin
st := lexer.CurrS();
Emmit('PUSHC$ "' + EscapeJsonString(keyStr) + '"');
Emmit('PUSHC$ "' + EscapeJsonString(st) + '"');
Emmit('PUSHC 3');
Emmit('CALLEX# "json_sets#@#$$" ');
lexer.Advance();
end;
btkInteger, btkFloat: // Numeric value
begin
Emmit('PUSHC$ "' + EscapeJsonString(keyStr) + '"');
Emmit('PUSHC ' + TUtils.FloatToStr2(lexer.CurrN));
Emmit('PUSHC 3');
Emmit('CALLEX# "json_setn#@#$n" ');
lexer.Advance();
end;
btkMinus: // Negative number
begin
lexer.Advance();
if (lexer.CurrTok() = btkInteger) or (lexer.CurrTok() = btkFloat) then
begin
Emmit('PUSHC$ "' + EscapeJsonString(keyStr) + '"');
Emmit('PUSHC ' + TUtils.FloatToStr2(-lexer.CurrN));
Emmit('PUSHC 3');
Emmit('CALLEX# "json_setn#@#$n" ');
lexer.Advance();
end
else
begin