-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInterpreter.pas
5762 lines (4827 loc) · 164 KB
/
Interpreter.pas
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
{==============================================================================}
{ Модуль : Interpreter.pas }
{ Разработчик : Денис Артёмов (denis.artyomov@gmail.com) }
{===============================================================================
Простой интерпретатор языка, похожего на паскаль.
Возможности языка:
* Динамическая типизация. Тип переменной задаётся автоматически в момент присваивания ей значения
* Поддержка типов Integer, Single, String
* Поддержка массивов любой размерности
* Поддержка процедур и функций в скрипте
* Поддержка вызова процедур и функций из вызываемого кода
* Поддержка внешних констант
* Поддержка внешних переменных
* Поддержка операторов для выражений: *, /, +, -, ^
* Поддержка целочисленных операторов: div, shl, mod, or, and xor
* Поддержка логических операторов: not, or, and, xor
* Поддержка операторов сравнения >, >=, <, <=, =, <>
* Поддержка операторв: := , for, while, if, repeat, break, continue, case, inc, dec
* Встроенные константы nil, true, false
Возможности отладчика:
* Пошаговое исполнение (в работе)
* Точки останова
* Просмотр значений переменных и аргументов ф-ции
* Просмотр стека вызовов
Примеры использования:
==== (1) ======================================================================
procedure Test1();
var
Int : TInterpreter;
begin
try
Int := TInterpreter.Create();
Int.CompileExpression('10+23/10+12');
Int.Execute();
WriteLn('result=', Int.Result.FloatValue);
finally
FreeAndNil(Int);
end;
end;
==== (2) ======================================================================
procedure Test2();
var
Int : TInterpreter;
a : TValueWrapper;
begin
try
Int := TInterpreter.Create();
a := Int.UserVariables.Add('a');
a.IntValue := 5;
Int.CompileScript('for i := 1 to 10 do Inc(a)');
Int.Execute();
WriteLn('a=', a.IntValue);
finally
FreeAndNil(Int);
end;
end;
===============================================================================}
// TODO: Eval
// TODO: Показывать место в коде, где произошла runtime-ошибка
// TODO: Улучшить дизасемблер кода виртуальной машины
// TODO: Юнит-тесты для отладчика
unit Interpreter;
interface
uses
Generics.Collections, SysUtils, Classes, Types;
type
// Целочисленный тип и тип с плавающей точкой
TIntType = Integer;
TFloatType = Single;
// fwd.
TParser = class;
TMemoryManager = class;
TScriptFunctions = class;
TStringValue = class;
TArrayValue = class;
// Исключения
TInterpreterException = class(Exception);
TRuntimeException = class(TInterpreterException);
TTypeCastException = class(TRuntimeException);
TZeroDivException = class(TRuntimeException);
TStackCorruptedException = class(TRuntimeException);
TDebbugerException = class(TRuntimeException);
TCantContinueException = class(TDebbugerException);
TBreakpointNotFoundException = class(TDebbugerException);
TCodeNotFoundForLineException = class(TDebbugerException);
TInternalInterpreterException = class(TInterpreterException);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TValueType - Возможные типы значений, которыми оперирует виртуальная машина }
TValueType = (
vtNil,
vtInt,
vtFloat,
vtBool,
vtString,
vtConstStr,
vtArray,
vtFunStackFrame
);
{ TValue - Значение, с которым оперирует виртуальная машина (для внутреннего использования) }
TValue = record
function ToString : String;
function ToInt : Integer; inline;
function ToFloat : TFloatType; inline;
function ToBool : Boolean; inline;
function GetChar(Index : Integer) : TValue; inline;
var
Typ : TValueType; // Тип
case byte of
0: ( Int : TIntType; ); // Целое значение
1: ( Float : TFloatType; ); // Значение с плавающей точкой
2: ( Bool : Boolean; ); // Булевое значение
3: ( Str : TStringValue; ); // Строка
4: ( Arr : TArrayValue; ); // Массив
5: ( CStr : PString ); // Строковая константа
6: ( SF : Integer ); // Фрейм стека ф-ции
end;
PValue = ^TValue;
TValueDynArray = array of TValue;
PValueDynArray = ^TValueDynArray;
TValueArray = array[0..65535] of TValue;
PValueArray = ^TValueArray;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TValueWrapper - Обёртка над TValue }
TValueWrapper = class
private
FValues : PValueDynArray;
FIndex : Integer;
FMM : TMemoryManager;
function GetValue() : TValue; inline;
function GetType() : TValueType; inline;
function ToStr() : String;
procedure SetString(const Value : String); inline;
function ToInt() : Integer; inline;
procedure SetInt(Value : Integer); inline;
function ToFloat() : Single; inline;
procedure SetFloat(Value : Single); inline;
function ToBool() : Boolean; inline;
procedure SetBool(Value : Boolean); inline;
function TypeIsNil() : Boolean; inline;
public
constructor Create(Values : PValueDynArray; Index : Integer; MM : TMemoryManager);
property ValueType : TValueType read GetType;
property Value : TValue read GetValue;
property IsNil : boolean read TypeIsNil;
procedure SetNil; inline;
property StrValue : string read ToStr write SetString;
property IntValue : Integer read ToInt write SetInt;
property FloatValue : Single read ToFloat write SetFloat;
property BoolValue : Boolean read ToBool write SetBool;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUserFunctionArgs - аргументы пользовательской функции }
TUserFunctionArgs = class
private
FItems : array of TValueWrapper;
FSize : Integer;
function GetItem(Index : Integer) : TValueWrapper; inline;
class procedure RaiseErrIndexExceedRange(Index, Size : Integer);
public
constructor Create();
destructor Destroy(); override;
procedure Clear();
function Add(Values : PValueDynArray; Index : Integer; MM : TMemoryManager) : TValueWrapper;
property Count : Integer read FSize;
property Items[Index : Integer] : TValueWrapper read GetItem; default;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TInterpreterFuncCallBack - Тип callback-функции для обработки вызова внешней функций }
TInterpreterFuncCallBack = reference to procedure(Context : Pointer; Args : TUserFunctionArgs; Ret : TValueWrapper);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUserFunction - Внешняя функция интерпретатора }
TUserFunction = class
private
FName : String;
FArgCount : Integer;
FContext : Pointer;
FCallback : TInterpreterFuncCallBack;
FIndex : Integer;
public
constructor Create(Index : Integer; const Name : String; ArgCount : Integer; Context : Pointer; Callback : TInterpreterFuncCallBack);
property Name : String read FName;
property ArgCount : Integer read FArgCount;
property Context : Pointer read FContext;
property Callback : TInterpreterFuncCallBack read FCallback;
property Index : Integer read FIndex;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUserFunctions - Список внешних функций интерпретатора }
TUserFunctions = class
private
FItems : TObjectList<TUserFunction>;
function GetCount() : Integer; inline;
function GetItem(Index : Integer) : TUserFunction; inline;
procedure RegisterStd();
public
constructor Create();
destructor Destroy(); override;
procedure Clear();
function Add(
const Name : String;
ArgCount : Integer;
Context : Pointer;
Callback : TInterpreterFuncCallBack
) : Integer;
function FindByName(const Name : String) : TUserFunction;
function IndexByName(const Name : String) : Integer;
property Count : Integer read GetCount;
property Items[Index : Integer] : TUserFunction read GetItem; default;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUserVariables - Пользовательские переменные }
TUserVariables = class
private
FValuesArray : PValueDynArray;
FVarNames : TStringList;
FMM : TMemoryManager;
public
constructor Create(ValuesArray : PValueDynArray; MM : TMemoryManager);
destructor Destroy(); Override;
procedure Clear();
function Add(const Name : string) : TValueWrapper;
function GetIndex(const Name : string) : Integer;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUserConsts - Пользовательские константы }
TUserConsts = class
private
FIntItems : TDictionary<String, Integer>;
FSingleItems : TDictionary<String, Single>;
FStrItems : TDictionary<String, String>;
public
constructor Create();
destructor Destroy(); override;
procedure Clear();
procedure AddStr(const Name, Value : String);
procedure AddInt(const Name : String; Value : Integer);
procedure AddSingle(const Name : String; Value : Single);
function GetStr(const Name : String) : String;
function GetInt(const Name : String) : Integer;
function GetSingle(const Name : String) : Single;
function GetConstType(const Name : String) : TValueType;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TTokenFlag - Возможные флаги токена }
TTokenFlag = (
ltStatementWord,
ltStatementSubWord,
ltExprContent,
ltExprOperator,
ltConst,
ltName,
ltSeq,
ltStatement,
ltEndOfText
);
TTokenFlags = set of TTokenFlag;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ Тип токена }
TTokenType = (
ttUnknown, ttSeq, ttIntConst, ttFloatConst, ttBoolConst,
ttStrConst, ttName, ttSqOpBracket, ttSqClBracket,
ttAssig, ttProcedure, ttFunction, ttBoolean, ttMult, ttDiv,
ttTrue, ttFalse, ttBegin, ttEnd, ttExit, ttFor,
ttWhile, ttIf, ttRepeat, ttBreak, ttCont, ttCase,
ttInc, ttDec, ttDo, ttTo, ttDownto, ttThen,
ttElse, ttUntil, ttTry, ttFinally,
ttOf, ttIDiv, ttMod, ttNot,
ttOr, ttAnd, ttXor, ttNil, ttComma, ttPower,
ttPlus, ttMinus, ttLess, ttLessEq, ttGreater, ttGreaterEq,
ttEquals, ttNotEq, ttClBracket, ttOpBracket, ttSemi, ttColon,
ttShl, ttShr, ttDot, ttEOF
);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TToken - один токен скрипта }
TToken = class
private
FType : TTokenType;
FIntConst : Integer;
FFloatConst : Single;
FBoolConst : Boolean;
FCol : Integer;
FLine : Integer;
FText : string;
FFlags : TTokenFlags;
procedure Init(Flags : TTokenFlags; Col, Line : Integer; TType : TTokenType);
public
constructor Create(const Text : string; Flags : TTokenFlags; Col, Line : Integer; TType : TTokenType = ttUnknown);
constructor CreateInt(Value : Integer; Col : Integer = -1; Line : Integer = -1);
constructor CreateFloat(Value : Single; Col : Integer = -1; Line : Integer = -1);
constructor CreateBool(Value : Boolean; Col : Integer = -1; Line : Integer = -1);
constructor CreateStr(const Text : String; Col : Integer = -1; Line : Integer = -1);
property TokenType : TTokenType read FType;
property Line : Integer read FLine;
property Col : Integer read FCol;
property Text : string read FText;
property Flags : TTokenFlags read FFlags;
property IntValue : Integer read FIntConst;
property FloatValue : Single read FFloatConst;
property BoolValue : Boolean read FBoolConst;
property StrValue : String read FText;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TTokenCursor - текущая позиция разбора на токены }
TTokenCursor = record
Pos : Integer;
Col : Integer;
Line : Integer;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TTokenizerException - исключение при разбиении на токены }
TTokenizerException = class(TInterpreterException)
private
FCol : Integer;
FLine : Integer;
public
constructor CreateFmt(const Text : String; const Args: array of const; Col, Line : Integer);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TTokenizer - класс для разбиения текста на токены }
TTokenizer = class
private
FItems : TObjectList<TToken>;
FPos : Integer;
FTokTypesByName : TDictionary<String, TTokenType>;
function AddToken(const Text : string; Col, Line : Integer; lc : boolean; Flags : TTokenFlags = []; TokenType : TTokenType = ttUnknown) : TToken;
function GetTokenFlags(TokenType : TTokenType) : TTokenFlags;
function GetItem(Index : Integer) : TToken; inline;
function GetCount() : Integer; inline;
function SkipSingleComment(const Text : string; const Cur : TTokenCursor; Len : Integer) : TTokenCursor;
function SkipMultiComment (const Text : string; const Cur : TTokenCursor; Len : Integer; Dbl : Boolean) : TTokenCursor;
function TockenizeName (const Text : string; const Cur : TTokenCursor; Len : Integer) : TTokenCursor;
function TockenizeValue (const Text : string; const Cur : TTokenCursor; Len : Integer) : TTokenCursor;
function TockenizeComplSym(const Text : string; const Cur : TTokenCursor; Len : Integer) : TTokenCursor;
function TockenizeString (const Text : string; const Cur : TTokenCursor; Len : Integer) : TTokenCursor;
function GetTypeByText(const Name : String) : TTokenType;
function GetTokenStrByType(TT : TTokenType) : string;
function GetTokenStrByTypes(const TTs : array of TTokenType) : string;
public
constructor Create();
destructor Destroy(); override;
procedure Start();
function Get(ExceptIfEnd : Boolean) : TToken;
procedure Next();
function Expect(TokenType : TTokenType) : TToken;
function ExpectAnyOf(const TokenTypes : array of TTokenType) : TToken;
procedure Tockenize(const Text : string; Consts : TUserConsts);
function EOF : Boolean; inline;
property Pos : Integer read FPos;
property Items[Index : Integer] : TToken read GetItem; default;
property Count : Integer read GetCount;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TASTNode - узел AST-дерева }
TASTNode = class
private
FItems : TList<TASTNode>;
FToken : TToken;
FParent : TASTNode;
FOwnerOfToken : Boolean;
FParser : TParser;
function GetCount() : Integer; inline;
function GetItem(Index : Integer) : TASTNode; inline;
procedure SetItem(Index : Integer; Item : TASTNode); inline;
protected
function GetEnumerable: TEnumerable<TASTNode>;
public
constructor CreateSpecial(Parser : TParser; Parent : TASTNode; TokenType : TTokenType; const Text : string); overload;
constructor CreateSpecial(Parser : TParser; Parent : TASTNode; TokenType : TTokenType; const Text : string; Arg1 : TASTNode); overload;
constructor CreateSpecial(Parser : TParser; Parent : TASTNode; TokenType : TTokenType; const Text : string; Arg1, Arg2 : TASTNode); overload;
constructor Create(Parser : TParser; Tocken : TToken; Parent : TASTNode); overload;
constructor Create(Parser : TParser; Tocken : TToken; Parent : TASTNode; OwnerOfToken : Boolean); overload;
constructor Create(Parser : TParser; Tocken : TToken; Parent : TASTNode; Arg1 : TASTNode); overload;
constructor Create(Parser : TParser; Tocken : TToken; Parent : TASTNode; Arg1, Arg2 : TASTNode); overload;
destructor Destroy(); override;
property Items : TEnumerable<TASTNode> read GetEnumerable;
property Count : Integer read GetCount;
property Childs[Index : Integer] : TASTNode read GetItem write SetItem; default;
property Parser : TParser read FParser;
property Token : TToken read FToken;
property Parent : TASTNode read FParent;
procedure Add(Item : TASTNode);
function UniqStr() : string;
procedure Swap(OtherAST : TASTNode);
function IsArrayExpr() : Boolean;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TScriptFunction - процедура или функция скрипта }
TScriptFunction = class
private
FTopNode : TASTNode;
FBodyNode : TASTNode;
FName : String;
FArgList : TStringList;
FVars : TStringList;
FIsFunction : Boolean;
procedure ReadFuncInfo();
function GetArgByIndex(Index : Integer) : String;
function GetVarByIndex(Index : Integer) : String;
public
constructor Create(Node : TASTNode; IsFunction : Boolean);
destructor Destroy(); override;
procedure FindLocalVariables(
UserVars : TUserVariables;
UserFuncs : TUserFunctions;
UserConsts : TUserConsts;
ScriptFuncs : TScriptFunctions
);
property BodyAST : TASTNode read FBodyNode;
property Name : String read FName;
property IsFunction : Boolean read FIsFunction;
function VariablesCount : Integer;
function VarIndex(const VarName : string) : Integer;
property Vars[Index : Integer] : String read GetVarByIndex;
function ArgsCount : Integer;
function ArgIndex(const ArgName : string) : Integer;
property Args[Index : Integer] : String read GetArgByIndex;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TScriptFunctions - список объявленных функций в скрипте }
TScriptFunctions = class
private
FItems : TObjectList<TScriptFunction>;
function GetCount() : Integer; inline;
function GetItem(Index : Integer) : TScriptFunction; inline;
public
constructor Create();
destructor Destroy(); override;
procedure Clear();
procedure Add(Func : TScriptFunction);
function FindByName(const Name : String) : TScriptFunction;
property Count : Integer read GetCount;
property Items[Index : Integer] : TScriptFunction read GetItem; default;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TParserException - Исключение при парсинге текста }
TParserException = class(TInterpreterException)
private
FToken : TToken;
public
constructor Create(Token : TToken; const Text : String);
constructor CreateFmt(Token : TToken; const Text : String; const Args: array of const);
destructor Destroy(); override;
property Token : TToken read FToken;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TPasrser - парсер скриптов и выражений }
TParser = class
private
FAllAstNodes : TObjectList<TASTNode>;
function ParseExprSeq(Parent : TASTNode; Tokens : TTokenizer; DelimTT, EndTT : TTokenType) : TToken;
function ParseExpr(Tokens : TTokenizer; LastOperPriority : Integer; CanBeNull : Boolean) : TASTNode;
function ParseStatement(Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseStatements(Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
procedure ParseProcedureArgsDecl(Func : TASTNode; Tokens : TTokenizer);
function ParseProcedureDecl(Tokens : TTokenizer) : TASTNode;
function ParseName(NameToken : TToken; Tokens : TTokenizer) : TASTNode;
function ParseWhile(WhileToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseIf(IfToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseFor(ForToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseRepeat(RepeatToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseIncDec(Token : TToken; Tokens : TTokenizer) : TASTNode;
function ParseCase(CaseToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseCaseItem(Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function ParseTryFinally(TryToken : TToken; Parent : TASTNode; Tokens : TTokenizer) : TASTNode;
function GetOperPrioryty(Token : TToken) : Integer;
public
constructor Create();
destructor Destroy(); override;
procedure ParseScript(Tokens : TTokenizer; Functions : TScriptFunctions);
procedure ParseExpression(Tokens : TTokenizer; Expression : TASTNode);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ Инструкции виртуальной машины }
TCodeInstr = (
ciPushInt,
ciPushFloat,
ciPushBool,
ciPushStr,
ciPushNil,
ciPushLocalValue,
ciPushGlobalValue,
ciPushLocalArray,
ciPushGlobalArray,
ciPushAcc,
ciPopLocalValue,
ciPopGlobalValue,
ciPopLocalArray,
ciPopGlobalArray,
ciPopAcc,
ciFunFrameBegin,
ciFunFrameEnd,
ciDecrStack,
ciAdd,
ciSub,
ciMult,
ciDiv,
ciIDiv,
ciMod,
ciShl,
ciShr,
ciPower,
ciOr,
ciAnd,
ciXor,
ciEqual,
ciLess,
ciLessEq,
ciGreater,
ciGreaterEq,
ciNot,
ciNeg,
ciJmp,
ciJmpIf,
ciJmpIfNot,
ciReturn,
ciCall,
ciUserFunc,
ciExit,
ciBreakpoint
);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TBinaryCodeItem - Одна инструкция }
TBinaryCodeItem = record
case byte of
0: (Instr : TCodeInstr);
1: (Int : Integer);
2: (Float : Single);
3: (Bool : Boolean);
end;
PBinaryCodeItem = ^TBinaryCodeItem;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TSrcPos - Позиция исполняемой инструкции в коде.
Используется для определения места, где произошла ошибка }
TSrcPos = record
Col : Integer;
Line : Integer;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TBreakpoint - точка останова }
TBreakpoint = record
LineNum : Integer;
Instr : TCodeInstr;
CodePos : Integer;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TFunDebugInfo - хранение отладочной инфы для одной ф-ции }
TFunDebugInfo = class
private
FFunName : String;
FArgs : TStrings;
FVars : TStrings;
public
constructor Create(ScriptFun : TScriptFunction);
destructor Destroy(); override;
property FunName : String read FFunName;
property Args : TStrings read FArgs;
property Vars : TStrings read FVars;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TDebugInfo - отладочная информация }
TDebugInfo = class
private
FSrcPositions : TDictionary<Integer,TSrcPos>;
FFunDebugItems : TObjectList<TFunDebugInfo>;
public
constructor Create();
destructor Destroy(); override;
procedure Clear();
function AddFunDebugInfo(ScriptFun : TScriptFunction) : Integer;
procedure AddSrcPos(CodePos : Integer; SrcPos : TSrcPos);
function GetFunDebugItem(FunIndex : Integer) : TFunDebugInfo;
function GetCodePosBySrcLine(LineNum : Integer) : Integer;
function GetSrcPosByAddr(Addr : Integer) : TSrcPos;
procedure ToStrings(Text : TStrings);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TBinaryCode - Бинарный код, выполняемый виртуальной машиной }
TBinaryCode = class
private
FCode : TList<TBinaryCodeItem>;
FStrings : TList<PString>;
FBreakpoins : TList<TBreakpoint>;
FChachedCodeBegin : PBinaryCodeItem;
FCachedCodeArr : TArray<TBinaryCodeItem>;
procedure CreateCachedCodeArr();
procedure DisassembleCode(Text : TStrings; DebugInfo : TDebugInfo);
procedure DisassembleStrings(Text : TStrings);
public
constructor Create();
destructor Destroy(); override;
function Size : Integer;
procedure Clear();
procedure AddInstr(Instr : TCodeInstr; Token : TToken; DebugInfo : TDebugInfo);
procedure AddInteger(Value : Integer);
procedure AddFloat(Value : Single);
procedure AddBool(Value : Boolean);
function AddStr(const Str : String) : Integer;
procedure SetInteger(Pos, Value : Integer);
function GetInstrBegin : PBinaryCodeItem; inline;
function GetString(Index : Integer) : PString; inline;
procedure AddBreakPoint(LineNum : Integer; DebugInfo : TDebugInfo);
procedure RemoveBreakpoint(LineNum : Integer; DebugInfo : TDebugInfo);
function GetBreakPointIndexByLineNum(LineNum : Integer) : Integer;
function GetBreakPointIndexByCodePos(CodePos : Integer) : Integer;
procedure RevertInstructionForBreakpoint(CodePos : Integer);
procedure SetInstructionsForAllBreakpoints();
procedure Disassemble(DestText : TStrings; DebugInfo : TDebugInfo);
procedure SaveToStream(Stream : TStream);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TCodeGenerator - Генератор бинарного кода для выполнения }
TCodeGenerator = class
private
FDebugInfo : TDebugInfo;
FForVariables : TStringList;
FScriptFuncs : TScriptFunctions;
FUserFunctions : TUserFunctions;
FUserConsts : TUserConsts;
FCode : TBinaryCode;
FLabels : TDictionary<String, Integer>;
FLabelsUse : TDictionary<Integer, String>;
FUserVars : TUserVariables;
FWasOptimized : Boolean;
procedure Expr(Func : TScriptFunction; Ast : TASTNode);
procedure NameExpr(Func : TScriptFunction; Ast : TASTNode);
procedure ArrExpr(Func : TScriptFunction; Ast : TASTNode; VarIndex : Integer; VarIsGlobal : Boolean);
procedure SomeFuncCall(Func : TScriptFunction; Ast : TASTNode);
procedure UserFuncCall(Func : TScriptFunction; Ast : TASTNode; UserFuncIndex : Integer);
procedure ScriptFuncCall(Func : TScriptFunction; Ast : TASTNode; ScriptFunc : TScriptFunction);
procedure BinOperExpr(Func : TScriptFunction; Ast : TASTNode);
procedure UnOperExpr(Func : TScriptFunction; Ast : TASTNode);
procedure ConstExpr(Ast : TASTNode);
procedure Fun(Func : TScriptFunction; UserConsts : TUserConsts; AddReturn : Boolean);
procedure Statement(Func : TScriptFunction; Ast : TASTNode);
procedure StAssign(Func : TScriptFunction; Ast : TASTNode);
procedure AssignPop(Func : TScriptFunction; Ast : TASTNode);
procedure AssignPopArrItem(Func : TScriptFunction; Ast : TASTNode; VarIndex : Integer; VarIsGlobal : Boolean);
procedure IncDec(Func : TScriptFunction; StAst : TASTNode; D : boolean); overload;
procedure IncDec(Func : TScriptFunction; NameAst, ValueAst : TASTNode; D : boolean); overload;
procedure StWhile(Func : TScriptFunction; Ast : TASTNode);
procedure StIf(Func : TScriptFunction; Ast : TASTNode);
procedure StFor(Func : TScriptFunction; Ast : TASTNode);
procedure StRepeat(Func : TScriptFunction; Ast : TASTNode);
procedure StBreakCont(Func : TScriptFunction; Ast : TASTNode; const Prefix : string);
procedure StExit(Func : TScriptFunction; Ast : TASTNode);
procedure StCase(Func : TScriptFunction; Ast : TASTNode);
procedure StTryFinally(Func : TScriptFunction; Ast : TASTNode);
procedure SubstituteConsts(var RootAst : TAstNode);
procedure OptimizeConsts(var RootAst : TAstNode);
procedure FoldConst(var AST : TASTNode);
procedure AddLabel(Ast : TASTNode; const Prefix : String); overload;
procedure AddLabel(const Name : String); overload;
procedure AddLabelPos(const Name : String);
procedure AddString(const Str : String);
function GetLabelPos(const Name : String) : Integer;
procedure FillLabelPositions();
public
constructor Create();
destructor Destroy(); override;
procedure GenerateFunctions(
Functions : TScriptFunctions;
UserFunctions : TUserFunctions;
UserVars : TUserVariables;
UserConsts : TUserConsts;
DebugInfo : TDebugInfo;
Code : TBinaryCode
);
procedure GenerateExpression(
Ast : TASTNode;
UserFunctions : TUserFunctions;
UserVars : TUserVariables;
UserConsts : TUserConsts;
DebugInfo : TDebugInfo;
Code : TBinaryCode
);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TBinOperException - исключение при выполнении бинарной операции }
TBinOperException = class(TRuntimeException)
public
constructor Create(const Value1, Value2 : TValue; const Oper : string);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TUnaryOperException - исключение при выполнении унарной операции }
TUnaryOperException = class(TRuntimeException)
public
constructor Create(const Value : TValue; const Oper : string);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TWrongTypeException - Исключении при использовании операнда недопустимого для опеарции типа }
TWrongTypeException = class(TRuntimeException)
public
constructor Create(const Value : TValue; const ExpectedType : string); overload;
constructor Create(const Value : TValueWrapper; const ExpectedType : string); overload;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TMemoryManagerObject - базовый объект менеджера памяти }
TMemoryManagerObject = class
private
FUsed : Boolean;
public
property Used : Boolean read FUsed write FUsed;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TStringValue - объект менеджера памяти - СТРОКА }
TStringValue = class(TMemoryManagerObject)
private
FString : String;
public
function GetPStr() : PString;
property Value : String read FString write FString;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TVisitAllValuesProc = reference to procedure (const Value : TValue);
{ TArrayValue - объект менеджера памяти - МАССИВ }
TArrayValue = class(TMemoryManagerObject)
private
FMultiItems : TDictionary<TIntegerDynArray, TValue>;
FItems : TDictionary<Integer, TValue>;
public
constructor Create();
destructor Destroy; override;
function GetValue_MultiDim(const Args : TIntegerDynArray; out Value : TValue) : Boolean; inline;
procedure PutValue_MultiDim(const Args : TIntegerDynArray; const Value : TValue); inline;
function GetValue_OneDim(Index : Integer; out Value : TValue) : Boolean; inline;
procedure PutValue_OneDim(Index : Integer; const Value : TValue); inline;
procedure Clear();
procedure ForEach(Proc : TVisitAllValuesProc);
function Count : Integer;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TMemoryManager - менеджер памяти. Создаёт объекты, производит сбоку мусора }
TMemoryManager = class
private
FObjects : TObjectList<TMemoryManagerObject>;
FAllocCounter : Integer;
class procedure MarkObjectAsUsed(const Value : TValue);
procedure TryToCollectGarbage(Stack : PValueDynArray; StkEnd : PValue; GlobalVars : PValueDynArray);
public
constructor Create();
destructor Destroy(); override;
function GetString(Stack : PValueDynArray; StkEnd : PValue; GlobalVars : PValueDynArray) : TStringValue;
function GetArray() : TArrayValue;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TCallStackVariable - одна переменная стека вызовов }
TCallStackVariable = class
private
FValueWrapper : TValueWrapper;
FName : String;
public
constructor Create(const Name : String; Values : PValueDynArray; ValueIndex : Integer; MM : TMemoryManager);
destructor Destroy(); override;
property Name : String read FName;
property ValueWrapper : TValueWrapper read FValueWrapper;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TCallStackVariables - набор переменных или аргументов элемента стека вызовов }
TCallStackVariables = class
private
FValues : TValueDynArray;
FWrappers : TObjectList<TCallStackVariable>;
function GetCount : Integer;
function GetItem(Index : Integer) : TCallStackVariable;
public
constructor Create(Names : TStrings; Values : TValueDynArray; MM : TMemoryManager);
destructor Destroy(); override;
property Count : Integer read GetCount;
property Items[Index : Integer] : TCallStackVariable read GetItem; default;
function GetEnumerator() : TList<TCallStackVariable>.TEnumerator;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TCallStackItem - один элемент стека вызовов }
TCallStackItem = class
private
FFun : TFunDebugInfo;
FArgs : TCallStackVariables;
FVars : TCallStackVariables;
public
constructor Create(Fun : TFunDebugInfo; Args : TValueDynArray; Vars : TValueDynArray; MM : TMemoryManager);
destructor Destroy(); override;
property Fun : TFunDebugInfo read FFun;