This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterpreter.py
More file actions
7111 lines (6555 loc) · 322 KB
/
interpreter.py
File metadata and controls
7111 lines (6555 loc) · 322 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
from __future__ import annotations
import json
import subprocess
import math
import os
import sys
import platform
import tempfile
import codecs
import numpy as np
import threading
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
from collections import OrderedDict
from numpy.typing import NDArray
from lexer import PrefixError, PrefixParseError, Lexer
from extensions import PrefixExtensionError, HookRegistry, RuntimeServices, StepContext, TypeContext, TypeRegistry, TypeSpec, build_default_services
from parser import (
Assignment,
Declaration,
Block,
BreakStatement,
CallArgument,
CallExpression,
Expression,
ExpressionStatement,
ForStatement,
ParForStatement,
FuncDef,
LambdaExpression,
AsyncExpression,
AsyncStatement,
GotoStatement,
GotopointStatement,
Identifier,
IndexExpression,
Range,
Star,
IfBranch,
IfStatement,
Literal,
MapLiteral,
Param,
PointerExpression,
Parser,
Program,
ReturnStatement,
PopStatement,
ThrStatement,
SourceLocation,
Statement,
TensorLiteral,
TensorSetStatement,
WhileStatement,
ContinueStatement,
TryStatement,
TypedTarget,
)
TYPE_INT = "INT"
TYPE_FLT = "FLT"
TYPE_STR = "STR"
TYPE_TNS = "TNS"
TYPE_FUNC = "FUNC"
TYPE_MAP = "MAP"
TYPE_THR = "THR"
# On Windows, command lines over a certain length cause CreateProcess errors
WINDOWS_COMMAND_LENGTH_LIMIT = 8000
@dataclass(frozen=True, slots=True)
class Tensor:
shape: List[int]
data: NDArray[Any]
strides: Tuple[int, ...] = field(init=False, repr=False)
def __post_init__(self) -> None:
# Cache row-major strides for fast flat indexing.
# For shape [d0, d1, ..., dn-1], strides are
# [d1*d2*...*dn-1, d2*...*dn-1, ..., 1].
stride = 1
out: List[int] = [0] * len(self.shape)
for i in range(len(self.shape) - 1, -1, -1):
out[i] = stride
stride *= int(self.shape[i])
object.__setattr__(self, "strides", tuple(out))
@dataclass(slots=True)
class Map:
# Preserve insertion order of keys (left-to-right insertion order).
data: OrderedDict[Tuple[str, Any], "Value"] = field(default_factory=OrderedDict)
@dataclass(slots=True)
class Value:
type: str
value: Any
@dataclass(slots=True)
class PointerRef:
env: "Environment"
name: str
def __repr__(self) -> str: # pragma: no cover - debug aid only
return f"<ptr {self.name}>"
class PrefixRuntimeError(PrefixError):
"""Raised for runtime faults."""
def __init__(
self,
message: str,
*,
location: Optional[SourceLocation] = None,
rewrite_rule: Optional[str] = None,
) -> None:
super().__init__(message)
self.message = message
self.location = location
self.rewrite_rule = rewrite_rule
self.step_index: Optional[int] = None
class ReturnSignal(Exception):
def __init__(self, value: Value) -> None:
super().__init__(value)
self.value = value
class ExitSignal(Exception):
def __init__(self, code: int = 0) -> None:
super().__init__(code)
self.code = code
class BreakSignal(Exception):
def __init__(self, count: int) -> None:
super().__init__(count)
self.count = count
class ContinueSignal(Exception):
def __init__(self) -> None:
super().__init__()
class JumpSignal(Exception):
def __init__(self, target: Value) -> None:
super().__init__(target)
self.target = target
@dataclass(slots=True)
class Environment:
parent: Optional["Environment"] = None
values: Dict[str, Value] = field(default_factory=dict)
# declared but unassigned symbol types
declared: Dict[str, str] = field(default_factory=dict)
frozen: set = field(default_factory=set)
permafrozen: set = field(default_factory=set)
def _find_env(self, name: str) -> Optional["Environment"]:
env: Optional[Environment] = self
while env is not None:
if env.values.get(name) is not None:
return env
env = env.parent
return None
def set(self, name: str, value: Value, declared_type: Optional[str] = None) -> None:
# Hot-path: inline _find_env to avoid an extra Python call on every assignment.
env: Optional[Environment] = self
found_env: Optional[Environment] = None
found_existing: Optional[Value] = None
while env is not None:
values = env.values
existing = values.get(name)
if existing is not None:
found_env = env
found_existing = existing
break
env = env.parent
if found_env is not None:
assert found_existing is not None
existing = found_existing
if name in found_env.frozen or name in found_env.permafrozen:
raise PrefixRuntimeError(
f"Identifier '{name}' is frozen and cannot be reassigned",
rewrite_rule="ASSIGN",
)
incoming_ptr = value.value if isinstance(value.value, PointerRef) else None
if incoming_ptr is not None and incoming_ptr.env is found_env and incoming_ptr.name == name:
raise PrefixRuntimeError(
"Cannot create self-referential pointer",
rewrite_rule="ASSIGN",
)
if isinstance(existing.value, PointerRef):
ptr = existing.value
if ptr.env is found_env and ptr.name == name:
raise PrefixRuntimeError(
"Cannot assign through self-referential pointer",
rewrite_rule="ASSIGN",
)
ptr.env.set(ptr.name, value, declared_type=None)
return
if declared_type and existing.type != declared_type:
raise PrefixRuntimeError(
f"Type mismatch for '{name}': previously declared as {existing.type}",
rewrite_rule="ASSIGN",
)
if existing.type != value.type:
raise PrefixRuntimeError(
f"Type mismatch for '{name}': expected {existing.type} but got {value.type}",
rewrite_rule="ASSIGN",
)
found_env.values[name] = value
return
# No existing value binding found. Look for a prior type declaration
# in this environment chain.
decl_env: Optional[Environment] = None
decl_type: Optional[str] = None
env2: Optional[Environment] = self
while env2 is not None:
if name in env2.declared:
decl_env = env2
decl_type = env2.declared[name]
break
env2 = env2.parent
if declared_type is None:
# Assignment without inline declaration: require a prior declaration
if decl_env is None:
raise PrefixRuntimeError(
f"Identifier '{name}' must be declared with a type before assignment",
rewrite_rule="ASSIGN",
)
if decl_type != value.type:
raise PrefixRuntimeError(
f"Assigned value type {value.type} does not match declaration {decl_type}",
rewrite_rule="ASSIGN",
)
decl_env.values[name] = value
return
# Assignment with inline declaration: if there is an existing declaration
# ensure it matches; otherwise record declaration in current env.
if decl_env is not None:
if decl_type != declared_type:
raise PrefixRuntimeError(
f"Type mismatch for '{name}': previously declared as {decl_type}",
rewrite_rule="ASSIGN",
)
if declared_type != value.type:
raise PrefixRuntimeError(
f"Assigned value type {value.type} does not match declaration {declared_type}",
rewrite_rule="ASSIGN",
)
decl_env.values[name] = value
return
# No prior declaration: record it in this environment and create the value
if declared_type != value.type:
raise PrefixRuntimeError(
f"Assigned value type {value.type} does not match declaration {declared_type}",
rewrite_rule="ASSIGN",
)
self.declared[name] = declared_type
self.values[name] = value
def get(self, name: str) -> Value:
# Hot-path: inline _find_env to avoid an extra Python call on every read.
env: Optional[Environment] = self
while env is not None:
values = env.values
found = values.get(name)
if found is not None:
return found
env = env.parent
raise PrefixRuntimeError(f"Undefined identifier '{name}'", rewrite_rule="IDENT")
def get_optional(self, name: str) -> Optional[Value]:
# Hot-path: inline _find_env; heavily used by identifier evaluation.
env: Optional[Environment] = self
while env is not None:
values = env.values
found = values.get(name)
if found is not None:
return found
env = env.parent
return None
def delete(self, name: str) -> None:
env: Optional[Environment] = self
found_env: Optional[Environment] = None
while env is not None:
if env.values.get(name) is not None:
found_env = env
break
env = env.parent
if found_env is not None:
if name in found_env.frozen or name in found_env.permafrozen:
raise PrefixRuntimeError(f"Identifier '{name}' is frozen and cannot be deleted", rewrite_rule="DEL")
del found_env.values[name]
return
raise PrefixRuntimeError(f"Cannot delete undefined identifier '{name}'", rewrite_rule="DEL")
def has(self, name: str) -> bool:
env: Optional[Environment] = self
while env is not None:
if env.values.get(name) is not None:
return True
env = env.parent
return False
def snapshot(self) -> Dict[str, str]:
def _render(val: Value) -> str:
if val.type == TYPE_TNS and isinstance(val.value, Tensor):
dims = ",".join(str(d) for d in val.value.shape)
return f"{val.type}:[{dims}]"
if val.type == TYPE_FUNC:
func_name = getattr(val.value, "name", "<func>")
return f"{val.type}:{func_name}"
if isinstance(val.value, PointerRef):
return f"{val.type}:&{val.value.name}"
try:
rendered = str(val.value)
except Exception:
rendered = repr(val.value)
if len(rendered) > 80:
rendered = rendered[:77] + "..."
return f"{val.type}:{rendered}"
return {k: _render(v) for k, v in self.values.items()}
def freeze(self, name: str) -> None:
env = self._find_env(name)
if env is None:
raise PrefixRuntimeError(f"Cannot freeze undefined identifier '{name}'", rewrite_rule="FREEZE")
env.frozen.add(name)
def thaw(self, name: str) -> None:
env = self._find_env(name)
if env is None:
raise PrefixRuntimeError(f"Cannot thaw undefined identifier '{name}'", rewrite_rule="THAW")
if name in env.permafrozen:
raise PrefixRuntimeError(
f"Identifier '{name}' is permanently frozen and cannot be thawed",
rewrite_rule="THAW",
)
# silently succeed if not frozen
env.frozen.discard(name)
def permafreeze(self, name: str) -> None:
env = self._find_env(name)
if env is None:
raise PrefixRuntimeError(f"Cannot permafreeze undefined identifier '{name}'", rewrite_rule="PERMAFREEZE")
env.frozen.add(name)
env.permafrozen.add(name)
@dataclass(slots=True)
class Function:
name: str
params: List[Param]
return_type: str
body: Block
closure: Environment
@dataclass(slots=True)
class Frame:
name: str
env: Environment
frame_id: str
call_location: Optional[SourceLocation]
gotopoints: Dict[Any, int] = field(default_factory=dict)
@dataclass(slots=True)
class StateEntry:
step_index: int
state_id: str
frame_id: Optional[str]
source_location: Optional[SourceLocation]
statement: Optional[str]
env_snapshot: Optional[Dict[str, Any]]
rewrite_record: Optional[Dict[str, Any]]
class StateLogger:
def __init__(self, verbose: bool) -> None:
self.verbose = verbose
self.entries: List[StateEntry] = []
self.next_state_index = 0
self.last_state_id = "seed"
self.frame_last_entry: Dict[str, StateEntry] = {}
def record(
self,
*,
frame: Optional[Frame],
location: Optional[SourceLocation],
statement: Optional[str],
rewrite_record: Optional[Dict[str, Any]] = None,
env_snapshot: Optional[Dict[str, Any]] = None,
) -> StateEntry:
# Hot-path: reuse the caller-provided dict rather than copying.
# The interpreter constructs a fresh dict per step in _log_step, so
# sharing is safe and avoids one allocation per step.
rewrite = {} if rewrite_record is None else rewrite_record
if "from_state_id" not in rewrite:
rewrite["from_state_id"] = self.last_state_id
step_index = self.next_state_index
state_id = f"s_{step_index:06d}"
rewrite["to_state_id"] = state_id
entry = StateEntry(
step_index=step_index,
state_id=state_id,
frame_id=frame.frame_id if frame else None,
source_location=location,
statement=statement,
env_snapshot=env_snapshot,
rewrite_record=rewrite,
)
self.entries.append(entry)
if frame:
self.frame_last_entry[frame.frame_id] = entry
self.last_state_id = state_id
self.next_state_index += 1
return entry
def last_entry_for_frame(self, frame_id: str) -> Optional[StateEntry]:
return self.frame_last_entry.get(frame_id)
BuiltinImpl = Callable[["Interpreter", List[Value], List[Expression], Environment, SourceLocation], Value]
@dataclass(slots=True)
class BuiltinFunction:
name: str
min_args: int
max_args: Optional[int]
impl: BuiltinImpl
def validate(self, supplied: int) -> None:
if supplied < self.min_args:
raise PrefixRuntimeError(f"{self.name} expects at least {self.min_args} arguments", rewrite_rule=self.name)
if self.max_args is not None and supplied > self.max_args:
raise PrefixRuntimeError(f"{self.name} expects at most {self.max_args} arguments", rewrite_rule=self.name)
def _as_bool(value: int) -> int:
return 0 if value == 0 else 1
class Builtins:
def __init__(self) -> None:
self.table: Dict[str, BuiltinFunction] = {}
self._register_custom("ADD", 2, 2, self._add)
self._register_custom("IADD", 2, 2, self._iadd)
self._register_custom("FADD", 2, 2, self._fadd)
self._register_custom("SUB", 2, 2, self._sub)
self._register_custom("ISUB", 2, 2, self._isub)
self._register_custom("FSUB", 2, 2, self._fsub)
self._register_custom("MUL", 2, 2, self._mul)
self._register_custom("IMUL", 2, 2, self._imul)
self._register_custom("FMUL", 2, 2, self._fmul)
self._register_custom("DIV", 2, 2, self._div)
self._register_custom("IDIV", 2, 2, self._idiv)
self._register_custom("FDIV", 2, 2, self._fdiv)
self._register_int_only("CDIV", 2, self._safe_cdiv)
self._register_custom("MOD", 2, 2, self._mod)
self._register_custom("POW", 2, 2, self._pow)
self._register_custom("IPOW", 2, 2, self._ipow)
self._register_custom("FPOW", 2, 2, self._fpow)
self._register_custom("ROOT", 2, 2, self._root)
self._register_custom("IROOT", 2, 2, self._iroot)
self._register_custom("FROOT", 2, 2, self._froot)
self._register_custom("NEG", 1, 1, self._neg)
self._register_custom("ABS", 1, 1, self._abs)
self._register_custom("GCD", 2, 2, self._gcd)
self._register_custom("LCM", 2, 2, self._lcm_num)
self._register_int_only("BAND", 2, lambda a, b: a & b)
self._register_int_only("BOR", 2, lambda a, b: a | b)
self._register_int_only("BXOR", 2, lambda a, b: a ^ b)
self._register_int_only("BNOT", 1, lambda a: ~a)
self._register_int_only("SHL", 2, self._shift_left)
self._register_int_only("SHR", 2, self._shift_right)
self._register_custom("SLICE", 3, 3, self._slice)
self._register_custom("AND", 2, 2, self._and)
self._register_custom("OR", 2, 2, self._or)
self._register_custom("XOR", 2, 2, self._xor)
self._register_custom("NOT", 1, 1, self._not)
self._register_custom("BOOL", 1, 1, self._bool)
self._register_custom("ARGV", 0, 0, self._argv)
self._register_custom("EQ", 2, 2, self._eq)
self._register_custom("IN", 2, 2, self._in)
self._register_custom("GT", 2, 2, self._gt)
self._register_custom("LT", 2, 2, self._lt)
self._register_custom("GTE", 2, 2, self._gte)
self._register_custom("LTE", 2, 2, self._lte)
self._register_variadic("SUM", 1, self._sum)
self._register_variadic("ISUM", 1, self._isum)
self._register_variadic("FSUM", 1, self._fsum)
self._register_variadic("PROD", 1, self._prod)
self._register_variadic("IPROD", 1, self._iprod)
self._register_variadic("FPROD", 1, self._fprod)
self._register_variadic("MAX", 1, self._max)
self._register_variadic("MIN", 1, self._min)
self._register_variadic("ANY", 1, self._any)
self._register_variadic("ALL", 1, self._all)
self._register_variadic("LEN", 0, self._len)
self._register_custom("SLEN", 1, 1, self._slen)
self._register_custom("ILEN", 1, 1, self._ilen)
self._register_variadic("JOIN", 1, self._join)
self._register_custom("SPLIT", 1, 2, self._split)
self._register_custom("LOG", 1, 1, self._log)
self._register_int_only("CLOG", 1, self._safe_clog)
self._register_custom("INT", 1, 1, self._int_op)
self._register_custom("FLT", 1, 1, self._flt_op)
self._register_custom("STR", 1, 1, self._str_op)
self._register_custom("UPPER", 1, 1, self._upper)
self._register_custom("LOWER", 1, 1, self._lower)
self._register_custom("STRIP", 2, 2, self._strip)
self._register_custom("REPLACE", 3, 3, self._replace)
self._register_custom("MAIN", 0, 0, self._main)
self._register_custom("OS", 0, 0, self._os)
self._register_custom("IMPORT", 1, 2, self._import)
self._register_custom("IMPORT_PATH", 1, 1, self._import_path)
self._register_custom("RUN", 1, 1, self._run)
self._register_custom("INPUT", 0, 1, self._input)
self._register_custom("PRINT", 0, None, self._print)
self._register_custom("ASSERT", 1, 1, self._assert)
self._register_custom("THROW", 0, None, self._throw)
self._register_custom("ASSIGN", 2, 2, self._assign)
self._register_custom("DEL", 1, 1, self._delete)
self._register_custom("FREEZE", 1, 1, self._freeze)
self._register_custom("THAW", 1, 1, self._thaw)
self._register_custom("PERMAFREEZE", 1, 1, self._permafreeze)
self._register_custom("FROZEN", 1, 1, self._frozen)
self._register_custom("PERMAFROZEN", 1, 1, self._permafrozen)
self._register_custom("EXIST", 1, 1, self._exist)
self._register_custom("KEYS", 1, 1, self._keys)
self._register_custom("VALUES", 1, 1, self._values)
self._register_custom("KEYIN", 2, 2, self._keyin)
self._register_custom("MATCH", 2, 5, self._match)
self._register_custom("VALUEIN", 2, 2, self._valuein)
self._register_custom("INV", 1, 1, self._inv)
self._register_custom("EXPORT", 2, 2, self._export)
self._register_custom("ISINT", 1, 1, self._isint)
self._register_custom("ISFLT", 1, 1, self._isflt)
self._register_custom("ISSTR", 1, 1, self._isstr)
self._register_custom("ISTNS", 1, 1, self._istns)
self._register_custom("TYPE", 1, 1, self._type)
self._register_custom("SIGNATURE", 1, 1, self._signature)
self._register_custom("COPY", 1, 1, self._copy)
self._register_custom("DEEPCOPY", 1, 1, self._deepcopy)
self._register_custom("ROUND", 1, 3, self._round)
self._register_custom("READFILE", 1, 2, self._readfile)
self._register_custom("BYTES", 1, 2, self._bytes)
self._register_custom("WRITEFILE", 2, 3, self._writefile)
self._register_custom("DELETEFILE", 1, 1, self._deletefile)
self._register_custom("EXISTFILE", 1, 1, self._existfile)
self._register_custom("CL", 1, 1, self._cl)
self._register_custom("EXIT", 0, 1, self._exit)
self._register_custom("SHUSH", 0, 0, self._shush)
self._register_custom("UNSHUSH", 0, 0, self._unshush)
self._register_custom("SHAPE", 1, 1, self._shape)
self._register_custom("TLEN", 2, 2, self._tlen)
self._register_custom("FILL", 2, 2, self._fill)
self._register_custom("TNS", 1, 2, self._tns)
self._register_custom("TINT", 1, 1, self._tint)
self._register_custom("TFLT", 1, 1, self._tflt)
self._register_custom("TSTR", 1, 1, self._tstr)
self._register_custom("MADD", 2, 2, self._madd)
self._register_custom("MSUB", 2, 2, self._msub)
self._register_custom("MMUL", 2, 2, self._mmul)
self._register_custom("MDIV", 2, 2, self._mdiv)
self._register_variadic("MSUM", 1, self._msum)
self._register_variadic("MPROD", 1, self._mprod)
self._register_custom("TADD", 2, 2, self._tadd)
self._register_custom("TSUB", 2, 2, self._tsub)
self._register_custom("TMUL", 2, 2, self._tmul)
self._register_custom("TDIV", 2, 2, self._tdiv)
self._register_custom("TPOW", 2, 2, self._tpow)
self._register_custom("CONV", 2, None, self._convolve)
self._register_custom("FLIP", 1, 1, self._flip)
self._register_custom("TFLIP", 2, 2, self._tflip)
self._register_custom("SCAT", 3, 3, self._scatter)
self._register_custom("PARALLEL", 1, None, self._parallel)
self._register_custom("SER", 1, 1, self._serialize)
self._register_custom("UNSER", 1, 1, self._unserialize)
def _register_int_only(self, name: str, arity: int, func: Callable[..., int]) -> None:
if arity == 1:
def impl_1(_: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._expect_int(args[0], name, location)
return Value(TYPE_INT, func(a))
self.table[name] = BuiltinFunction(name=name, min_args=1, max_args=1, impl=impl_1)
return
if arity == 2:
def impl_2(_: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._expect_int(args[0], name, location)
b = self._expect_int(args[1], name, location)
return Value(TYPE_INT, func(a, b))
self.table[name] = BuiltinFunction(name=name, min_args=2, max_args=2, impl=impl_2)
return
def impl_n(_: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
ints = [self._expect_int(arg, name, location) for arg in args]
return Value(TYPE_INT, func(*ints))
self.table[name] = BuiltinFunction(name=name, min_args=arity, max_args=arity, impl=impl_n)
def _register_variadic(
self,
name: str,
min_args: int,
func: Callable[["Interpreter", List[Value], SourceLocation], Value],
) -> None:
def impl(interpreter: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
return func(interpreter, args, location)
self.table[name] = BuiltinFunction(name=name, min_args=min_args, max_args=None, impl=impl)
def _register_custom(
self,
name: str,
min_args: int,
max_args: Optional[int],
impl: BuiltinImpl,
) -> None:
self.table[name] = BuiltinFunction(name=name, min_args=min_args, max_args=max_args, impl=impl)
def register_extension_operator(
self,
*,
name: str,
min_args: int,
max_args: Optional[int],
impl: BuiltinImpl,
) -> None:
if name in self.table:
raise PrefixExtensionError(f"Cannot override existing operator '{name}'")
self.table[name] = BuiltinFunction(name=name, min_args=min_args, max_args=max_args, impl=impl)
def invoke(
self,
interpreter: "Interpreter",
name: str,
args: List[Value],
arg_nodes: List[Expression],
env: Environment,
location: SourceLocation,
) -> Value:
builtin = self.table.get(name)
if builtin is None:
raise PrefixRuntimeError(f"Unknown function '{name}'", location=location)
supplied = len(args)
if supplied < builtin.min_args:
raise PrefixRuntimeError(f"{name} expects at least {builtin.min_args} arguments", rewrite_rule=name, location=location)
if builtin.max_args is not None and supplied > builtin.max_args:
raise PrefixRuntimeError(f"{name} expects at most {builtin.max_args} arguments", rewrite_rule=name, location=location)
return builtin.impl(interpreter, args, arg_nodes, env, location)
# Helpers
def _expect_int(self, value: Value, rule: str, location: SourceLocation) -> int:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type != TYPE_INT:
raise PrefixRuntimeError(f"{rule} expects integer arguments", location=location, rewrite_rule=rule)
assert isinstance(value.value, int)
return value.value
def _expect_flt(self, value: Value, rule: str, location: SourceLocation) -> float:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type != TYPE_FLT:
raise PrefixRuntimeError(f"{rule} expects float arguments", location=location, rewrite_rule=rule)
assert isinstance(value.value, float)
return value.value
def _expect_num_pair(self, args: List[Value], rule: str, location: SourceLocation) -> Tuple[str, Any, Any]:
if len(args) != 2:
raise PrefixRuntimeError(f"{rule} expects 2 arguments", location=location, rewrite_rule=rule)
a, b = args[0], args[1]
if a.type != b.type:
raise PrefixRuntimeError(f"{rule} cannot mix INT and FLT", location=location, rewrite_rule=rule)
if a.type == TYPE_INT:
return TYPE_INT, self._expect_int(a, rule, location), self._expect_int(b, rule, location)
if a.type == TYPE_FLT:
return TYPE_FLT, self._expect_flt(a, rule, location), self._expect_flt(b, rule, location)
raise PrefixRuntimeError(f"{rule} expects INT or FLT arguments", location=location, rewrite_rule=rule)
def _expect_num_unary(self, args: List[Value], rule: str, location: SourceLocation) -> Tuple[str, Any]:
if len(args) != 1:
raise PrefixRuntimeError(f"{rule} expects 1 argument", location=location, rewrite_rule=rule)
a = args[0]
if a.type == TYPE_INT:
return TYPE_INT, self._expect_int(a, rule, location)
if a.type == TYPE_FLT:
return TYPE_FLT, self._expect_flt(a, rule, location)
raise PrefixRuntimeError(f"{rule} expects INT or FLT arguments", location=location, rewrite_rule=rule)
def _coerce_int(self, value: Value, rule: str, location: SourceLocation) -> int:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type == TYPE_INT:
assert isinstance(value.value, int)
return value.value
if value.type == TYPE_FLT:
assert isinstance(value.value, float)
return int(value.value)
raise PrefixRuntimeError(f"{rule} expects INT or FLT arguments", location=location, rewrite_rule=rule)
def _coerce_flt(self, value: Value, rule: str, location: SourceLocation) -> float:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type == TYPE_FLT:
assert isinstance(value.value, float)
return value.value
if value.type == TYPE_INT:
assert isinstance(value.value, int)
return float(value.value)
raise PrefixRuntimeError(f"{rule} expects INT or FLT arguments", location=location, rewrite_rule=rule)
def _root_numeric(self, t: str, x: Any, n: Any, *, rule: str, location: SourceLocation) -> Value:
# Common checks
if (t == TYPE_INT and n == 0) or (t == TYPE_FLT and n == 0.0):
raise PrefixRuntimeError(f"{rule} exponent must be non-zero", rewrite_rule=rule, location=location)
if t == TYPE_INT:
if n < 0:
if x == 0:
raise PrefixRuntimeError("Division by zero", rewrite_rule=rule, location=location)
if abs(x) != 1:
raise PrefixRuntimeError(f"Negative {rule} exponent yields non-integer result", rewrite_rule=rule, location=location)
return Value(TYPE_INT, x)
k = n
if k == 1:
return Value(TYPE_INT, x)
if x >= 0:
lo = 0
hi = 1
while pow(hi, k) <= x:
hi <<= 1
while lo + 1 < hi:
mid = (lo + hi) // 2
if pow(mid, k) <= x:
lo = mid
else:
hi = mid
return Value(TYPE_INT, lo)
if k % 2 == 0:
raise PrefixRuntimeError("Even root of negative integer", rewrite_rule=rule, location=location)
ax = -x
lo = 0
hi = 1
while pow(hi, k) <= ax:
hi <<= 1
while lo + 1 < hi:
mid = (lo + hi) // 2
if pow(mid, k) <= ax:
lo = mid
else:
hi = mid
return Value(TYPE_INT, -lo)
if x == 0.0 and n < 0.0:
raise PrefixRuntimeError("Division by zero", rewrite_rule=rule, location=location)
if x < 0.0:
if not float(n).is_integer() or int(n) % 2 == 0:
raise PrefixRuntimeError(f"{rule} of negative float requires odd integer root", rewrite_rule=rule, location=location)
return Value(TYPE_FLT, -1.0 * pow(abs(x), 1.0 / n))
return Value(TYPE_FLT, pow(x, 1.0 / n))
def _add(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "ADD", location)
return Value(t, a + b)
def _iadd(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_int(args[0], "IADD", location)
b = self._coerce_int(args[1], "IADD", location)
return Value(TYPE_INT, a + b)
def _fadd(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_flt(args[0], "FADD", location)
b = self._coerce_flt(args[1], "FADD", location)
return Value(TYPE_FLT, a + b)
def _sub(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "SUB", location)
return Value(t, a - b)
def _isub(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_int(args[0], "ISUB", location)
b = self._coerce_int(args[1], "ISUB", location)
return Value(TYPE_INT, a - b)
def _fsub(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_flt(args[0], "FSUB", location)
b = self._coerce_flt(args[1], "FSUB", location)
return Value(TYPE_FLT, a - b)
def _mul(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "MUL", location)
return Value(t, a * b)
def _imul(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_int(args[0], "IMUL", location)
b = self._coerce_int(args[1], "IMUL", location)
return Value(TYPE_INT, a * b)
def _fmul(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_flt(args[0], "FMUL", location)
b = self._coerce_flt(args[1], "FMUL", location)
return Value(TYPE_FLT, a * b)
def _div(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "DIV", location)
if t == TYPE_INT:
return Value(TYPE_INT, self._safe_div(a, b))
if b == 0.0:
raise PrefixRuntimeError("Division by zero", rewrite_rule="DIV", location=location)
return Value(TYPE_FLT, a / b)
def _idiv(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_int(args[0], "IDIV", location)
b = self._coerce_int(args[1], "IDIV", location)
if b == 0:
raise PrefixRuntimeError("Division by zero", rewrite_rule="IDIV", location=location)
return Value(TYPE_INT, a // b)
def _fdiv(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_flt(args[0], "FDIV", location)
b = self._coerce_flt(args[1], "FDIV", location)
if b == 0.0:
raise PrefixRuntimeError("Division by zero", rewrite_rule="FDIV", location=location)
return Value(TYPE_FLT, a / b)
def _mod(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "MOD", location)
if t == TYPE_INT:
return Value(TYPE_INT, self._safe_mod(a, b))
if b == 0.0:
raise PrefixRuntimeError("Division by zero", rewrite_rule="MOD", location=location)
return Value(TYPE_FLT, a % abs(b))
def _pow(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "POW", location)
if t == TYPE_INT:
return Value(TYPE_INT, self._safe_pow(a, b))
return Value(TYPE_FLT, pow(a, b))
def _ipow(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_int(args[0], "IPOW", location)
b = self._coerce_int(args[1], "IPOW", location)
if b < 0:
raise PrefixRuntimeError("Negative exponent not supported", rewrite_rule="IPOW", location=location)
return Value(TYPE_INT, pow(a, b))
def _fpow(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
a = self._coerce_flt(args[0], "FPOW", location)
b = self._coerce_flt(args[1], "FPOW", location)
return Value(TYPE_FLT, pow(a, b))
def _root(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, x, n = self._expect_num_pair(args, "ROOT", location)
return self._root_numeric(t, x, n, rule="ROOT", location=location)
def _iroot(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
x = self._coerce_int(args[0], "IROOT", location)
n = self._coerce_int(args[1], "IROOT", location)
return self._root_numeric(TYPE_INT, x, n, rule="IROOT", location=location)
def _froot(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
x = self._coerce_flt(args[0], "FROOT", location)
n = self._coerce_flt(args[1], "FROOT", location)
return self._root_numeric(TYPE_FLT, x, n, rule="FROOT", location=location)
def _neg(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a = self._expect_num_unary(args, "NEG", location)
return Value(t, -a)
def _abs(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a = self._expect_num_unary(args, "ABS", location)
return Value(t, abs(a))
def _gcd(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "GCD", location)
if t == TYPE_INT:
return Value(TYPE_INT, math.gcd(a, b))
# For floats, only accept integer-valued inputs.
if not float(a).is_integer() or not float(b).is_integer():
raise PrefixRuntimeError("GCD expects integer-valued floats", location=location, rewrite_rule="GCD")
return Value(TYPE_FLT, float(math.gcd(int(a), int(b))))
def _lcm_num(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "LCM", location)
if t == TYPE_INT:
return Value(TYPE_INT, self._lcm(a, b))
if not float(a).is_integer() or not float(b).is_integer():
raise PrefixRuntimeError("LCM expects integer-valued floats", location=location, rewrite_rule="LCM")
return Value(TYPE_FLT, float(math.lcm(int(a), int(b))))
def _gt(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "GT", location)
return Value(TYPE_INT, 1 if a > b else 0)
def _lt(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "LT", location)
return Value(TYPE_INT, 1 if a < b else 0)
def _gte(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "GTE", location)
return Value(TYPE_INT, 1 if a >= b else 0)
def _lte(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a, b = self._expect_num_pair(args, "LTE", location)
return Value(TYPE_INT, 1 if a <= b else 0)
def _log(self, _: "Interpreter", args: List[Value], __: List[Expression], ___: Environment, location: SourceLocation) -> Value:
t, a = self._expect_num_unary(args, "LOG", location)
if t == TYPE_INT:
return Value(TYPE_INT, self._safe_log(a))
if a <= 0.0:
raise PrefixRuntimeError("LOG argument must be > 0", rewrite_rule="LOG", location=location)
return Value(TYPE_FLT, float(math.floor(math.log2(a))))
def _expect_str(self, value: Value, rule: str, location: SourceLocation) -> str:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type != TYPE_STR:
raise PrefixRuntimeError(f"{rule} expects string arguments", location=location, rewrite_rule=rule)
assert isinstance(value.value, str)
return value.value
def _expect_tns(self, value: Value, rule: str, location: SourceLocation) -> Tensor:
value = self._deref_pointer(value, rule=rule, location=location)
if value.type != TYPE_TNS:
raise PrefixRuntimeError(f"{rule} expects tensor arguments", location=location, rewrite_rule=rule)
assert isinstance(value.value, Tensor)
return value.value
def _deref_pointer(self, value: Value, *, rule: str, location: SourceLocation) -> Value:
current = value
hops = 0
while isinstance(current.value, PointerRef):
hops += 1
if hops > 128:
raise PrefixRuntimeError("Pointer cycle detected", location=location, rewrite_rule=rule)
ptr = current.value
target = ptr.env.get_optional(ptr.name)
if target is None:
raise PrefixRuntimeError(
f"Pointer target '{ptr.name}' is undefined",
location=location,
rewrite_rule=rule,
)
current = target
return current
def _normalize_coding(self, coding_raw: str, rule: str, location: SourceLocation) -> str:
tag = coding_raw.strip().lower().replace("_", "-")
compact = tag.replace("-", "").replace(" ", "")
mapping = {
"utf8": "utf-8",
"utf8bom": "utf-8-bom",
"utf8sig": "utf-8-bom",
"utf": "utf-8",
"utf-8": "utf-8",
"utf-8bom": "utf-8-bom",
"utf-8sig": "utf-8-bom",
"utf16le": "utf-16-le",
"utf16be": "utf-16-be",
"utf-16le": "utf-16-le",
"utf-16be": "utf-16-be",
"binary": "binary",
"bin": "binary",
"hex": "hex",
"hexadecimal": "hex",
"ansi": "ansi",
}
normalized = mapping.get(compact)
if normalized is None:
raise PrefixRuntimeError(
f"Unsupported coding '{coding_raw}'",
location=location,
rewrite_rule=rule,
)
return normalized