-
Notifications
You must be signed in to change notification settings - Fork 0
/
hcast.py
executable file
·1349 lines (1020 loc) · 35.7 KB
/
hcast.py
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 string
import math
from dataclasses import dataclass
import hrminstr as hrmi
from hcexceptions import HCTypeError
class HCInternalError(Exception):
pass
# Generate a unique name according using an index
def generate_name(idx):
name = ""
while True:
idx, rem = divmod(idx, 26)
name += string.ascii_lowercase[rem]
if idx == 0:
return name
# Generate a function which will validate an expression
# Function returns a tuple of:
# (
# AbstractExpr to replace this expression with. May be the same expression,
# List of statements to inject before the containing statement in order to prepare for this expression.
# )
def get_validate_func(method_name):
def validate_func(expr, namespace):
if not hasattr(expr, method_name):
raise HCInternalError("Expression cannot be validated", expr)
new_expr, injected_stmts = getattr(expr, method_name)(namespace)
# Individual validate functions may return new_expr=None to mean, don't replace anything
if new_expr is None:
new_expr = expr
elif not isinstance(new_expr, AbstractExpr):
raise HCInternalError("Unexpected expression replacement type")
# Individual validate functions may return a single AbstractLine, None, or an iterable of AbstractLines
if isinstance(injected_stmts, AbstractLine):
injected_stmts = [injected_stmts]
elif injected_stmts is None:
injected_stmts = []
elif all(isinstance(s, AbstractLine) for s in injected_stmts):
injected_stmts = [*injected_stmts]
else:
raise HCInternalError("Unexpected injected statements type", injected_stmts)
return (new_expr, injected_stmts)
return validate_func
validate_expr_branchable = get_validate_func("validate_branchable")
validate_expr = get_validate_func("validate")
class AbstractLine:
__slots__ = [
"block",
"indent",
"lineno",
]
def __init__(self, indent="", lineno=None):
self.indent = indent
self.lineno = lineno
# Get list of memory values and variable assigned by this statement
# Defaults to returning an empty tuple, since most statements don't add any
def get_memory_map(self):
return ()
# Create a block of HRM instructions to represent this line
# Assign to self.block
# Doesn't need to assign_next yet
def create_block(self):
raise NotImplementedError("AbstractLine.createBlock", self)
# Fetch a list of variables used in this line
def get_namespace(self):
raise NotImplementedError("AbstractLine.get_namespace", self)
# eg: init zero @ 10
# eg: init zero = 0 @ 10
class InitialValueDeclaration(AbstractLine):
__slots__ = [
"name",
"loc",
"value",
]
def create_block(self):
# Empty block
self.block = hrmi.Block(self.lineno)
def get_memory_map(self):
return (MemoryLocation(self.name, self.loc, self.value),)
def __init__(self, loc, *, name=None, value=None):
super().__init__("")
self.loc = loc
self.name = name
self.value = value
# Assign a unique name if no name is provided
if self.name is None:
self.name = "init!" + repr(self.loc)
def get_namespace(self):
return Namespace(self.name)
def validate(self, namespace):
return None
def __repr__(self):
s = "InitialValueDeclaration(" + repr(self.loc)
if self.name is not None:
s += ", name=" + repr(self.name)
if self.value is not None:
s += ", value=" + repr(self.value)
s += ")"
return s
@dataclass
class MemoryLocation:
name: str
loc: int
value: int
# Sequence of AbstractLine objects, to be run in order
class StatementList:
__slots__ = [
"stmts",
"first_block",
"last_block",
]
def append(self, stmt):
self.stmts.append(stmt)
def create_blocks(self):
if len(self.stmts) == 0:
self.first_block = self.last_block = hrmi.Block()
return
for stmt in self.stmts:
stmt.create_block()
# Assign each to jump to the next one
for i in range(1, len(self.stmts)):
self.stmts[i - 1].block.assign_next(self.stmts[i].block)
# Last block is left with no jump specified
self.first_block = self.stmts[0].block
self.last_block = self.stmts[-1].block
# Look up memory locations of variables specified by the program
# Returns as an iterable of MemoryLocation objects
def get_memory_map(self):
memory_by_name = {}
memory_by_loc = {}
for stmt in self.stmts:
new_memory = stmt.get_memory_map()
for mem in new_memory:
if mem.name in memory_by_name:
raise HCTypeError(f"Variable '{mem.name}' declared twice "
f"on line {stmt.lineno}")
if mem.loc in memory_by_loc:
raise HCTypeError(f"Multiple variables declared at floor "
f"address {mem.loc} on line {stmt.lineno}")
memory_by_name[mem.name] = mem
memory_by_loc[mem.loc] = mem
return memory_by_name.values()
# Some expressions will require processing before they can be converted to instructions
def validate_structure(self, namespace):
i = 0
while i < len(self.stmts):
stmt = self.stmts[i]
result = stmt.validate(namespace)
# If the validation function returns a Statement, replace the current one
if isinstance(result, AbstractLine):
self.stmts[i] = result
# If the validation returns a list of statements, replace the current one with all of them
elif (isinstance(result, list)
and all(isinstance(s, AbstractLine) for s in result)):
self.stmts[i:i+1] = result
i += len(result) - 1
# If the validation function returns None, accept the validation with no modifications
elif result is None:
pass
else:
raise HCInternalError("Unexpected validation function return type", result)
i += 1
# Fetch a list of variable names used in this program tree
def get_namespace(self):
ns = Namespace()
for stmt in self.stmts:
stmt_ns = stmt.get_namespace()
ns.merge(stmt_ns)
return ns
def get_last_stmt(self):
if len(self.stmts) == 0:
return None
return self.stmts[-1]
def get_entry_block(self):
return self.first_block
def get_exit_blocks(self):
return self.last_block.get_exit_blocks()
def __init__(self, stmts=None):
self.stmts = stmts
if self.stmts is None:
self.stmts = []
def __repr__(self):
return f"StatementList({repr(self.stmts)})"
# Abstract class for lines/statements which contain an indented body block after
# them.
class StmtWithBody(AbstractLine):
def get_body(self):
raise NotImplementedError("StmtWithBody.get_body", self)
# forever loop
class Forever(StmtWithBody):
__slots__ = ["body"]
def __init__(self, body=None):
self.body = body
if self.body is None:
self.body = StatementList()
def get_body(self):
return self.body
def create_block(self):
self.body.create_blocks()
# Assign the last to jump back to the first
# TODO: handle empty body properly
self.body.stmts[-1].block.assign_next(self.body.stmts[0].block)
self.block = hrmi.ForeverBlock(self.body.stmts[0].block)
def get_namespace(self):
return self.body.get_namespace()
def validate(self, namespace):
self.body.validate_structure(namespace)
return None
def __repr__(self):
return f"Forever({repr(self.body)})"
class While(StmtWithBody):
__slots__ = [
"condition",
"body",
]
def __init__(self, cond, body=None):
super().__init__()
self.condition = cond
self.body = body if body is not None else StatementList()
def get_body(self):
return self.body
def get_namespace(self):
ns = self.condition.get_namespace()
ns.merge(self.body.get_namespace())
return ns
def validate(self, namespace):
self.condition, injected_stmts_cond = validate_expr_branchable(
self.condition, namespace)
if len(injected_stmts_cond) > 0:
self.condition = InlineStatementExpr(
injected_stmts_cond, self.condition)
self.body.validate_structure(namespace)
return None
def create_block(self):
self.body.create_blocks()
exit_block = hrmi.Block(self.lineno)
cond_block = self.condition.create_branch_block(
self.body, exit_block, self.lineno)
for blk in self.body.get_exit_blocks():
blk.assign_next(cond_block.get_entry_block())
self.block = hrmi.CompoundBlock(cond_block, [exit_block])
def __repr__(self):
return (type(self).__name__ + "("
+ repr(self.condition) + ", "
+ repr(self.body) +")")
class If(StmtWithBody):
__slots__ = [
"condition",
"then_block",
"else_block",
]
def __init__(self, cond, then_block=None, else_block=None):
super().__init__()
self.condition = cond
self.then_block = then_block
self.else_block = else_block
if self.then_block is None:
self.then_block = StatementList()
def get_body(self):
# This always returns the then_block. This function is used by the phase
# 2 parser, which handles else statements specially.
return self.then_block
def create_block(self):
# Fill in empty else block
if self.else_block is None:
self.else_block = StatementList()
self.then_block.create_blocks()
self.else_block.create_blocks()
self.block = self.condition.create_branch_block(
self.then_block, self.else_block, self.lineno)
def get_namespace(self):
ns = self.condition.get_namespace()
ns.merge(self.then_block.get_namespace())
if self.else_block is not None:
ns.merge(self.else_block.get_namespace())
return ns
def validate(self, namespace):
self.condition, injected_stmts = validate_expr_branchable(self.condition, namespace)
self.then_block.validate_structure(namespace)
if self.else_block is not None:
self.else_block.validate_structure(namespace)
injected_stmts.append(self)
return injected_stmts
def __repr__(self):
s = "If(" + repr(self.condition)
s += ", " + repr(self.then_block)
if self.else_block is not None:
s += ", " + repr(self.else_block)
return s + ")"
# Pseudo node used in parsing
class Else(AbstractLine):
def __repr__(self):
return "Else()"
class AbstractLineWithExpr(AbstractLine):
__slots = ["expr"]
def __init__(self, expr, indent=""):
super().__init__(indent)
self.expr = expr
def validate(self, namespace):
self.expr, injected_stmts = validate_expr(self.expr, namespace)
injected_stmts.append(self)
return injected_stmts
def get_namespace(self):
return self.expr.get_namespace()
# output <expr>
class Output(AbstractLineWithExpr):
__slots__ = ["expr"]
def create_block(self):
self.block = hrmi.Block(self.lineno)
self.expr.add_to_block(self.block)
self.block.add_instruction(hrmi.Output())
def __repr__(self):
return ("Output("
+ repr(self.expr) + ", "
+ repr(self.indent) + ")")
class ExprLine(AbstractLineWithExpr):
def create_block(self):
self.block = hrmi.Block(self.lineno)
self.expr.add_to_block(self.block)
def __repr__(self):
return ("ExprLine("
+ repr(self.expr) + ", "
+ repr(self.indent) + ")")
class AbstractExpr:
# Add instructions to load this expression into the accumulator (hands),
# along with any side-effects
def add_to_block(self, block):
raise NotImplementedError("AbstractExpr.add_to_block", self)
def validate(self, namespace):
raise NotImplementedError("AbstractExpr.validate", self)
def has_side_effects(self):
raise NotImplementedError("AbstractExpr.has_side_effects", self)
def get_namespace(self):
raise NotImplementedError("AbstractExpr.get_namespace", self)
# Fetch the return type of this expression
def get_type(self):
if hasattr(self, "hctype"):
return self.hctype
raise NotImplementedError("AbstractExpr.get_type", self)
# eg. name = expr
class Assignment(AbstractExpr):
__slots__ = [
"name",
"expr",
]
def add_to_block(self, block):
self.expr.add_to_block(block)
block.add_instruction(hrmi.Save(self.name))
def __init__(self, name, expr):
self.name = name
self.expr = expr
def validate(self, namespace):
self.expr, injected_stmts = validate_expr(self.expr, namespace)
return (None, injected_stmts)
def get_namespace(self):
ns = self.expr.get_namespace()
ns.add_name(self.name)
return ns
def __repr__(self):
return ("Assignment("
+ repr(self.name) + ", "
+ repr(self.expr) + ")")
class Primitive(AbstractExpr):
__slots__ = ["value"]
def __init__(self, value):
self.value = value
@classmethod
def get_type(cls):
return cls
def get_namespace(self):
return Namespace()
def has_side_effects(self):
return False
def __repr__(self):
return (type(self).__name__ + "(" + repr(self.value) + ")")
class Number(Primitive):
def validate(self, namespace):
return (None, None)
def add_to_block(self, block):
block.add_instruction(hrmi.LoadConstant(self.value))
# Boolean value.
# Currently not directly producable by the source code
class Boolean(Primitive):
def validate_branchable(self, namespace):
return (None, None)
def create_branch_block(self, then_block, else_block, lineno=None):
block = then_block if self.value else else_block
return hrmi.CompoundBlock(
block.get_entry_block(), block.get_exit_blocks())
def is_zero(expr):
return isinstance(expr, Number) and expr.value == 0
class VariableRef(AbstractExpr):
__slots__ = ["name"]
hctype = Number
def add_to_block(self, block):
block.add_instruction(hrmi.Load(self.name))
def __init__(self, name):
self.name = name
def validate(self, namespace):
return (None, None)
def has_side_effects(self):
return False
def get_namespace(self):
return Namespace(self.name)
def __repr__(self):
return ("VariableRef("
+ repr(self.name) + ")")
class Input(AbstractExpr):
hctype = Number
def add_to_block(self, block):
block.add_instruction(hrmi.Input())
def validate(self, namespace):
return (None, None)
def has_side_effects(self):
return True
def get_namespace(self):
return Namespace()
def __repr__(self):
return "Input()"
# Any operator with a left and right operand
class AbstractBinaryOperator(AbstractExpr):
__slots__ = [
"left",
"right",
]
def __init__(self, left, right):
self.left = left
self.right = right
def has_side_effects(self):
return self.left.has_side_effects() or self.right.has_side_effects()
def get_namespace(self):
ns_l = self.left.get_namespace()
ns_r = self.right.get_namespace()
ns_l.merge(ns_r)
return ns_l
def __repr__(self):
return (type(self).__name__ + "("
+ repr(self.left) + ", "
+ repr(self.right) + ")")
class AbstractAdditiveOperator(AbstractBinaryOperator):
hctype = Number
# True in subclasses if left and right operands may
# be swapped without affecting the operation.
commutative = False
# True in subclasses if the right operand is negated by the operation
negate_right_operand = False
# True in subclasses if this variable evaluates to pseudo instructions
pseudo = False
def validate(self, namespace):
injected_stmts = []
# Recurse on both operands
self.left, left_injected = validate_expr(self.left, namespace)
injected_stmts.extend(left_injected)
self.right, right_injected = validate_expr(self.right, namespace)
injected_stmts.extend(right_injected)
# Handle constant values
if isinstance(self.left, Number) and isinstance(self.right, Number):
return (self.eval_static(self.left.value, self.right.value),
injected_stmts)
if is_zero(self.right):
return (self.left, injected_stmts)
# Handle a single constant value
if isinstance(self.left, Number) and self.commutative:
self.left, self.right = self.right, self.left
if isinstance(self.right, Number) and not self.pseudo:
added_name = namespace.get_unique_name()
injected_stmts.append(ExprLine(Assignment(added_name, self.left)))
injected_stmts.extend(ExprLine(
(Decrement if self.negate_right_operand
else Increment)(added_name))
for _ in range(self.right.value))
return (VariableRef(added_name), injected_stmts)
if not self.negate_right_operand and is_zero(self.left):
return (self.right, injected_stmts)
if not self.pseudo and isinstance(self.right, VariableRef):
return (None, injected_stmts)
# If the right hand side is another additive operator,
# rotate to put the child add/subtract on the left.
# Relies on associativity on additive operations
if (not self.pseudo
and isinstance(self.right, AbstractAdditiveOperator)
and not self.right.pseudo):
# a + (b + c) -> (a + b) + c
# a + (b - c) -> (a + b) - c
# a - (b + c) -> (a - b) - c
# a - (b - c) -> (a - b) + c
a = self.left
b = self.right.left
c = self.right.right
negate_b = self.negate_right_operand
negate_c = self.negate_right_operand != self.right.negate_right_operand
l_expr = (Subtract if negate_b else Add)(a, b)
expr = (Subtract if negate_c else Add)(l_expr, c)
expr, rot_stmts = validate_expr(expr, namespace)
injected_stmts.extend(rot_stmts)
return expr, injected_stmts
# Swap operands if left operand is a variable reference.
if self.commutative and isinstance(self.left, VariableRef):
self.left, self.right = self.right, self.left
return (self, injected_stmts)
# Must move the right operand out to a new variable.
# Must take into account side effects, as this operation
# may change the order of evaluation.
if self.left.has_side_effects() and self.right.has_side_effects():
if self.commutative:
self.left, self.right = self.right, self.left
else:
left_name = namespace.get_unique_name()
left_assign = ExprLine(Assignment(left_name, self.left))
injected_stmts.append(left_assign)
self.left = VariableRef(left_name)
right_name = namespace.get_unique_name()
right_assign = ExprLine(Assignment(right_name, self.right))
injected_stmts.append(right_assign)
self.right = VariableRef(right_name)
return (None, injected_stmts)
# Evaluate the value of the expression given statically
def eval_static(self, left, right):
raise NotImplementedError("AbstractAdditiveOperator.eval_static",
self)
class Add(AbstractAdditiveOperator):
commutative = True
def add_to_block(self, block):
self.left.add_to_block(block)
if isinstance(self.right, VariableRef):
block.add_instruction(hrmi.Add(self.right.name))
else:
raise HCInternalError("Unable to directly add right operand",
self.right)
def eval_static(self, left, right):
return Number(left + right)
class Subtract(AbstractAdditiveOperator):
negate_right_operand = True
def add_to_block(self, block):
self.left.add_to_block(block)
if isinstance(self.right, VariableRef):
block.add_instruction(hrmi.Subtract(self.right.name))
else:
raise HCInternalError("Unable to directly subtract right operand",
self.right)
# Evaluate the value of the expression given statically
def eval_static(self, left, right):
return Number(left - right)
# Pseudo operator.
# Like subtraction, but may represent either (x - y) or (y - x) in cases
# where either is correct, but one may be more efficient than the other.
class Difference(AbstractAdditiveOperator):
commutative = True
pseudo = True
def add_to_block(self, block):
if not isinstance(self.left, VariableRef) or not isinstance(self.right, VariableRef):
raise HCInternalError("Unable to convert Difference "
+ "operator with non variable reference operands")
block.add_instruction(hrmi.Difference(self.left.name, self.right.name))
_primes = [2]
def get_primes():
for p in _primes:
yield p
i = _primes[-1]
while True:
i += 1
is_prime = True
for p in _primes:
quot, rem = divmod(i, p)
if rem == 0:
is_prime = False
break
if quot < p:
break
if is_prime:
_primes.append(i)
yield i
def prime_factors(n):
if n == 1:
return [1]
factors = []
primes = get_primes()
p = next(primes)
while n != 1:
quot, rem = divmod(n, p)
if rem == 0:
factors.append(p)
n = quot
elif quot < p:
factors.append(n)
break
else:
p = next(primes)
return factors
# Holds a strategy for multiplying up to a large number.
# Consists of a series of multiplications (factors),
# then a small addition (offset).
class MultiplicationStrategy:
__slots__ = [
"factors",
"offset",
# Value this strategy will multiply up to
"value",
# Estimated number of instructions taken
# to perform this multiplication.
"instructions",
]
def __init__(self, factors, offset):
self.factors = sorted(factors, reverse=True)
self.offset = offset
self.value = math.prod(factors) + offset
for i in range(len(self.factors)):
f = self.factors[i]
if f > 5 and f < self.value:
self.factors[i] = find_multiplication_strategy(f)
self.instructions = self.offset
for f in self.factors:
if isinstance(f, MultiplicationStrategy):
self.instructions += f.instructions
else:
self.instructions += f
def __str__(self):
return (" * ".join(f"({f})" if isinstance(f, MultiplicationStrategy)
else str(f) for f in self.factors)
+ (" + " + str(self.offset) if self.offset != 0 else ""))
# Lookup table for memoising multiplication stategies
_multiplication_stategies = {}
# Find the best strategy for multiplying by addition.
# Returns (a list of prime factors, and number to add at the end)
# Any value in the prime factors could be replaced
# with another tuple of a similar form.
def find_multiplication_strategy(n):
if n in _multiplication_stategies:
return _multiplication_stategies[n]
best_strategy = None
i = 0
while best_strategy is None or i < best_strategy.instructions:
product = n - i
factors = prime_factors(product)
strategy = MultiplicationStrategy(factors, i)
if (best_strategy is None
or strategy.instructions < best_strategy.instructions):
best_strategy = strategy
i += 1
_multiplication_stategies[n] = best_strategy
return best_strategy
# Nest repeated addition nodes
def nest_addition(expr, n):
if n == 0:
return Number(0)
if n == 1:
return expr
return Add(nest_addition(expr, n - 1), expr)
# Expand a multiplication strategy into its various additions and assignments.
# Returns (the new expression which holds the result of the multiplication,
# and a list of injected statements used in the calculation)
def expand_multiplication_strategy(strategy, expr, namespace):
if isinstance(strategy, int):
return (nest_addition(expr, strategy), [])
injected_stmts = []
working_product = expr
for fact in strategy.factors:
working_product, fact_stmts = expand_multiplication_strategy(
fact, working_product, namespace)
injected_stmts.extend(fact_stmts)
var_name = namespace.get_unique_name()
injected_stmts.append(ExprLine(Assignment(var_name, working_product)))
working_product = VariableRef(var_name)
offset_add = nest_addition(expr, strategy.offset)
final_add = Add(working_product, offset_add)
final_add, injected_final = validate_expr(final_add, namespace)
injected_stmts.extend(injected_final)
return (final_add, injected_stmts)
# Find an efficient way to multiply an expression by a constant using only addition.
# Returns (a new expression node, and a list of injected statements)
def validate_expr_mul_const(expr, n, namespace):
injected_stmts = []
if expr.has_side_effects() and n > 1:
var_name = namespace.get_unique_name()
new_assign = ExprLine(Assignment(var_name, expr))
injected_stmts.append(new_assign)
expr = VariableRef(var_name)
strategy = find_multiplication_strategy(n)
expanded_expr, expanded_stmts = (
expand_multiplication_strategy(strategy, expr, namespace))
injected_stmts.extend(expanded_stmts)
return (expanded_expr, injected_stmts)
class Multiply(AbstractBinaryOperator):
hctype = Number
def validate(self, namespace):
self.left, injected_stmts = validate_expr(self.left, namespace)
self.right, injected_stmts_right = validate_expr(self.right, namespace)
injected_stmts.extend(injected_stmts_right)
left_const = isinstance(self.left, Number)
right_const = isinstance(self.right, Number)
if left_const and right_const:
return (Number(self.left.value * self.right.value), None)
# Ensure any constant term is on the right
if left_const:
self.left, self.right = self.right, self.left
left_const, right_const = right_const, left_const
if right_const and self.right.value == 0:
if self.left.has_side_effects():
injected_stmts.append(ExprLine(self.left))
return (Number(0), injected_stmts)
if right_const and self.right.value > 0:
expr, injected_stmts_mul = validate_expr_mul_const(
self.left, self.right.value, namespace)
injected_stmts.extend(injected_stmts_mul)
return (expr, injected_stmts)
# Expand to full multiplication algorithm
multiplicand_name = namespace.get_unique_name()
injected_stmts.append(ExprLine(
Assignment(multiplicand_name, self.left)))
self.left = VariableRef(multiplicand_name)
multiplier_name = namespace.get_unique_name()
injected_stmts.append(ExprLine(
Assignment(multiplier_name, self.right)))
self.right = VariableRef(multiplier_name)
product_name = namespace.get_unique_name()
injected_stmts.extend([
# Swap operands to ensure multiplier <= multiplicand
If(CompareLt(Subtract(VariableRef(multiplicand_name),
VariableRef(multiplier_name)), Number(0)), StatementList([
ExprLine(Assignment(product_name,
VariableRef(multiplicand_name))),
ExprLine(Assignment(multiplicand_name,
VariableRef(multiplier_name))),
ExprLine(Assignment(multiplier_name,
VariableRef(product_name))),
])),
ExprLine(Assignment(product_name, Number(0))),
While(CompareNe(VariableRef(multiplier_name), Number(0)),
StatementList([
ExprLine(Assignment(product_name, Add(VariableRef(product_name),
VariableRef(multiplicand_name)))),
ExprLine(Decrement(multiplier_name)),
])),
])
return (VariableRef(product_name), injected_stmts)
# Abstract class for both increment and decrement
class AbstractIncrement(AbstractExpr):
__slots__ = [
"name",
]
def __init__(self, name):
self.name = name
def get_namespace(self):
return Namespace(self.name)
def validate(self, namespace):
return (None, None)
def __repr__(self):
return (type(self).__name__ + "("
+ repr(self.name) + ")")
# Prefix increment
class Increment(AbstractIncrement):
def add_to_block(self, block):
block.add_instruction(hrmi.BumpUp(self.name))