-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathinterpreter.ts
1642 lines (1531 loc) · 57.2 KB
/
interpreter.ts
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
import { Address, beginCell, BitString, Cell, Slice, toNano } from "@ton/core";
import { paddedBufferToBits } from "@ton/core/dist/boc/utils/paddedBits";
import * as crc32 from "crc-32";
import { evalConstantExpression } from "./constEval";
import { CompilerContext } from "./context";
import {
TactCompilationError,
TactConstEvalError,
idTextErr,
throwConstEvalError,
throwInternalCompilerError,
} from "./errors";
import {
AstBinaryOperation,
AstBoolean,
AstCondition,
AstConditional,
AstConstantDef,
AstContract,
AstExpression,
AstFieldAccess,
AstFunctionDef,
AstId,
AstInitOf,
AstMessageDecl,
AstMethodCall,
AstModuleItem,
AstNativeFunctionDecl,
AstNull,
AstNumber,
AstOpBinary,
AstOpUnary,
AstPrimitiveTypeDecl,
FactoryAst,
AstStatement,
AstStatementAssign,
AstStatementAugmentedAssign,
AstStatementDestruct,
AstStatementExpression,
AstStatementForEach,
AstStatementLet,
AstStatementRepeat,
AstStatementReturn,
AstStatementTry,
AstStatementTryCatch,
AstStatementUntil,
AstStatementWhile,
AstStaticCall,
AstString,
AstStructDecl,
AstStructInstance,
AstTrait,
AstUnaryOperation,
eqNames,
getAstFactory,
idText,
isSelfId,
} from "./grammar/ast";
import { SrcInfo, dummySrcInfo, Parser, getParser } from "./grammar";
import { divFloor, modFloor } from "./optimizer/util";
import {
getStaticConstant,
getStaticFunction,
getType,
hasStaticConstant,
hasStaticFunction,
} from "./types/resolveDescriptors";
import { getExpType } from "./types/resolveExpression";
import {
CommentValue,
StructValue,
TypeRef,
Value,
showValue,
} from "./types/types";
import { sha256_sync } from "@ton/crypto";
import { defaultParser } from "./grammar/grammar";
// TVM integers are signed 257-bit integers
const minTvmInt: bigint = -(2n ** 256n);
const maxTvmInt: bigint = 2n ** 256n - 1n;
// Range allowed in repeat statements
const minRepeatStatement: bigint = -(2n ** 256n); // Note it is the same as minimum for TVM
const maxRepeatStatement: bigint = 2n ** 31n - 1n;
// Throws a non-fatal const-eval error, in the sense that const-eval as a compiler
// optimization cannot be applied, e.g. to `let`-statements.
// Note that for const initializers this is a show-stopper.
export function throwNonFatalErrorConstEval(
msg: string,
source: SrcInfo,
): never {
throwConstEvalError(
`Cannot evaluate expression to a constant: ${msg}`,
false,
source,
);
}
// Throws a fatal const-eval, meaning this is a meaningless program,
// so compilation should be aborted in all cases
function throwErrorConstEval(msg: string, source: SrcInfo): never {
throwConstEvalError(
`Cannot evaluate expression to a constant: ${msg}`,
true,
source,
);
}
type EvalResult =
| { kind: "ok"; value: Value }
| { kind: "error"; message: string };
export function ensureInt(val: Value, source: SrcInfo): bigint {
if (typeof val !== "bigint") {
throwErrorConstEval(
`integer expected, but got '${showValue(val)}'`,
source,
);
}
if (minTvmInt <= val && val <= maxTvmInt) {
return val;
} else {
throwErrorConstEval(
`integer '${showValue(val)}' does not fit into TVM Int type`,
source,
);
}
}
function ensureRepeatInt(val: Value, source: SrcInfo): bigint {
if (typeof val !== "bigint") {
throwErrorConstEval(
`integer expected, but got '${showValue(val)}'`,
source,
);
}
if (minRepeatStatement <= val && val <= maxRepeatStatement) {
return val;
} else {
throwErrorConstEval(
`repeat argument must be a number between -2^256 (inclusive) and 2^31 - 1 (inclusive)`,
source,
);
}
}
function ensureBoolean(val: Value, source: SrcInfo): boolean {
if (typeof val !== "boolean") {
throwErrorConstEval(
`boolean expected, but got '${showValue(val)}'`,
source,
);
}
return val;
}
function ensureString(val: Value, source: SrcInfo): string {
if (typeof val !== "string") {
throwErrorConstEval(
`string expected, but got '${showValue(val)}'`,
source,
);
}
return val;
}
function ensureFunArity(arity: number, args: AstExpression[], source: SrcInfo) {
if (args.length !== arity) {
throwErrorConstEval(
`function expects ${arity} argument(s), but got ${args.length}`,
source,
);
}
}
function ensureMethodArity(
arity: number,
args: AstExpression[],
source: SrcInfo,
) {
if (args.length !== arity) {
throwErrorConstEval(
`method expects ${arity} argument(s), but got ${args.length}`,
source,
);
}
}
export function evalUnaryOp(
op: AstUnaryOperation,
valOperand: Value,
operandLoc: SrcInfo = dummySrcInfo,
source: SrcInfo = dummySrcInfo,
): Value {
switch (op) {
case "+":
return ensureInt(valOperand, operandLoc);
case "-":
return ensureInt(-ensureInt(valOperand, operandLoc), source);
case "~":
return ~ensureInt(valOperand, operandLoc);
case "!":
return !ensureBoolean(valOperand, operandLoc);
case "!!":
if (valOperand === null) {
throwErrorConstEval(
"non-null value expected but got null",
operandLoc,
);
}
return valOperand;
}
}
export function evalBinaryOp(
op: AstBinaryOperation,
valLeft: Value,
valRightContinuation: () => Value, // It needs to be a continuation, because some binary operators short-circuit
locLeft: SrcInfo = dummySrcInfo,
locRight: SrcInfo = dummySrcInfo,
source: SrcInfo = dummySrcInfo,
): Value {
switch (op) {
case "+":
return ensureInt(
ensureInt(valLeft, locLeft) +
ensureInt(valRightContinuation(), locRight),
source,
);
case "-":
return ensureInt(
ensureInt(valLeft, locLeft) -
ensureInt(valRightContinuation(), locRight),
source,
);
case "*":
return ensureInt(
ensureInt(valLeft, locLeft) *
ensureInt(valRightContinuation(), locRight),
source,
);
case "/": {
// The semantics of integer division for TVM (and by extension in Tact)
// is a non-conventional one: by default it rounds towards negative infinity,
// meaning, for instance, -1 / 5 = -1 and not zero, as in many mainstream languages.
// Still, the following holds: a / b * b + a % b == a, for all b != 0.
const r = ensureInt(valRightContinuation(), locRight);
if (r === 0n)
throwErrorConstEval(
"divisor expression must be non-zero",
locRight,
);
return ensureInt(divFloor(ensureInt(valLeft, locLeft), r), source);
}
case "%": {
// Same as for division, see the comment above
// Example: -1 % 5 = 4
const r = ensureInt(valRightContinuation(), locRight);
if (r === 0n)
throwErrorConstEval(
"divisor expression must be non-zero",
locRight,
);
return ensureInt(modFloor(ensureInt(valLeft, locLeft), r), source);
}
case "&":
return (
ensureInt(valLeft, locLeft) &
ensureInt(valRightContinuation(), locRight)
);
case "|":
return (
ensureInt(valLeft, locLeft) |
ensureInt(valRightContinuation(), locRight)
);
case "^":
return (
ensureInt(valLeft, locLeft) ^
ensureInt(valRightContinuation(), locRight)
);
case "<<": {
const valNum = ensureInt(valLeft, locLeft);
const valBits = ensureInt(valRightContinuation(), locRight);
if (0n > valBits || valBits > 256n) {
throwErrorConstEval(
`the number of bits shifted ('${valBits}') must be within [0..256] range`,
locRight,
);
}
try {
return ensureInt(valNum << valBits, source);
} catch (e) {
if (e instanceof RangeError)
// this actually should not happen
throwErrorConstEval(
`integer does not fit into TVM Int type`,
source,
);
throw e;
}
}
case ">>": {
const valNum = ensureInt(valLeft, locLeft);
const valBits = ensureInt(valRightContinuation(), locRight);
if (0n > valBits || valBits > 256n) {
throwErrorConstEval(
`the number of bits shifted ('${valBits}') must be within [0..256] range`,
locRight,
);
}
try {
return ensureInt(valNum >> valBits, source);
} catch (e) {
if (e instanceof RangeError)
// this is actually should not happen
throwErrorConstEval(
`integer does not fit into TVM Int type`,
source,
);
throw e;
}
}
case ">":
return (
ensureInt(valLeft, locLeft) >
ensureInt(valRightContinuation(), locRight)
);
case "<":
return (
ensureInt(valLeft, locLeft) <
ensureInt(valRightContinuation(), locRight)
);
case ">=":
return (
ensureInt(valLeft, locLeft) >=
ensureInt(valRightContinuation(), locRight)
);
case "<=":
return (
ensureInt(valLeft, locLeft) <=
ensureInt(valRightContinuation(), locRight)
);
case "==": {
const valR = valRightContinuation();
// the null comparisons account for optional types, e.g.
// a const x: Int? = 42 can be compared to null
if (
typeof valLeft !== typeof valR &&
valLeft !== null &&
valR !== null
) {
throwErrorConstEval(
"operands of `==` must have same type",
source,
);
}
return valLeft === valR;
}
case "!=": {
const valR = valRightContinuation();
if (typeof valLeft !== typeof valR) {
throwErrorConstEval(
"operands of `!=` must have same type",
source,
);
}
return valLeft !== valR;
}
case "&&":
return (
ensureBoolean(valLeft, locLeft) &&
ensureBoolean(valRightContinuation(), locRight)
);
case "||":
return (
ensureBoolean(valLeft, locLeft) ||
ensureBoolean(valRightContinuation(), locRight)
);
}
}
function interpretEscapeSequences(stringLiteral: string, source: SrcInfo) {
return stringLiteral.replace(
/\\\\|\\"|\\n|\\r|\\t|\\v|\\b|\\f|\\u{([0-9A-Fa-f]{1,6})}|\\u([0-9A-Fa-f]{4})|\\x([0-9A-Fa-f]{2})/g,
(match, unicodeCodePoint, unicodeEscape, hexEscape) => {
switch (match) {
case "\\\\":
return "\\";
case '\\"':
return '"';
case "\\n":
return "\n";
case "\\r":
return "\r";
case "\\t":
return "\t";
case "\\v":
return "\v";
case "\\b":
return "\b";
case "\\f":
return "\f";
default:
// Handle Unicode code point escape
if (unicodeCodePoint) {
const codePoint = parseInt(unicodeCodePoint, 16);
if (codePoint > 0x10ffff) {
throwErrorConstEval(
`unicode code point is outside of valid range 000000-10FFFF: ${stringLiteral}`,
source,
);
}
return String.fromCodePoint(codePoint);
}
// Handle Unicode escape
if (unicodeEscape) {
const codeUnit = parseInt(unicodeEscape, 16);
return String.fromCharCode(codeUnit);
}
// Handle hex escape
if (hexEscape) {
const hexValue = parseInt(hexEscape, 16);
return String.fromCharCode(hexValue);
}
return match;
}
},
);
}
class ReturnSignal extends Error {
private value?: Value;
constructor(value?: Value) {
super();
this.value = value;
}
public getValue(): Value | undefined {
return this.value;
}
}
export type InterpreterConfig = {
// Options that tune the interpreter's behavior.
// Maximum number of iterations inside a loop before a time out is issued.
// This option only applies to: do...until and while loops
maxLoopIterations: bigint;
};
const WILDCARD_NAME: string = "_";
type Environment = { values: Map<string, Value>; parent?: Environment };
class EnvironmentStack {
private currentEnv: Environment;
constructor() {
this.currentEnv = { values: new Map() };
}
private findBindingMap(name: string): Map<string, Value> | undefined {
let env: Environment | undefined = this.currentEnv;
while (env !== undefined) {
if (env.values.has(name)) {
return env.values;
} else {
env = env.parent;
}
}
return undefined;
}
/*
Sets a binding for "name" in the **current** environment of the stack.
If a binding for "name" already exists in the current environment, it
overwrites the binding with the provided value.
As a special case, name "_" is ignored.
Note that this method does not check if binding "name" already exists in
a parent environment.
This means that if binding "name" already exists in a parent environment,
it will be shadowed by the provided value in the current environment.
This shadowing behavior is useful for modelling recursive function calls.
For example, consider the recursive implementation of factorial
(for simplification purposes, it returns 1 for the factorial of
negative numbers):
1 fun factorial(a: Int): Int {
2 if (a <= 1) {
3 return 1;
4 } else {
5 return a * factorial(a - 1);
6 }
Just before factorial(4) finishes its execution, the environment stack will
look as follows (the arrows point to their parent environment):
a = 4 <------- a = 3 <-------- a = 2 <------- a = 1
Note how each child environment shadows variable a, because each
recursive call to factorial at line 5 creates a child
environment with a new binding for a.
When factorial(1) = 1 finishes execution, the environment at the top
of the stack is popped:
a = 4 <------- a = 3 <-------- a = 2
and execution resumes at line 5 in the environment where a = 2,
so that the return at line 5 is 2 * 1 = 2.
This in turn causes the stack to pop the environment at the top:
a = 4 <------- a = 3
so that the return at line 5 (now in the environment a = 3) will
produce 3 * 2 = 6, and so on.
*/
public setNewBinding(name: string, val: Value) {
if (name !== WILDCARD_NAME) {
this.currentEnv.values.set(name, val);
}
}
/*
Searches the binding "name" in the stack, starting at the current
environment and moving towards the parent environments.
If it finds the binding, it updates its value
to "val". If it does not find "name", the stack is unchanged.
As a special case, name "_" is always ignored.
*/
public updateBinding(name: string, val: Value) {
if (name !== WILDCARD_NAME) {
const bindings = this.findBindingMap(name);
if (bindings !== undefined) {
bindings.set(name, val);
}
}
}
/*
Searches the binding "name" in the stack, starting at the current
environment and moving towards the parent environments.
If it finds "name", it returns its value.
If it does not find "name", it returns undefined.
As a special case, name "_" always returns undefined.
*/
public getBinding(name: string): Value | undefined {
if (name === WILDCARD_NAME) {
return undefined;
}
const bindings = this.findBindingMap(name);
if (bindings !== undefined) {
return bindings.get(name);
} else {
return undefined;
}
}
public selfInEnvironment(): boolean {
return this.findBindingMap("self") !== undefined;
}
/*
Executes "code" in a fresh environment that is placed at the top
of the environment stack. The fresh environment is initialized
with the bindings in "initialBindings". Once "code" finishes
execution, the new environment is automatically popped from
the stack.
This method is useful for starting a new local variables scope,
like in a function call.
*/
public executeInNewEnvironment<T>(
code: () => T,
initialBindings: { names: string[]; values: Value[] } = {
names: [],
values: [],
},
): T {
const names = initialBindings.names;
const values = initialBindings.values;
const oldEnv = this.currentEnv;
this.currentEnv = { values: new Map(), parent: oldEnv };
names.forEach((name, index) => {
this.setNewBinding(name, values[index]!);
}, this);
try {
return code();
} finally {
this.currentEnv = oldEnv;
}
}
}
export function parseAndEvalExpression(
sourceCode: string,
ast: FactoryAst = getAstFactory(),
parser: Parser = getParser(ast, defaultParser),
): EvalResult {
try {
const ast = parser.parseExpression(sourceCode);
const constEvalResult = evalConstantExpression(
ast,
new CompilerContext(),
);
return { kind: "ok", value: constEvalResult };
} catch (error) {
if (
error instanceof TactCompilationError ||
error instanceof TactConstEvalError
)
return { kind: "error", message: error.message };
throw error;
}
}
const defaultInterpreterConfig: InterpreterConfig = {
// We set the default max number of loop iterations
// to the maximum number allowed for repeat loops
maxLoopIterations: maxRepeatStatement,
};
/*
Interprets Tact AST trees.
The constructor receives an optional CompilerContext which includes
all external declarations that the interpreter will use during interpretation.
If no CompilerContext is provided, the interpreter will use an empty
CompilerContext.
**IMPORTANT**: if a custom CompilerContext is provided, it should be the
CompilerContext provided by the typechecker.
The reason for requiring a CompilerContext is that the interpreter should work
in the use case where the interpreter only knows part of the code.
For example, consider the following code (I marked with brackets [ ] the places
where the interpreter gets called during expression simplification in the
compilation phase):
const C: Int = [1];
contract TestContract {
get fun test(): Int {
return [C + 1];
}
}
When the interpreter gets called inside the brackets, it does not know what
other code is surrounding those brackets, because the interpreter did not execute the
code outside the brackets. Hence, it relies on the typechecker to receive the
CompilerContext that includes the declarations in the code
(the constant C for example).
Since the interpreter relies on the typechecker, it assumes that the given AST tree
is already a valid Tact program.
Internally, the interpreter uses a stack of environments to keep track of
variables at different scopes. Each environment in the stack contains a map
that binds a variable name to its corresponding value.
*/
export class Interpreter {
private envStack: EnvironmentStack;
private context: CompilerContext;
private config: InterpreterConfig;
constructor(
context: CompilerContext = new CompilerContext(),
config: InterpreterConfig = defaultInterpreterConfig,
) {
this.envStack = new EnvironmentStack();
this.context = context;
this.config = config;
}
public interpretModuleItem(ast: AstModuleItem): void {
switch (ast.kind) {
case "constant_def":
this.interpretConstantDef(ast);
break;
case "function_def":
this.interpretFunctionDef(ast);
break;
case "asm_function_def":
throwNonFatalErrorConstEval(
"Asm functions are currently not supported.",
ast.loc,
);
break;
case "struct_decl":
this.interpretStructDecl(ast);
break;
case "message_decl":
this.interpretMessageDecl(ast);
break;
case "native_function_decl":
this.interpretFunctionDecl(ast);
break;
case "primitive_type_decl":
this.interpretPrimitiveTypeDecl(ast);
break;
case "contract":
this.interpretContract(ast);
break;
case "trait":
this.interpretTrait(ast);
break;
}
}
public interpretConstantDef(ast: AstConstantDef) {
throwNonFatalErrorConstEval(
"Constant definitions are currently not supported.",
ast.loc,
);
}
public interpretFunctionDef(ast: AstFunctionDef) {
throwNonFatalErrorConstEval(
"Function definitions are currently not supported.",
ast.loc,
);
}
public interpretStructDecl(ast: AstStructDecl) {
throwNonFatalErrorConstEval(
"Struct declarations are currently not supported.",
ast.loc,
);
}
public interpretMessageDecl(ast: AstMessageDecl) {
throwNonFatalErrorConstEval(
"Message declarations are currently not supported.",
ast.loc,
);
}
public interpretPrimitiveTypeDecl(ast: AstPrimitiveTypeDecl) {
throwNonFatalErrorConstEval(
"Primitive type declarations are currently not supported.",
ast.loc,
);
}
public interpretFunctionDecl(ast: AstNativeFunctionDecl) {
throwNonFatalErrorConstEval(
"Native function declarations are currently not supported.",
ast.loc,
);
}
public interpretContract(ast: AstContract) {
throwNonFatalErrorConstEval(
"Contract declarations are currently not supported.",
ast.loc,
);
}
public interpretTrait(ast: AstTrait) {
throwNonFatalErrorConstEval(
"Trait declarations are currently not supported.",
ast.loc,
);
}
public interpretExpression(ast: AstExpression): Value {
switch (ast.kind) {
case "id":
return this.interpretName(ast);
case "method_call":
return this.interpretMethodCall(ast);
case "init_of":
return this.interpretInitOf(ast);
case "null":
return this.interpretNull(ast);
case "boolean":
return this.interpretBoolean(ast);
case "number":
return this.interpretNumber(ast);
case "string":
return this.interpretString(ast);
case "op_unary":
return this.interpretUnaryOp(ast);
case "op_binary":
return this.interpretBinaryOp(ast);
case "conditional":
return this.interpretConditional(ast);
case "struct_instance":
return this.interpretStructInstance(ast);
case "field_access":
return this.interpretFieldAccess(ast);
case "static_call":
return this.interpretStaticCall(ast);
}
}
public interpretName(ast: AstId): Value {
if (hasStaticConstant(this.context, idText(ast))) {
const constant = getStaticConstant(this.context, idText(ast));
if (constant.value !== undefined) {
return constant.value;
} else {
throwErrorConstEval(
`cannot evaluate declared constant ${idTextErr(ast)} as it does not have a body`,
ast.loc,
);
}
}
const variableBinding = this.envStack.getBinding(idText(ast));
if (variableBinding !== undefined) {
return variableBinding;
}
throwNonFatalErrorConstEval("cannot evaluate a variable", ast.loc);
}
public interpretMethodCall(ast: AstMethodCall): Value {
switch (idText(ast.method)) {
case "asComment": {
ensureMethodArity(0, ast.args, ast.loc);
const comment = ensureString(
this.interpretExpression(ast.self),
ast.self.loc,
);
return new CommentValue(comment);
}
default:
throwNonFatalErrorConstEval(
`calls of ${idTextErr(ast.method)} are not supported at this moment`,
ast.loc,
);
}
}
public interpretInitOf(ast: AstInitOf): Value {
throwNonFatalErrorConstEval(
"initOf is not supported at this moment",
ast.loc,
);
}
public interpretNull(_ast: AstNull): null {
return null;
}
public interpretBoolean(ast: AstBoolean): boolean {
return ast.value;
}
public interpretNumber(ast: AstNumber): bigint {
return ensureInt(ast.value, ast.loc);
}
public interpretString(ast: AstString): string {
return ensureString(
interpretEscapeSequences(ast.value, ast.loc),
ast.loc,
);
}
public interpretUnaryOp(ast: AstOpUnary): Value {
// Tact grammar does not have negative integer literals,
// so in order to avoid errors for `-115792089237316195423570985008687907853269984665640564039457584007913129639936`
// which is `-(2**256)` we need to have a special case for it
if (ast.operand.kind === "number" && ast.op === "-") {
// emulating negative integer literals
return ensureInt(-ast.operand.value, ast.loc);
}
const valOperand = this.interpretExpression(ast.operand);
return evalUnaryOp(ast.op, valOperand, ast.operand.loc, ast.loc);
}
public interpretBinaryOp(ast: AstOpBinary): Value {
const valLeft = this.interpretExpression(ast.left);
const valRightContinuation = () => this.interpretExpression(ast.right);
return evalBinaryOp(
ast.op,
valLeft,
valRightContinuation,
ast.left.loc,
ast.right.loc,
ast.loc,
);
}
public interpretConditional(ast: AstConditional): Value {
// here we rely on the typechecker that both branches have the same type
const valCond = ensureBoolean(
this.interpretExpression(ast.condition),
ast.condition.loc,
);
if (valCond) {
return this.interpretExpression(ast.thenBranch);
} else {
return this.interpretExpression(ast.elseBranch);
}
}
public interpretStructInstance(ast: AstStructInstance): StructValue {
const structTy = getType(this.context, ast.type);
// initialize the resulting struct value with
// the default values for fields with initializers
// or null for uninitialized optional fields
const resultWithDefaultFields: StructValue = structTy.fields.reduce(
(resObj, field) => {
if (field.default !== undefined) {
resObj[field.name] = field.default;
} else {
if (field.type.kind === "ref" && field.type.optional) {
resObj[field.name] = null;
}
}
return resObj;
},
{ $tactStruct: idText(ast.type) } as StructValue,
);
// this will override default fields set above
return ast.args.reduce((resObj, fieldWithInit) => {
resObj[idText(fieldWithInit.field)] = this.interpretExpression(
fieldWithInit.initializer,
);
return resObj;
}, resultWithDefaultFields);
}
public interpretFieldAccess(ast: AstFieldAccess): Value {
// special case for contract/trait constant accesses via `self.constant`
// interpret "self" as a contract/trait access only if "self"
// is not already assigned in the environment (this would mean
// we are executing inside an extends function)
if (
ast.aggregate.kind === "id" &&
isSelfId(ast.aggregate) &&
!this.envStack.selfInEnvironment()
) {
const selfTypeRef = getExpType(this.context, ast.aggregate);
if (selfTypeRef.kind === "ref") {
const contractTypeDescription = getType(
this.context,
selfTypeRef.name,
);
const foundContractConst =
contractTypeDescription.constants.find((constId) =>
eqNames(ast.field, constId.name),
);
if (foundContractConst === undefined) {
// not a constant, e.g. `self.storageVariable`
throwNonFatalErrorConstEval(
"cannot evaluate non-constant self field access",
ast.aggregate.loc,
);
}
if (foundContractConst.value !== undefined) {
return foundContractConst.value;
} else {
throwErrorConstEval(
`cannot evaluate declared contract/trait constant ${idTextErr(ast.field)} as it does not have a body`,
ast.field.loc,
);
}
}
}
const valStruct = this.interpretExpression(ast.aggregate);
if (
valStruct === null ||
typeof valStruct !== "object" ||
!("$tactStruct" in valStruct)
) {
throwErrorConstEval(
`constant struct expected, but got ${showValue(valStruct)}`,
ast.aggregate.loc,
);
}
if (idText(ast.field) in valStruct) {
return valStruct[idText(ast.field)]!;
} else {
// this cannot happen in a well-typed program
throwInternalCompilerError(
`struct field ${idTextErr(ast.field)} is missing`,
ast.aggregate.loc,
);
}
}
public interpretStaticCall(ast: AstStaticCall): Value {
switch (idText(ast.function)) {
case "ton": {