-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQBasicInterp.pas
More file actions
2296 lines (2085 loc) · 59.4 KB
/
QBasicInterp.pas
File metadata and controls
2296 lines (2085 loc) · 59.4 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
{$MODE OBJFPC}{$H+}
unit QBasicInterp;
{
QBasicInterp - QBasic Interpreter Unit for Font Editor
This is a modified version of the standalone interpreter,
converted to a reusable unit that can be embedded in applications.
Key changes from standalone:
- No console I/O (uses callbacks)
- Custom function registration for Font API
- Error handling with exceptions
}
interface
uses
Classes, SysUtils, Math;
type
TTokenType = (
ttEOF, ttEOL, ttNumber, ttString, ttIdent, ttComma, ttSemicolon,
ttPlus, ttMinus, ttMult, ttDiv, ttMod, ttPower,
ttEQ, ttNE, ttLT, ttLE, ttGT, ttGE,
ttLParen, ttRParen, ttColon,
ttPRINT, ttINPUT, ttLET, ttIF, ttTHEN, ttELSE, ttELSEIF, ttEND,
ttFOR, ttTO, ttSTEP, ttNEXT, ttWHILE, ttWEND, ttDO, ttLOOP,
ttGOTO, ttGOSUB, ttRETURN, ttDIM, ttAS,
ttINTEGER, ttSINGLE, ttDOUBLE, ttSTRING_TYPE, ttREM,
ttCLS, ttLOCATE, ttCOLOR, ttSCREEN,
ttAND, ttOR, ttNOT, ttXOR,
ttSUB, ttFUNCTION, ttEXIT, ttCALL, ttSTATIC, ttSHARED,
ttSELECT, ttCASE, ttIS
);
TToken = record
TokenType: TTokenType;
Value: string;
Line: Integer;
Col: Integer;
end;
TVariable = record
Name: string;
IsString: Boolean;
NumValue: Double;
StrValue: string;
IsArray: Boolean;
ArrayDims: array of Integer;
ArrayData: array of Double;
ArrayStrData: array of string;
end;
TSubParameter = record
Name: string;
IsString: Boolean;
ByRef: Boolean;
end;
TSubProgram = record
Name: string;
StartPos: Integer;
EndPos: Integer;
IsFunction: Boolean;
Parameters: array of TSubParameter;
LocalVars: array of TVariable;
end;
TCallStackEntry = record
ReturnPos: Integer;
SubName: string;
SavedLocalVars: array of TVariable;
PrevSubIdx: Integer;
WasInSub: Boolean;
end;
TForStackEntry = record
VarName: string;
EndVal: Double;
StepVal: Double;
LoopPos: Integer;
end;
TLabelEntry = record
Name: string;
Position: Integer;
end;
{ Custom function callback types }
TBuiltinFuncNum = function(const Args: array of Double): Double of object;
TBuiltinFuncStr = function(const Args: array of Double; const StrArgs: array of string): string of object;
TBuiltinProc = procedure(const Args: array of Double; const StrArgs: array of string) of object;
TBuiltinFunction = record
Name: string;
MinArgs: Integer;
MaxArgs: Integer;
ReturnsString: Boolean;
NumFunc: TBuiltinFuncNum;
StrFunc: TBuiltinFuncStr;
ProcFunc: TBuiltinProc;
IsProc: Boolean;
end;
{ Event types }
TPrintEvent = procedure(const Text: string) of object;
TInputEvent = function(const Prompt: string; var Value: string): Boolean of object;
{ Forward declaration }
TQBasicInterpreter = class;
{ Lexer }
TQBasicLexer = class
private
FText: string;
FPos: Integer;
FLine: Integer;
FCol: Integer;
function CurrentChar: Char;
procedure Advance;
procedure SkipWhitespace;
function ReadNumber: string;
function ReadString: string;
function ReadIdent: string;
public
constructor Create(const AText: string);
function GetNextToken: TToken;
property Line: Integer read FLine;
property Col: Integer read FCol;
end;
{ Interpreter }
TQBasicInterpreter = class
private
FTokens: array of TToken;
FPos: Integer;
FVariables: array of TVariable;
FForStack: array of TForStackEntry;
FGosubStack: array of Integer;
FLabels: array of TLabelEntry;
FSubPrograms: array of TSubProgram;
FCallStack: array of TCallStackEntry;
FInSubProgram: Boolean;
FCurrentSubIdx: Integer;
FBuiltins: array of TBuiltinFunction;
FRunning: Boolean;
FStopRequested: Boolean;
FOnPrint: TPrintEvent;
FOnInput: TInputEvent;
function CurrentToken: TToken;
procedure Advance;
function Match(AType: TTokenType): Boolean;
procedure Expect(AType: TTokenType);
function PeekToken(Offset: Integer = 1): TToken;
function GetVariable(const AName: string): Integer;
function GetVariableValue(const AName: string): Double;
function GetVariableStrValue(const AName: string): string;
procedure SetVariable(const AName: string; AValue: Double; const AStrValue: string; AIsString: Boolean; ForceLocal: Boolean = False);
function EvaluateExpr: Double;
function EvaluateStrExpr: string;
function EvaluateTerm: Double;
function EvaluateUnary: Double;
function EvaluateFactor: Double;
function EvaluateComparison: Double;
function EvaluateLogical: Double;
function IsStringExpr: Boolean;
procedure ExecuteStatement;
procedure ExecutePRINT;
procedure ExecuteINPUT;
procedure ExecuteLET;
procedure ExecuteIF;
procedure ExecuteFOR;
procedure ExecuteNEXT;
procedure ExecuteWHILE;
procedure ExecuteWEND;
procedure ExecuteDO;
procedure ExecuteLOOP;
procedure ExecuteGOTO;
procedure ExecuteGOSUB;
procedure ExecuteRETURN;
procedure ExecuteDIM;
procedure ExecuteCALL;
procedure ExecuteSUB;
procedure ExecuteFUNCTION;
procedure ExecuteSELECT;
procedure ScanLabels;
procedure ScanSubPrograms;
function FindLabel(const ALabel: string): Integer;
function FindSubProgram(const AName: string): Integer;
function FindBuiltin(const AName: string): Integer;
function CallFunction(const AName: string): Double;
function CallStringFunction(const AName: string): string;
procedure CallBuiltinProc(const AName: string);
function BuiltinABS(const Args: array of Double): Double;
function BuiltinINT(const Args: array of Double): Double;
function BuiltinSGN(const Args: array of Double): Double;
function BuiltinSQR(const Args: array of Double): Double;
function BuiltinSIN(const Args: array of Double): Double;
function BuiltinCOS(const Args: array of Double): Double;
function BuiltinTAN(const Args: array of Double): Double;
function BuiltinATN(const Args: array of Double): Double;
function BuiltinLOG(const Args: array of Double): Double;
function BuiltinEXP(const Args: array of Double): Double;
function BuiltinRND(const Args: array of Double): Double;
function BuiltinLEN(const Args: array of Double): Double;
function BuiltinASC(const Args: array of Double): Double;
function BuiltinVAL(const Args: array of Double): Double;
function BuiltinMIN(const Args: array of Double): Double;
function BuiltinMAX(const Args: array of Double): Double;
function BuiltinCHR(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinSTR(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinLEFT(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinRIGHT(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinMID(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinUCASE(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinLCASE(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinLTRIM(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinRTRIM(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinSPACE(const Args: array of Double; const StrArgs: array of string): string;
function BuiltinSTRING(const Args: array of Double; const StrArgs: array of string): string;
procedure RegisterBuiltins;
public
constructor Create;
destructor Destroy; override;
procedure LoadProgram(const ACode: string);
procedure Execute;
procedure Stop;
procedure Reset;
{ Register custom functions }
procedure RegisterFunction(const AName: string; AMinArgs, AMaxArgs: Integer;
AFunc: TBuiltinFuncNum);
procedure RegisterStringFunction(const AName: string; AMinArgs, AMaxArgs: Integer;
AFunc: TBuiltinFuncStr);
procedure RegisterProcedure(const AName: string; AMinArgs, AMaxArgs: Integer;
AProc: TBuiltinProc);
{ Set/Get global variables from host }
procedure SetGlobalVariable(const AName: string; AValue: Double);
procedure SetGlobalStringVariable(const AName: string; const AValue: string);
function GetGlobalVariable(const AName: string): Double;
function GetGlobalStringVariable(const AName: string): string;
property OnPrint: TPrintEvent read FOnPrint write FOnPrint;
property OnInput: TInputEvent read FOnInput write FOnInput;
property Running: Boolean read FRunning;
end;
EQBasicError = class(Exception)
public
Line: Integer;
Col: Integer;
constructor Create(const AMsg: string; ALine, ACol: Integer);
end;
implementation
{ EQBasicError }
constructor EQBasicError.Create(const AMsg: string; ALine, ACol: Integer);
begin
inherited CreateFmt('Line %d, Col %d: %s', [ALine, ACol, AMsg]);
Line := ALine;
Col := ACol;
end;
{ TQBasicLexer }
constructor TQBasicLexer.Create(const AText: string);
begin
FText := AText + #0;
FPos := 1;
FLine := 1;
FCol := 1;
end;
function TQBasicLexer.CurrentChar: Char;
begin
if FPos <= Length(FText) then
Result := FText[FPos]
else
Result := #0;
end;
procedure TQBasicLexer.Advance;
begin
if CurrentChar = #10 then
begin
Inc(FLine);
FCol := 1;
end
else
Inc(FCol);
Inc(FPos);
end;
procedure TQBasicLexer.SkipWhitespace;
begin
while CurrentChar in [' ', #9] do
Advance;
end;
function TQBasicLexer.ReadNumber: string;
var
HasDot: Boolean;
begin
Result := '';
HasDot := False;
while CurrentChar in ['0'..'9', '.'] do
begin
if CurrentChar = '.' then
begin
if HasDot then Break;
HasDot := True;
end;
Result := Result + CurrentChar;
Advance;
end;
end;
function TQBasicLexer.ReadString: string;
begin
Result := '';
Advance; // Skip opening quote
while (CurrentChar <> '"') and (CurrentChar <> #0) and (CurrentChar <> #10) do
begin
Result := Result + CurrentChar;
Advance;
end;
if CurrentChar = '"' then
Advance;
end;
function TQBasicLexer.ReadIdent: string;
begin
Result := '';
while CurrentChar in ['A'..'Z', 'a'..'z', '0'..'9', '_', '$', '%', '!', '#', '&'] do
begin
Result := Result + UpCase(CurrentChar);
Advance;
end;
end;
function TQBasicLexer.GetNextToken: TToken;
var
Ident: string;
begin
SkipWhitespace;
Result.Line := FLine;
Result.Col := FCol;
Result.Value := '';
if CurrentChar = #0 then
begin
Result.TokenType := ttEOF;
Exit;
end;
if CurrentChar in [#10, #13] then
begin
while CurrentChar in [#10, #13] do
Advance;
Result.TokenType := ttEOL;
Exit;
end;
if CurrentChar = ':' then
begin
Advance;
Result.TokenType := ttColon;
Exit;
end;
// Handle single-quote comments
if CurrentChar = '''' then
begin
while not (CurrentChar in [#10, #13, #0]) do
Advance;
Result.TokenType := ttEOL;
Exit;
end;
if CurrentChar in ['0'..'9'] then
begin
Result.TokenType := ttNumber;
Result.Value := ReadNumber;
Exit;
end;
if CurrentChar = '.' then
begin
if (FPos + 1 <= Length(FText)) and (FText[FPos + 1] in ['0'..'9']) then
begin
Result.TokenType := ttNumber;
Result.Value := ReadNumber;
Exit;
end;
end;
if CurrentChar = '"' then
begin
Result.TokenType := ttString;
Result.Value := ReadString;
Exit;
end;
if CurrentChar in ['A'..'Z', 'a'..'z', '_'] then
begin
Ident := ReadIdent;
// Keywords
if Ident = 'PRINT' then Result.TokenType := ttPRINT
else if Ident = 'INPUT' then Result.TokenType := ttINPUT
else if Ident = 'LET' then Result.TokenType := ttLET
else if Ident = 'IF' then Result.TokenType := ttIF
else if Ident = 'THEN' then Result.TokenType := ttTHEN
else if Ident = 'ELSE' then Result.TokenType := ttELSE
else if Ident = 'ELSEIF' then Result.TokenType := ttELSEIF
else if Ident = 'END' then Result.TokenType := ttEND
else if Ident = 'FOR' then Result.TokenType := ttFOR
else if Ident = 'TO' then Result.TokenType := ttTO
else if Ident = 'STEP' then Result.TokenType := ttSTEP
else if Ident = 'NEXT' then Result.TokenType := ttNEXT
else if Ident = 'WHILE' then Result.TokenType := ttWHILE
else if Ident = 'WEND' then Result.TokenType := ttWEND
else if Ident = 'DO' then Result.TokenType := ttDO
else if Ident = 'LOOP' then Result.TokenType := ttLOOP
else if Ident = 'GOTO' then Result.TokenType := ttGOTO
else if Ident = 'GOSUB' then Result.TokenType := ttGOSUB
else if Ident = 'RETURN' then Result.TokenType := ttRETURN
else if Ident = 'DIM' then Result.TokenType := ttDIM
else if Ident = 'AS' then Result.TokenType := ttAS
else if Ident = 'INTEGER' then Result.TokenType := ttINTEGER
else if Ident = 'SINGLE' then Result.TokenType := ttSINGLE
else if Ident = 'DOUBLE' then Result.TokenType := ttDOUBLE
else if Ident = 'STRING' then Result.TokenType := ttSTRING_TYPE
else if Ident = 'REM' then Result.TokenType := ttREM
else if Ident = 'CLS' then Result.TokenType := ttCLS
else if Ident = 'LOCATE' then Result.TokenType := ttLOCATE
else if Ident = 'COLOR' then Result.TokenType := ttCOLOR
else if Ident = 'SCREEN' then Result.TokenType := ttSCREEN
else if Ident = 'AND' then Result.TokenType := ttAND
else if Ident = 'OR' then Result.TokenType := ttOR
else if Ident = 'NOT' then Result.TokenType := ttNOT
else if Ident = 'XOR' then Result.TokenType := ttXOR
else if Ident = 'MOD' then Result.TokenType := ttMod
else if Ident = 'SUB' then Result.TokenType := ttSUB
else if Ident = 'FUNCTION' then Result.TokenType := ttFUNCTION
else if Ident = 'EXIT' then Result.TokenType := ttEXIT
else if Ident = 'CALL' then Result.TokenType := ttCALL
else if Ident = 'STATIC' then Result.TokenType := ttSTATIC
else if Ident = 'SHARED' then Result.TokenType := ttSHARED
else if Ident = 'SELECT' then Result.TokenType := ttSELECT
else if Ident = 'CASE' then Result.TokenType := ttCASE
else if Ident = 'IS' then Result.TokenType := ttIS
else
begin
Result.TokenType := ttIdent;
Result.Value := Ident;
end;
Exit;
end;
case CurrentChar of
'+': begin Advance; Result.TokenType := ttPlus; end;
'-': begin Advance; Result.TokenType := ttMinus; end;
'*': begin Advance; Result.TokenType := ttMult; end;
'/': begin Advance; Result.TokenType := ttDiv; end;
'\': begin Advance; Result.TokenType := ttDiv; end; // Integer division
'^': begin Advance; Result.TokenType := ttPower; end;
'(': begin Advance; Result.TokenType := ttLParen; end;
')': begin Advance; Result.TokenType := ttRParen; end;
',': begin Advance; Result.TokenType := ttComma; end;
';': begin Advance; Result.TokenType := ttSemicolon; end;
'=': begin Advance; Result.TokenType := ttEQ; end;
'<':
begin
Advance;
if CurrentChar = '=' then
begin
Advance;
Result.TokenType := ttLE;
end
else if CurrentChar = '>' then
begin
Advance;
Result.TokenType := ttNE;
end
else
Result.TokenType := ttLT;
end;
'>':
begin
Advance;
if CurrentChar = '=' then
begin
Advance;
Result.TokenType := ttGE;
end
else
Result.TokenType := ttGT;
end;
else
Advance;
Result.TokenType := ttEOL; // Skip unknown characters
end;
end;
{ TQBasicInterpreter }
constructor TQBasicInterpreter.Create;
begin
inherited Create;
FPos := 0;
SetLength(FTokens, 0);
SetLength(FVariables, 0);
SetLength(FForStack, 0);
SetLength(FGosubStack, 0);
SetLength(FLabels, 0);
SetLength(FSubPrograms, 0);
SetLength(FCallStack, 0);
SetLength(FBuiltins, 0);
FInSubProgram := False;
FCurrentSubIdx := -1;
FRunning := False;
FStopRequested := False;
RegisterBuiltins;
end;
destructor TQBasicInterpreter.Destroy;
begin
Reset;
inherited Destroy;
end;
procedure TQBasicInterpreter.Reset;
begin
SetLength(FTokens, 0);
SetLength(FVariables, 0);
SetLength(FForStack, 0);
SetLength(FGosubStack, 0);
SetLength(FLabels, 0);
SetLength(FSubPrograms, 0);
SetLength(FCallStack, 0);
FPos := 0;
FInSubProgram := False;
FCurrentSubIdx := -1;
FRunning := False;
FStopRequested := False;
end;
procedure TQBasicInterpreter.LoadProgram(const ACode: string);
var
Lexer: TQBasicLexer;
Token: TToken;
begin
Reset;
Lexer := TQBasicLexer.Create(ACode);
try
repeat
Token := Lexer.GetNextToken;
SetLength(FTokens, Length(FTokens) + 1);
FTokens[High(FTokens)] := Token;
until Token.TokenType = ttEOF;
finally
Lexer.Free;
end;
ScanLabels;
ScanSubPrograms;
end;
function TQBasicInterpreter.CurrentToken: TToken;
begin
if FPos < Length(FTokens) then
Result := FTokens[FPos]
else
begin
Result.TokenType := ttEOF;
Result.Value := '';
Result.Line := 0;
Result.Col := 0;
end;
end;
function TQBasicInterpreter.PeekToken(Offset: Integer): TToken;
begin
if FPos + Offset < Length(FTokens) then
Result := FTokens[FPos + Offset]
else
begin
Result.TokenType := ttEOF;
Result.Value := '';
end;
end;
procedure TQBasicInterpreter.Advance;
begin
Inc(FPos);
end;
function TQBasicInterpreter.Match(AType: TTokenType): Boolean;
begin
Result := CurrentToken.TokenType = AType;
if Result then
Advance;
end;
procedure TQBasicInterpreter.Expect(AType: TTokenType);
begin
if not Match(AType) then
raise EQBasicError.Create(Format('Expected token type %d, got %d',
[Ord(AType), Ord(CurrentToken.TokenType)]),
CurrentToken.Line, CurrentToken.Col);
end;
function TQBasicInterpreter.GetVariable(const AName: string): Integer;
var
i: Integer;
begin
// Check local variables first
if FInSubProgram and (FCurrentSubIdx >= 0) then
begin
for i := 0 to High(FSubPrograms[FCurrentSubIdx].LocalVars) do
if FSubPrograms[FCurrentSubIdx].LocalVars[i].Name = AName then
Exit(-(i + 2)); // Use -2, -3, -4... to avoid conflict with -1 (not found)
end;
// Check global variables
for i := 0 to High(FVariables) do
if FVariables[i].Name = AName then
Exit(i);
Result := -1; // Not found
end;
function TQBasicInterpreter.GetVariableValue(const AName: string): Double;
var
Idx: Integer;
begin
Idx := GetVariable(AName);
if Idx >= 0 then
Result := FVariables[Idx].NumValue
else if Idx < -1 then
begin
Idx := -(Idx + 2); // Decode: -2 -> 0, -3 -> 1, etc.
Result := FSubPrograms[FCurrentSubIdx].LocalVars[Idx].NumValue;
end
else
Result := 0;
end;
function TQBasicInterpreter.GetVariableStrValue(const AName: string): string;
var
Idx: Integer;
begin
Idx := GetVariable(AName);
if Idx >= 0 then
Result := FVariables[Idx].StrValue
else if Idx < -1 then
begin
Idx := -(Idx + 2);
Result := FSubPrograms[FCurrentSubIdx].LocalVars[Idx].StrValue;
end
else
Result := '';
end;
procedure TQBasicInterpreter.SetVariable(const AName: string; AValue: Double;
const AStrValue: string; AIsString: Boolean; ForceLocal: Boolean = False);
var
Idx: Integer;
begin
Idx := GetVariable(AName);
// If ForceLocal and we're in a subprogram, always create/use local variable
if ForceLocal and FInSubProgram and (FCurrentSubIdx >= 0) then
begin
if Idx < -1 then
begin
// Local already exists, update it
Idx := -(Idx + 2);
with FSubPrograms[FCurrentSubIdx].LocalVars[Idx] do
begin
IsString := AIsString;
NumValue := AValue;
StrValue := AStrValue;
end;
end
else
begin
// Create new local (even if global exists)
SetLength(FSubPrograms[FCurrentSubIdx].LocalVars,
Length(FSubPrograms[FCurrentSubIdx].LocalVars) + 1);
Idx := High(FSubPrograms[FCurrentSubIdx].LocalVars);
with FSubPrograms[FCurrentSubIdx].LocalVars[Idx] do
begin
Name := AName;
IsString := AIsString;
NumValue := AValue;
StrValue := AStrValue;
end;
end;
Exit;
end;
if Idx < -1 then
begin
// Local variable
Idx := -(Idx + 2);
with FSubPrograms[FCurrentSubIdx].LocalVars[Idx] do
begin
IsString := AIsString;
NumValue := AValue;
StrValue := AStrValue;
end;
end
else if Idx >= 0 then
begin
// Existing global
FVariables[Idx].IsString := AIsString;
FVariables[Idx].NumValue := AValue;
FVariables[Idx].StrValue := AStrValue;
end
else
begin
// New variable
if FInSubProgram and (FCurrentSubIdx >= 0) then
begin
// Create local
SetLength(FSubPrograms[FCurrentSubIdx].LocalVars,
Length(FSubPrograms[FCurrentSubIdx].LocalVars) + 1);
Idx := High(FSubPrograms[FCurrentSubIdx].LocalVars);
with FSubPrograms[FCurrentSubIdx].LocalVars[Idx] do
begin
Name := AName;
IsString := AIsString;
NumValue := AValue;
StrValue := AStrValue;
end;
end
else
begin
// Create global
SetLength(FVariables, Length(FVariables) + 1);
Idx := High(FVariables);
FVariables[Idx].Name := AName;
FVariables[Idx].IsString := AIsString;
FVariables[Idx].NumValue := AValue;
FVariables[Idx].StrValue := AStrValue;
end;
end;
end;
procedure TQBasicInterpreter.SetGlobalVariable(const AName: string; AValue: Double);
var
i: Integer;
begin
for i := 0 to High(FVariables) do
if FVariables[i].Name = UpperCase(AName) then
begin
FVariables[i].NumValue := AValue;
FVariables[i].IsString := False;
Exit;
end;
SetLength(FVariables, Length(FVariables) + 1);
FVariables[High(FVariables)].Name := UpperCase(AName);
FVariables[High(FVariables)].NumValue := AValue;
FVariables[High(FVariables)].IsString := False;
end;
procedure TQBasicInterpreter.SetGlobalStringVariable(const AName: string; const AValue: string);
var
i: Integer;
begin
for i := 0 to High(FVariables) do
if FVariables[i].Name = UpperCase(AName) then
begin
FVariables[i].StrValue := AValue;
FVariables[i].IsString := True;
Exit;
end;
SetLength(FVariables, Length(FVariables) + 1);
FVariables[High(FVariables)].Name := UpperCase(AName);
FVariables[High(FVariables)].StrValue := AValue;
FVariables[High(FVariables)].IsString := True;
end;
function TQBasicInterpreter.GetGlobalVariable(const AName: string): Double;
var
i: Integer;
begin
for i := 0 to High(FVariables) do
if FVariables[i].Name = UpperCase(AName) then
Exit(FVariables[i].NumValue);
Result := 0;
end;
function TQBasicInterpreter.GetGlobalStringVariable(const AName: string): string;
var
i: Integer;
begin
for i := 0 to High(FVariables) do
if FVariables[i].Name = UpperCase(AName) then
Exit(FVariables[i].StrValue);
Result := '';
end;
function TQBasicInterpreter.IsStringExpr: Boolean;
var
VarIdx: Integer;
VarName: string;
begin
Result := False;
if CurrentToken.TokenType = ttString then
Result := True
else if CurrentToken.TokenType = ttIdent then
begin
VarName := CurrentToken.Value;
if (Length(VarName) > 0) and (VarName[Length(VarName)] = '$') then
Result := True
else
begin
VarIdx := GetVariable(VarName);
if VarIdx >= 0 then
Result := FVariables[VarIdx].IsString
else if VarIdx < -1 then
begin
VarIdx := -(VarIdx + 2);
Result := FSubPrograms[FCurrentSubIdx].LocalVars[VarIdx].IsString;
end;
end;
end;
end;
function TQBasicInterpreter.EvaluateFactor: Double;
var
VarName: string;
VarIdx: Integer;
BuiltinIdx: Integer;
begin
Result := 0;
if Match(ttNumber) then
Result := StrToFloatDef(FTokens[FPos - 1].Value, 0)
else if CurrentToken.TokenType = ttIdent then
begin
VarName := CurrentToken.Value;
// Check for function call
if PeekToken.TokenType = ttLParen then
begin
BuiltinIdx := FindBuiltin(VarName);
if BuiltinIdx >= 0 then
Result := CallFunction(VarName)
else if FindSubProgram(VarName) >= 0 then
Result := CallFunction(VarName)
else
begin
Advance;
Result := 0;
end;
end
else
begin
Advance;
VarIdx := GetVariable(VarName);
if VarIdx >= 0 then
Result := FVariables[VarIdx].NumValue
else if VarIdx < -1 then
begin
VarIdx := -(VarIdx + 2);
Result := FSubPrograms[FCurrentSubIdx].LocalVars[VarIdx].NumValue;
end;
end;
end
else if Match(ttLParen) then
begin
Result := EvaluateExpr;
Expect(ttRParen);
end
else if Match(ttString) then
Result := 0;
end;
function TQBasicInterpreter.EvaluateUnary: Double;
begin
if Match(ttMinus) then
Result := -EvaluateFactor
else if Match(ttPlus) then
Result := EvaluateFactor
else if Match(ttNOT) then
begin
if EvaluateFactor <> 0 then
Result := 0
else
Result := -1;
end
else
Result := EvaluateFactor;
end;
function TQBasicInterpreter.EvaluateTerm: Double;
var
Op: TTokenType;
begin
Result := EvaluateUnary;
while CurrentToken.TokenType in [ttMult, ttDiv, ttMod, ttPower] do
begin
Op := CurrentToken.TokenType;
Advance;
case Op of
ttMult: Result := Result * EvaluateUnary;
ttDiv:
begin
if EvaluateUnary <> 0 then
Result := Result / EvaluateUnary
else
raise EQBasicError.Create('Division by zero', CurrentToken.Line, CurrentToken.Col);
end;
ttMod: Result := Trunc(Result) mod Trunc(EvaluateUnary);
ttPower: Result := Power(Result, EvaluateUnary);
end;
end;
end;
function TQBasicInterpreter.EvaluateExpr: Double;
begin
Result := EvaluateTerm;
while CurrentToken.TokenType in [ttPlus, ttMinus] do
begin
if Match(ttPlus) then
Result := Result + EvaluateTerm
else if Match(ttMinus) then
Result := Result - EvaluateTerm;
end;
end;
function TQBasicInterpreter.EvaluateComparison: Double;
var
Left: Double;
Op: TTokenType;
begin
Left := EvaluateExpr;
if CurrentToken.TokenType in [ttEQ, ttNE, ttLT, ttLE, ttGT, ttGE] then
begin
Op := CurrentToken.TokenType;
Advance;
case Op of
ttEQ: if Abs(Left - EvaluateExpr) < 0.00001 then Result := -1 else Result := 0;
ttNE: if Abs(Left - EvaluateExpr) >= 0.00001 then Result := -1 else Result := 0;
ttLT: if Left < EvaluateExpr then Result := -1 else Result := 0;
ttLE: if Left <= EvaluateExpr then Result := -1 else Result := 0;
ttGT: if Left > EvaluateExpr then Result := -1 else Result := 0;
ttGE: if Left >= EvaluateExpr then Result := -1 else Result := 0;
else
Result := Left;
end;
end
else
Result := Left;
end;
function TQBasicInterpreter.EvaluateLogical: Double;
var
Left: Double;
begin
Left := EvaluateComparison;
while CurrentToken.TokenType in [ttAND, ttOR, ttXOR] do
begin
if Match(ttAND) then
Left := Trunc(Left) and Trunc(EvaluateComparison)
else if Match(ttOR) then
Left := Trunc(Left) or Trunc(EvaluateComparison)
else if Match(ttXOR) then
Left := Trunc(Left) xor Trunc(EvaluateComparison);
end;
Result := Left;
end;
function TQBasicInterpreter.EvaluateStrExpr: string;
var
VarName: string;
VarIdx: Integer;