forked from ajtowns/bllsh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopcodes.py
More file actions
executable file
·1606 lines (1429 loc) · 56.1 KB
/
Copy pathopcodes.py
File metadata and controls
executable file
·1606 lines (1429 loc) · 56.1 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
#!/usr/bin/env python3
import hashlib
import struct
import sys
from typing import final
import verystable.core.key
import verystable.core.messages
import verystable.core.script
import verystable.core.secp256k1
import costs
import ripemd160
from element import Element, Atom, Cons, Error, SerDeser, int_to_bytes
class Tree:
def __init__(self):
self.tree = []
@classmethod
def dbl_n(cls, n, offset=0, size=0):
assert offset >= 0 and (offset >> size) == 0
r = [1]
while n > 0:
r = [a*2 for a in r] + [a*2+1 for a in r]
n -= 1
if size > 0:
r = [(a << size) + offset for a in r]
return r
@classmethod
def get_values(cls, n, offset=0, size=0):
k, v = 0,1
while v < n:
k += 1
v *= 2
values = []
while n > 0:
while v > n:
k -= 1
v //= 2
values.extend(cls.dbl_n(k, offset, size))
offset = (offset * 2) + 1
size += 1
n -= v
return values
@classmethod
def get_values_pair(cls, n1, n2):
if n1 == 0:
return [], cls.get_values(n2)
elif n2 == 0:
return cls.get_values(n1), []
else:
return (cls.get_values(n1, offset=0, size=1),
cls.get_values(n2, offset=1, size=1))
def add(self, element):
i = 0
while i < len(self.tree):
if self.tree[i] is None:
self.tree[i] = element
return
element = Cons(self.tree[i], element)
self.tree[i] = None
i += 1
self.tree.append(element)
def resolve(self):
x = None
for el in self.tree:
if el is None: continue
if x is None:
x = el
else:
x = Cons(el, x)
return x
class Opcode:
@classmethod
@final
def opcode_name(cls):
return cls.__name__
@classmethod
def size_cap(cls):
"""Overridable output size limit for the opcodes whose result
can outgrow their inputs, checked at a fixed point in each
one's charge sequence. The base opcodes are uncapped, a
capped variant only overrides the value so every charge
sequence lives here once."""
return None
@staticmethod
def initial_state():
return Atom(0)
@staticmethod
def initial_int_state():
return None
@classmethod
def argument(cls, budget, int_state, state, arg): raise NotImplementedError
@classmethod
def finish(cls, budget, int_state, state): raise NotImplementedError
class BinOpcode(Opcode):
"""For opcodes that are essentially binary operators"""
@classmethod
def binop(cls, budget, left, right):
raise NotImplementedError
@final
@classmethod
def argument(cls, budget, int_state, state, arg):
assert int_state is None
r = cls.binop(budget, state, arg)
return (r, None)
@staticmethod
def finish(budget, int_state, state):
assert int_state is None
return state.bumpref()
@staticmethod
def finish_escape(budget, state):
"""The finish path of the folds that deliver their running
accumulator as the result. Only that last accumulator
escapes the fold, every superseded intermediate dies with
the next binop, so the ELEMENT_ALLOC memory charge for the
delivered element object lands here, once per application.
The charge is flat on purpose: an interned or borrowed
delivery overpays it, the safe direction, and the finish
cost never depends on the operand values."""
if not budget.charge(costs.ELEMENT_ALLOC):
return None
return state.bumpref()
class FixOpcode(Opcode):
min_args = max_args = -1
@classmethod
def operation(cls, budget, *args):
raise NotImplementedError
@final
@staticmethod
def state_info(state):
if state.is_nil(): return 0, state
assert state.is_cons() and state.val2.is_atom()
return state.val2.as_int(), state.val1
@final
@classmethod
def argument(cls, budget, int_state, state, arg):
assert int_state is None
# The collection charge covers the accumulator's two conses
# and count atom plus their share of the finish-time unpack
# walk. Charged before the arity check: the too-many error
# is collection work too.
if not budget.charge(costs.FIX_COLLECT):
return (None, None)
n, rest = cls.state_info(state)
if n >= cls.max_args:
return (Error("too many arguments"), None)
return (Cons(Cons(arg.bumpref(), rest.bumpref()), Atom(n+1)), None)
@final
@classmethod
def finish(cls, budget, int_state, state):
assert int_state is None
n, rest = cls.state_info(state)
if n < cls.min_args:
return Error("too few arguments")
args = []
for _ in range(n):
args.append(rest.val1)
rest = rest.val2
return cls.operation(budget, *(args[::-1]))
class op_x(FixOpcode):
min_args = 0
max_args = 10
@classmethod
def operation(cls, budget, *args):
if not budget.charge(costs.CONTROL_BASE):
return None
return Error(f"Exception: {" ".join(str(a) for a in args)}")
class op_add(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.ARITH_ARG):
return None
if left.is_atom() and right.is_atom():
if not budget.charge(costs.ARITH_PER_BYTE * (left.val1 + right.val1)):
return None
enc = int_to_bytes(left.as_int() + right.as_int())
cap = cls.size_cap()
if cap is not None and len(enc) > cap:
return Error("element size limit exceeded")
if not budget.charge(costs.MALLOC_PER_BYTE * len(enc)):
return None
return Atom(enc)
else:
return Error("add requires atoms")
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_sub(BinOpcode):
@staticmethod
def initial_state():
return Cons(Atom(0), Atom(0))
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.ARITH_ARG):
return None
if not right.is_atom():
return Error("sub requires atoms")
# The marker fold stores the minuend without scanning it, so
# it carries the base charge alone.
if left.is_cons() and left.val1.is_nil():
return Cons(Atom(1), right.bumpref())
minuend = left.val2 if left.is_cons() else left
if not budget.charge(costs.ARITH_PER_BYTE * (minuend.val1 + right.val1)):
return None
enc = int_to_bytes(minuend.as_int() - right.as_int())
cap = cls.size_cap()
if cap is not None and len(enc) > cap:
return Error("element size limit exceeded")
if not budget.charge(costs.MALLOC_PER_BYTE * len(enc)):
return None
return Atom(enc)
@classmethod
def finish(cls, budget, intstate, state):
if state.is_cons():
# The negation re-encodes the stored minuend: base, scan
# and allocation charges like any other fold of this
# family, plus the delivered result object's memory
# charge.
stored = state.val2
if not budget.charge(costs.ARITH_ARG + costs.ELEMENT_ALLOC
+ costs.ARITH_PER_BYTE * stored.val1):
return None
enc = int_to_bytes(0 - stored.as_int())
cap = cls.size_cap()
if cap is not None and len(enc) > cap:
return Error("element size limit exceeded")
if not budget.charge(costs.MALLOC_PER_BYTE * len(enc)):
return None
return Atom(enc)
else:
# A folded-past-the-marker state is the running
# difference, delivered like the other arithmetic folds.
return cls.finish_escape(budget, state)
class op_mul(BinOpcode):
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.ARITH_ARG):
return None
if left.is_atom() and right.is_atom():
# The schoolbook product runs one pass per limb of one
# operand over the other: the divided byte product plus
# a per-pass overhead linear in the wider operand.
if not budget.charge(costs.mul_fold_work(left.val1, right.val1)):
return None
enc = int_to_bytes(left.as_int() * right.as_int())
cap = cls.size_cap()
if cap is not None and len(enc) > cap:
return Error("element size limit exceeded")
if not budget.charge(costs.MALLOC_PER_BYTE * len(enc)):
return None
return Atom(enc)
else:
return Error("mul requires atoms")
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_mod(FixOpcode):
min_args = max_args = 2
@classmethod
def operation(cls, budget, num, den):
if not budget.charge(costs.MOD_BASE):
return None
if not num.is_atom() or not den.is_atom():
return Error("mod requires atoms")
# Charged before the divisor decode, so the by-zero error
# pays the full division charge: the zero test itself reads
# the whole operand. Long division runs one pass per quotient
# limb, the same divided-product-plus-limb shape as
# multiplication.
work = (costs.MOD_PER_BYTE * (num.val1 + den.val1)
+ costs.MULDIV_LIMB_PER_BYTE * max(num.val1, den.val1)
+ (num.val1 * den.val1) // costs.MUL_PRODUCT_DIV)
if not budget.charge(work):
return None
if den.as_int() == 0:
return Error("mod: attempted div by 0")
enc = int_to_bytes(num.as_int() % den.as_int())
if not budget.charge(costs.MALLOC_PER_BYTE * len(enc)):
return None
return Atom(enc)
class op_lt_num(BinOpcode):
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.COMPARE_ARG):
return None
# Rejected ahead of the failed-chain shortcut, so whether an
# application is valid never depends on the values of earlier
# arguments.
if right.is_func():
return Error("<: cannot compare a function object")
if left.is_nil():
# failed already
return left.bumpref()
if not right.is_atom():
return Atom(0)
if left.is_cons():
# Both operands are decoded in full before comparing.
work = costs.LT_NUM_PER_BYTE * (left.val2.val1 + right.val1)
if not budget.charge(work):
return None
if left.val2.as_int() >= right.as_int():
return Atom(0)
return Cons(Atom(1), right.bumpref())
@staticmethod
def finish(budget, intstate, state):
if state.is_atom():
return state.bumpref()
else:
return state.val1.bumpref()
class op_i(FixOpcode):
min_args = 1
max_args = 3
@classmethod
def operation(cls, budget, c, t=None, e=None):
if not budget.charge(costs.CONTROL_BASE):
return None
# A function object may only be bound, passed on or applied.
# Branch selection examines the condition, so a function
# object there is an error. The branch values are passed on
# unexamined, so they may be function objects.
if c.is_func():
return Error("i: condition is a function object")
if c.is_nil():
return e.bumpref() if e is not None else c.bumpref()
else:
return t.bumpref() if t is not None else Atom(1)
class IntStateOpcode(Opcode):
@classmethod
@final
def argument(cls, budget, int_state, state, arg):
assert state.is_nil()
next_state = cls.update_state(budget, int_state, arg)
if next_state is None:
# a charge failed and latched the budget
return (None, None)
if isinstance(next_state, Element):
assert next_state.is_error()
return (next_state, None)
return (state.bumpref(), next_state)
@classmethod
@final
def finish(cls, budget, int_state, state):
assert state.is_nil()
return cls.final_state(budget, int_state)
@classmethod
def update_state(cls, budget, int_state, arg):
raise NotImplementedError
@classmethod
def final_state(cls, budget, int_state):
raise NotImplementedError
class op_sha256(IntStateOpcode):
digest_size = 32
@classmethod
def initial_int_state(cls):
return hashlib.sha256()
@classmethod
def update_state(cls, budget, int_state, arg):
# The argument charge precedes the shape check: rejecting a
# list is fold work too.
if not budget.charge(costs.HASH_ARG):
return None
if not arg.is_atom():
return Error("cannot hash list")
if not budget.charge(costs.HASH_PER_BYTE * arg.val1):
return None
h = int_state.copy()
h.update(arg.val2)
return h
@classmethod
def final_state(cls, budget, int_state):
# One charge covers finalization, including the double-hash
# opcodes' second compression pass, plus the digest atom's
# allocation, spent here once so every hash opcode only
# overrides the digest hook.
if not budget.charge(costs.HASH_BASE + costs.MALLOC_PER_BYTE * cls.digest_size):
return None
return Atom(cls.digest(int_state))
@classmethod
def digest(cls, int_state):
return int_state.digest()
class op_ripemd160(op_sha256):
digest_size = 20
@classmethod
def initial_int_state(cls):
return ripemd160.hasher()
class op_hash160(op_sha256):
digest_size = 20
@classmethod
def digest(cls, int_state):
x = ripemd160.hasher()
x.update(int_state.digest())
return x.digest()
class op_hash256(op_sha256):
digest_size = 32
@classmethod
def digest(cls, int_state):
x = hashlib.sha256()
x.update(int_state.digest())
return x.digest()
class op_rc(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.RC_ARG):
return None
if left.is_cons():
return Cons(left.val1.bumpref(), Cons(right.bumpref(), left.val2.bumpref()))
else:
return Cons(left.bumpref(), right.bumpref())
@classmethod
def finish(cls, budget, intstate, state):
if state.is_cons():
return state.val2.bumpref()
else:
return state.bumpref()
class op_b(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
# One charge per argument covers the amortized carry merges
# of the binary counter, time and merge-cons memory both.
# The finish conses charge at finish instead: a shared
# binding can run the finish once per finalise, so memory
# paid per argument here could be escaped many times there.
if not budget.charge(costs.B_ARG):
return None
if left.is_nil():
return Cons(Cons(right.bumpref(), Atom(0)), Atom(1))
else:
assert left.is_cons() and left.val1.is_cons() and left.val2.is_atom()
n = left.val2.as_int()
n_next = n + 1
v = right.bumpref()
m = left.val1
while n % 2 == 1:
assert m.is_cons()
n //= 2
v = Cons(m.val1.bumpref(), v)
m = m.val2
return Cons(Cons(v, m.bumpref()), Atom(n_next))
@classmethod
def finish(cls, budget, intstate, state):
if state.is_nil():
return state.bumpref()
else:
assert state.is_cons() and state.val1.is_cons() and state.val2.is_atom()
l = state.val1.val1.bumpref()
rest = state.val1.val2
while rest.is_cons():
# Each finish cons escapes into the delivered tree,
# and this finish runs once per finalise of a shared
# binding over the same unchanged pending chain, so
# its memory charge lands here per cons, charged
# before the build with early exit, never amortized
# into the per-argument constant that a re-finalise
# would not pay again.
if not budget.charge(costs.ELEMENT_ALLOC):
l.deref()
return None
l = Cons(rest.val1.bumpref(), l)
rest = rest.val2
assert rest.is_nil()
return l
class op_h(FixOpcode):
min_args = max_args = 1
@classmethod
def operation(cls, budget, lst):
if not budget.charge(costs.CONTROL_BASE):
return None
if not lst.is_cons():
return Error("not a list")
return lst.val1.bumpref()
class op_t(FixOpcode):
min_args = max_args = 1
@classmethod
def operation(cls, budget, lst):
if not budget.charge(costs.CONTROL_BASE):
return None
if not lst.is_cons():
return Error("not a list")
return lst.val2.bumpref()
class op_l(FixOpcode):
min_args = max_args = 1
@classmethod
def operation(cls, budget, lst):
if not budget.charge(costs.CONTROL_BASE):
return None
# A function object is neither an atom nor a pair, so the
# shape question has no honest answer and errors instead of
# picking one.
if lst.is_func():
return Error("l: argument is a function object")
return Atom(1 if lst.is_cons() else 0)
class op_nand(BinOpcode):
# aka is any false?
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.LOGIC_ARG):
return None
# The truth test examines the argument, and a function object
# is neither nil nor a value, so it is an error rather than
# silently true.
if right.is_func():
return Error("notall: argument is a function object")
if right.is_nil():
return Atom(1)
else:
return left.bumpref()
class op_and(BinOpcode):
# aka are all true?
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.LOGIC_ARG):
return None
# Same rule as notall: a truth test on a function object is
# an error.
if right.is_func():
return Error("all: argument is a function object")
if right.is_nil():
return Atom(0)
else:
return left.bumpref()
class op_or(BinOpcode):
# aka are any true?
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.LOGIC_ARG):
return None
# Same rule as notall: a truth test on a function object is
# an error.
if right.is_func():
return Error("any: argument is a function object")
if not right.is_nil():
return Atom(1)
else:
return left.bumpref()
class op_or_bytes(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.BITWISE_ARG):
return None
if not right.is_atom():
return Error("or_bytes: argument must be atom")
wider = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * max(left.val1, right.val1)
if not budget.charge(wider):
return None
out = bytearray(max(left.val1, right.val1))
for i,e in enumerate(left.val2):
out[i] = e
for i,e in enumerate(right.val2):
out[i] |= e
return Atom(bytes(out))
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_xor_bytes(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.BITWISE_ARG):
return None
if not right.is_atom():
return Error("xor_bytes: argument must be atom")
wider = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * max(left.val1, right.val1)
if not budget.charge(wider):
return None
out = bytearray(max(left.val1, right.val1))
for i,e in enumerate(left.val2):
out[i] = e
for i,e in enumerate(right.val2):
out[i] ^= e
return Atom(bytes(out))
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_and_bytes(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.BITWISE_ARG):
return None
if not right.is_atom():
return Error("and_bytes: argument must be atom")
# The nil-state passthrough copies and allocates nothing, so
# it carries no size charge.
if left.is_nil():
return right.bumpref()
else:
wider = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * max(left.val1, right.val1)
if not budget.charge(wider):
return None
out = bytearray((0 for _ in range(max(left.val1, right.val1))))
for i,(el, er) in enumerate(zip(left.val2, right.val2)):
out[i] = el & er
return Atom(bytes(out))
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_nand_bytes(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.BITWISE_ARG):
return None
if not right.is_atom():
return Error("nand_bytes: argument must be atom")
wider = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * max(left.val1, right.val1)
if not budget.charge(wider):
return None
out = bytearray((255 for _ in range(max(left.val1, right.val1))))
for i,e in enumerate(left.val2):
out[i] = (e ^ 255)
for i,e in enumerate(right.val2):
out[i] &= e
for i in range(len(out)):
out[i] ^= 255
return Atom(bytes(out))
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_shift(FixOpcode):
min_args = max_args = 2
@classmethod
def operation(cls, budget, inp, n):
if not budget.charge(costs.SHIFT_BASE):
return None
if not isinstance(inp, Atom) or not isinstance(n, Atom):
return Error("shift: expects atomic arguments")
if not budget.charge(costs.atom_scan(n.val1)):
return None
delta = n.as_int()
if delta == 0:
return inp.bumpref()
# The output size bound: prepended zeros, one push per input
# byte and the final overflow byte for a left shift, at most
# one byte per input byte plus the overflow byte for a right
# shift. The bound is what gets charged, not the emitted
# length.
if delta > 0:
out_size = delta // 8 + inp.val1 + 1
cap = cls.size_cap()
if cap is not None and out_size > cap:
return Error("element size limit exceeded")
else:
out_size = inp.val1 + 1
if not budget.charge((costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * out_size):
return None
bb = bytearray(delta//8) if delta > 0 else bytearray()
overflow = 0
if delta > 0:
delta %= 8
for b in inp.val2:
if delta < -8:
delta += 8
continue
elif delta < 0:
overflow = b >> (-delta)
delta += 8
continue
x = (b << delta) + overflow
bb.append(x & 0xFF)
overflow = x >> 8
bb.append(overflow)
return Atom(bytes(bb))
class op_eq(BinOpcode):
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.COMPARE_ARG):
return None
# Rejected ahead of the failed-chain shortcut, so whether an
# application is valid never depends on the values of earlier
# arguments.
if right.is_func():
return Error("=: cannot compare a function object")
if left.is_nil():
# failed already
return left.bumpref()
elif not right.is_atom():
# pairs aren't compared with this opcode
return Atom(0)
elif left.is_atom():
# first arg, nothing to be equal to
return Cons(right.bumpref(), left.bumpref())
else:
assert left.is_cons() and left.val1.is_atom()
# The scan is charged on the argument's width whether or
# not the widths match, one rule instead of two.
if not budget.charge(costs.COMPARE_PER_BYTE * right.val1):
return None
if left.val1.val1 != right.val1 or left.val1.val2 != right.val2:
return Atom(0)
else:
return left.bumpref()
@staticmethod
def finish(budget, intstate, state):
if state.is_cons():
return state.val2.bumpref()
else:
return state.bumpref()
class op_bigeq(BinOpcode):
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.COMPARE_ARG):
return None
# Rejected ahead of the failed-chain shortcut, so whether an
# application is valid never depends on the values of earlier
# arguments. Function objects nested inside an argument are
# rejected where the walk below reaches them.
if right.is_func():
return Error("===: cannot compare a function object")
if left.is_nil():
# failed already
return left.bumpref()
elif left.is_atom():
# first arg, nothing to be equal to
return Cons(right.bumpref(), left.bumpref())
else:
# Charged per node pair inside the walk with early exit:
# the walk follows structure, not memory, so a small
# shared tree can visit exponentially many pairs. The
# byte scan is charged for equal-width atom pairs only,
# after the free width comparison.
chk = [(left.val1, right)]
while chk:
if not budget.charge(costs.BIGEQ_PER_NODE):
return None
a, b = chk.pop()
# The walk examines both nodes, so a function object
# on either side is an error, not an inequality. A
# node the early exit never reaches is never examined,
# the same boundary the charged serializer has.
if a.is_func() or b.is_func():
return Error("===: cannot compare a function object")
if a.is_atom():
if not b.is_atom() or a.val1 != b.val1:
return Atom(0)
if not budget.charge(costs.COMPARE_PER_BYTE * a.val1):
return None
if a.val2 != b.val2:
return Atom(0)
elif b.is_atom():
return Atom(0)
else:
assert a.is_cons() and b.is_cons()
chk.append((a.val1, b.val1))
chk.append((a.val2, b.val2))
return left.bumpref()
@staticmethod
def finish(budget, intstate, state):
if state.is_cons():
return state.val2.bumpref()
else:
return state.bumpref()
class op_strlen(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.STRLEN_ARG):
return None
if not right.is_atom():
return Error(f"strlen: not an atom {right}")
return Atom(left.as_int() + len(right.val2))
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_cat(BinOpcode):
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.CAT_ARG):
return None
if not right.is_atom():
return Error(f"cat: not an atom {right}")
cap = cls.size_cap()
if cap is not None and left.val1 + right.val1 > cap:
return Error("element size limit exceeded")
# The whole state is recopied every fold, so charging the
# copy and the allocation per fold prices the quadratic
# self-append shape with no special case.
joint = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * (left.val1 + right.val1)
if not budget.charge(joint):
return None
return Atom(left.val2 + right.val2)
@staticmethod
def finish(budget, int_state, state):
return BinOpcode.finish_escape(budget, state)
class op_substr(FixOpcode):
min_args = 0
max_args = 3
@classmethod
def operation(cls, budget, el=None, start=None, end=None):
if not budget.charge(costs.SUBSTR_BASE):
return None
if el is None:
return Atom(0)
if not el.is_atom():
return Error("substr: cannot take substr of non-atom")
if start is None:
return el.bumpref()
if not start.is_atom():
return Error("substr: start must be atom")
if not budget.charge(costs.atom_scan(start.val1)):
return None
start = start.as_int()
if end is not None and not end.is_atom():
return Error("substr: end must be atom")
if end is None:
end = el.val1
else:
if not budget.charge(costs.atom_scan(end.val1)):
return None
end = end.as_int()
# The identity and nil shortcuts copy and allocate nothing,
# so only the copied range carries a size charge.
if start == 0 and end >= el.val1:
return el.bumpref()
if start > el.val1:
return Atom(0)
low = max(start + el.val1, 0) if start < 0 else start
high = max(end + el.val1, 0) if end < 0 else min(end, el.val1)
if low >= high:
return Atom(0)
copied = (costs.COPY_PER_BYTE + costs.MALLOC_PER_BYTE) * (high - low)
if not budget.charge(copied):
return None
return Atom(el.val2[low:high])
class op_lt_str(BinOpcode):
@staticmethod
def initial_state():
return Atom(1)
@classmethod
def binop(cls, budget, left, right):
if not budget.charge(costs.COMPARE_ARG):
return None
# Rejected ahead of the failed-chain shortcut, so whether an
# application is valid never depends on the values of earlier
# arguments.
if right.is_func():
return Error("<s: cannot compare a function object")
if left.is_nil():
# failed already
return left.bumpref()
if not right.is_atom():
return Atom(0)
if left.is_cons():
# The lexicographic scan stops at the shorter operand,
# the argument's width is the deterministic upper bound.
if not budget.charge(costs.COMPARE_PER_BYTE * right.val1):
return None
if left.val2.val2 >= right.val2:
return Atom(0)
return Cons(Atom(1), right.bumpref())
@staticmethod
def finish(budget, intstate, state):
if state.is_atom():
return state.bumpref()
else:
return state.val1.bumpref()
'''
# op_mod / op_divmod
class op_div_u64(Operator):
def __init__(self):
self.i = None
def argument(self, el):
if not el.is_atom(): raise Exception("div: arguments must be atoms")
n = el.atom_as_u64()
el.deref()
if self.i is None:
self.i = n
else:
## if el >= 2**64 should we just set i to 0?
if n == 0:
raise Exception("div: attempted div by 0")
self.i //= n
def finish(self):
if self.i is None:
raise Exception("div: missing arguments")
return Atom(self.i)
'''
class op_list_read(FixOpcode):
min_args = max_args = 1
@classmethod
def operation(cls, budget, el):
if not budget.charge(costs.RD_BASE):
return None