-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
lnodes.py
1138 lines (868 loc) · 29.9 KB
/
lnodes.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
# Copyright (C) 2013-2023 Martin Sandve Alnæs, Chris Richardson
#
# This file is part of FFCx.(https://www.fenicsproject.org)
#
# SPDX-License-Identifier: LGPL-3.0-or-later
"""LNodes.
LNodes is intended as a minimal generic language description.
Formatting is done later, depending on the target language.
Supported:
Floating point (and complex) and integer variables and multidimensional arrays
Range loops
Simple arithmetic, +-*/
Math operations
Logic conditions
Comments
Not supported:
Pointers
Function Calls
Flow control (if, switch, while)
Booleans
Strings
"""
import numbers
from collections.abc import Sequence
from enum import Enum
from typing import Optional
import numpy as np
import ufl
class PRECEDENCE:
"""An enum-like class for operator precedence levels."""
HIGHEST = 0
LITERAL = 0
SYMBOL = 0
SUBSCRIPT = 2
NOT = 3
NEG = 3
MUL = 4
DIV = 4
ADD = 5
SUB = 5
LT = 7
LE = 7
GT = 7
GE = 7
EQ = 8
NE = 8
AND = 11
OR = 12
CONDITIONAL = 13
ASSIGN = 13
LOWEST = 15
def is_zero_lexpr(lexpr):
"""Check if an expression is zero."""
return (isinstance(lexpr, LiteralFloat) and lexpr.value == 0.0) or (
isinstance(lexpr, LiteralInt) and lexpr.value == 0
)
def is_one_lexpr(lexpr):
"""Check if an expression is one."""
return (isinstance(lexpr, LiteralFloat) and lexpr.value == 1.0) or (
isinstance(lexpr, LiteralInt) and lexpr.value == 1
)
def is_negative_one_lexpr(lexpr):
"""Check if an expression is negative one."""
return (isinstance(lexpr, LiteralFloat) and lexpr.value == -1.0) or (
isinstance(lexpr, LiteralInt) and lexpr.value == -1
)
def float_product(factors):
"""Build product of float factors.
Simplify ones and returning 1.0 if empty sequence.
"""
factors = [f for f in factors if not is_one_lexpr(f)]
if len(factors) == 0:
return LiteralFloat(1.0)
elif len(factors) == 1:
return factors[0]
else:
return Product(factors)
class DataType(Enum):
"""Representation of data types for variables in LNodes.
These can be REAL (same type as geometry),
SCALAR (same type as tensor), or INT (for entity indices etc.)
"""
REAL = 0
SCALAR = 1
INT = 2
BOOL = 3
NONE = 4
def merge_dtypes(dtypes: list[DataType]):
"""Promote dtype to SCALAR or REAL if either argument matches."""
if DataType.NONE in dtypes:
raise ValueError(f"Invalid DataType in LNodes {dtypes}")
if DataType.SCALAR in dtypes:
return DataType.SCALAR
elif DataType.REAL in dtypes:
return DataType.REAL
elif DataType.INT in dtypes:
return DataType.INT
elif DataType.BOOL in dtypes:
return DataType.BOOL
else:
raise ValueError(f"Can't get dtype for operation with {dtypes}")
class LNode:
"""Base class for all AST nodes."""
def __eq__(self, other):
"""Check for equality."""
return NotImplemented
def __ne__(self, other):
"""Check for inequality."""
return NotImplemented
class LExpr(LNode):
"""Base class for all expressions.
All subtypes should define a 'precedence' class attribute.
"""
dtype = DataType.NONE
def __getitem__(self, indices):
"""Get an item."""
return ArrayAccess(self, indices)
def __neg__(self):
"""Negate."""
if isinstance(self, LiteralFloat):
return LiteralFloat(-self.value)
if isinstance(self, LiteralInt):
return LiteralInt(-self.value)
return Neg(self)
def __add__(self, other):
"""Add."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return other
if is_zero_lexpr(other):
return self
if isinstance(other, Neg):
return Sub(self, other.arg)
return Add(self, other)
def __radd__(self, other):
"""Add."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return other
if is_zero_lexpr(other):
return self
if isinstance(self, Neg):
return Sub(other, self.arg)
return Add(other, self)
def __sub__(self, other):
"""Subtract."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return -other
if is_zero_lexpr(other):
return self
if isinstance(other, Neg):
return Add(self, other.arg)
if isinstance(self, LiteralInt) and isinstance(other, LiteralInt):
return LiteralInt(self.value - other.value)
return Sub(self, other)
def __rsub__(self, other):
"""Subtract."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return other
if is_zero_lexpr(other):
return -self
if isinstance(self, Neg):
return Add(other, self.arg)
return Sub(other, self)
def __mul__(self, other):
"""Multiply."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return self
if is_zero_lexpr(other):
return other
if is_one_lexpr(self):
return other
if is_one_lexpr(other):
return self
if is_negative_one_lexpr(other):
return Neg(self)
if is_negative_one_lexpr(self):
return Neg(other)
if isinstance(self, LiteralInt) and isinstance(other, LiteralInt):
return LiteralInt(self.value * other.value)
return Mul(self, other)
def __rmul__(self, other):
"""Multiply."""
other = as_lexpr(other)
if is_zero_lexpr(self):
return self
if is_zero_lexpr(other):
return other
if is_one_lexpr(self):
return other
if is_one_lexpr(other):
return self
if is_negative_one_lexpr(other):
return Neg(self)
if is_negative_one_lexpr(self):
return Neg(other)
return Mul(other, self)
def __div__(self, other):
"""Divide."""
other = as_lexpr(other)
if is_zero_lexpr(other):
raise ValueError("Division by zero!")
if is_zero_lexpr(self):
return self
return Div(self, other)
def __rdiv__(self, other):
"""Divide."""
other = as_lexpr(other)
if is_zero_lexpr(self):
raise ValueError("Division by zero!")
if is_zero_lexpr(other):
return other
return Div(other, self)
# TODO: Error check types?
__truediv__ = __div__
__rtruediv__ = __rdiv__
__floordiv__ = __div__
__rfloordiv__ = __rdiv__
class LExprOperator(LExpr):
"""Base class for all expression operators."""
sideeffect = False
class LExprTerminal(LExpr):
"""Base class for all expression terminals."""
sideeffect = False
class LiteralFloat(LExprTerminal):
"""A floating point literal value."""
precedence = PRECEDENCE.LITERAL
def __init__(self, value):
"""Initialise."""
assert isinstance(value, (float, complex))
self.value = value
if isinstance(value, complex):
self.dtype = DataType.SCALAR
else:
self.dtype = DataType.REAL
def __eq__(self, other):
"""Check equality."""
return isinstance(other, LiteralFloat) and self.value == other.value
def __float__(self):
"""Convert to float."""
return float(self.value)
def __repr__(self):
"""Representation."""
return str(self.value)
class LiteralInt(LExprTerminal):
"""An integer literal value."""
precedence = PRECEDENCE.LITERAL
def __init__(self, value):
"""Initialise."""
assert isinstance(value, (int, np.number))
self.value = value
self.dtype = DataType.INT
def __eq__(self, other):
"""Check equality."""
return isinstance(other, LiteralInt) and self.value == other.value
def __hash__(self):
"""Hash."""
return hash(self.value)
def __repr__(self):
"""Representation."""
return str(self.value)
class Symbol(LExprTerminal):
"""A named symbol."""
precedence = PRECEDENCE.SYMBOL
def __init__(self, name: str, dtype):
"""Initialise."""
assert isinstance(name, str)
assert name.replace("_", "").isalnum()
self.name = name
self.dtype = dtype
def __eq__(self, other):
"""Check equality."""
return isinstance(other, Symbol) and self.name == other.name
def __hash__(self):
"""Hash."""
return hash(self.name)
def __repr__(self):
"""Representation."""
return self.name
class MultiIndex(LExpr):
"""A multi-index for accessing tensors flattened in memory."""
precedence = PRECEDENCE.SYMBOL
def __init__(self, symbols: list, sizes: list):
"""Initialise."""
self.dtype = DataType.INT
self.sizes = sizes
self.symbols = [as_lexpr(sym) for sym in symbols]
for sym in self.symbols:
assert sym.dtype == DataType.INT
dim = len(sizes)
if dim == 0:
self.global_index: LExpr = LiteralInt(0)
else:
stride = [np.prod(sizes[i:]) for i in range(dim)] + [LiteralInt(1)]
self.global_index = Sum(n * sym for n, sym in zip(stride[1:], symbols))
@property
def dim(self):
"""Dimension of the multi-index."""
return len(self.sizes)
def size(self):
"""Size of the multi-index."""
return np.prod(self.sizes)
def local_index(self, idx):
"""Get the local index."""
assert idx < len(self.symbols)
return self.symbols[idx]
def intersection(self, other):
"""Get the intersection."""
symbols = []
sizes = []
for sym, size in zip(self.symbols, self.sizes):
if sym in other.symbols:
i = other.symbols.index(sym)
assert other.sizes[i] == size
symbols.append(sym)
sizes.append(size)
return MultiIndex(symbols, sizes)
def union(self, other):
"""Get the union.
Note:
Result may depend on order a.union(b) != b.union(a)
"""
symbols = self.symbols.copy()
sizes = self.sizes.copy()
for sym, size in zip(other.symbols, other.sizes):
if sym in symbols:
i = symbols.index(sym)
assert sizes[i] == size
else:
symbols.append(sym)
sizes.append(size)
return MultiIndex(symbols, sizes)
def difference(self, other):
"""Get the difference."""
symbols = []
sizes = []
for idx, size in zip(self.symbols, self.sizes):
if idx not in other.symbols:
symbols.append(idx)
sizes.append(size)
return MultiIndex(symbols, sizes)
def __hash__(self):
"""Hash."""
return hash(self.global_index.__repr__)
class PrefixUnaryOp(LExprOperator):
"""Base class for unary operators."""
def __init__(self, arg):
"""Initialise."""
self.arg = as_lexpr(arg)
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.arg == other.arg
class BinOp(LExprOperator):
"""A binary operator."""
def __init__(self, lhs, rhs):
"""Initialise."""
self.lhs = as_lexpr(lhs)
self.rhs = as_lexpr(rhs)
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.lhs == other.lhs and self.rhs == other.rhs
def __hash__(self):
"""Hash."""
return hash(self.lhs) + hash(self.rhs)
def __repr__(self):
"""Representation."""
return f"({self.lhs} {self.op} {self.rhs})"
class ArithmeticBinOp(BinOp):
"""An artithmetic binary operator."""
def __init__(self, lhs, rhs):
"""Initialise."""
self.lhs = as_lexpr(lhs)
self.rhs = as_lexpr(rhs)
self.dtype = merge_dtypes([self.lhs.dtype, self.rhs.dtype])
class NaryOp(LExprOperator):
"""Base class for special n-ary operators."""
op = ""
def __init__(self, args):
"""Initialise."""
self.args = [as_lexpr(arg) for arg in args]
self.dtype = self.args[0].dtype
for arg in self.args:
self.dtype = merge_dtypes([self.dtype, arg.dtype])
def __eq__(self, other):
"""Check equality."""
return (
isinstance(other, type(self))
and len(self.args) == len(other.args)
and all(a == b for a, b in zip(self.args, other.args))
)
def __repr__(self) -> str:
"""Representation."""
return f"{self.op} ".join(f"{i} " for i in self.args)
def __hash__(self):
"""Hash."""
return hash(tuple(self.args))
class Neg(PrefixUnaryOp):
"""Negation operator."""
precedence = PRECEDENCE.NEG
op = "-"
def __init__(self, arg):
"""Initialise."""
self.arg = as_lexpr(arg)
self.dtype = self.arg.dtype
class Not(PrefixUnaryOp):
"""Not operator."""
precedence = PRECEDENCE.NOT
op = "!"
class Add(ArithmeticBinOp):
"""Add operator."""
precedence = PRECEDENCE.ADD
op = "+"
class Sub(ArithmeticBinOp):
"""Subtract operator."""
precedence = PRECEDENCE.SUB
op = "-"
class Mul(ArithmeticBinOp):
"""Multiply operator."""
precedence = PRECEDENCE.MUL
op = "*"
class Div(ArithmeticBinOp):
"""Division operator."""
precedence = PRECEDENCE.DIV
op = "/"
class EQ(BinOp):
"""Equality operator."""
precedence = PRECEDENCE.EQ
op = "=="
class NE(BinOp):
"""Inequality operator."""
precedence = PRECEDENCE.NE
op = "!="
class LT(BinOp):
"""Less than operator."""
precedence = PRECEDENCE.LT
op = "<"
class GT(BinOp):
"""Greater than operator."""
precedence = PRECEDENCE.GT
op = ">"
class LE(BinOp):
"""Less than or equal to operator."""
precedence = PRECEDENCE.LE
op = "<="
class GE(BinOp):
"""Greater than or equal to operator."""
precedence = PRECEDENCE.GE
op = ">="
class And(BinOp):
"""And operator."""
precedence = PRECEDENCE.AND
op = "&&"
class Or(BinOp):
"""Or operator."""
precedence = PRECEDENCE.OR
op = "||"
class Sum(NaryOp):
"""Sum of any number of operands."""
precedence = PRECEDENCE.ADD
op = "+"
class Product(NaryOp):
"""Product of any number of operands."""
precedence = PRECEDENCE.MUL
op = "*"
class MathFunction(LExprOperator):
"""A Math Function, with any arguments."""
precedence = PRECEDENCE.HIGHEST
def __init__(self, func, args):
"""Initialise."""
self.function = func
self.args = [as_lexpr(arg) for arg in args]
self.dtype = self.args[0].dtype
def __eq__(self, other):
"""Check equality."""
return (
isinstance(other, type(self))
and self.function == other.function
and len(self.args) == len(other.args)
and all(a == b for a, b in zip(self.args, other.args))
)
class AssignOp(BinOp):
"""Base class for assignment operators."""
precedence = PRECEDENCE.ASSIGN
sideeffect = True
def __init__(self, lhs, rhs):
"""Initialise."""
assert isinstance(lhs, LNode)
BinOp.__init__(self, lhs, rhs)
class Assign(AssignOp):
"""Assign operator."""
op = "="
class AssignAdd(AssignOp):
"""Assign add operator."""
op = "+="
class AssignSub(AssignOp):
"""Assign subtract operator."""
op = "-="
class AssignMul(AssignOp):
"""Assign multiply operator."""
op = "*="
class AssignDiv(AssignOp):
"""Assign division operator."""
op = "/="
class ArrayAccess(LExprOperator):
"""Array access."""
precedence = PRECEDENCE.SUBSCRIPT
def __init__(self, array, indices):
"""Initialise."""
# Typecheck array argument
if isinstance(array, Symbol):
self.array = array
self.dtype = array.dtype
elif isinstance(array, ArrayDecl):
self.array = array.symbol
self.dtype = array.symbol.dtype
else:
raise ValueError(f"Unexpected array type {type(array).__name__}")
# Allow expressions or literals as indices
if not isinstance(indices, (list, tuple)):
indices = (indices,)
self.indices = tuple(as_lexpr(i) for i in indices)
# Early error checking for negative array dimensions
if any(isinstance(i, int) and i < 0 for i in self.indices):
raise ValueError("Index value < 0.")
# Additional dimension checks possible if we get an ArrayDecl instead of just a name
if isinstance(array, ArrayDecl):
if len(self.indices) != len(array.sizes):
raise ValueError("Invalid number of indices.")
ints = (int, LiteralInt)
if any(
(isinstance(i, ints) and isinstance(d, ints) and int(i) >= int(d))
for i, d in zip(self.indices, array.sizes)
):
raise ValueError("Index value >= array dimension.")
def __getitem__(self, indices):
"""Handle nested expr[i][j]."""
if isinstance(indices, list):
indices = tuple(indices)
elif not isinstance(indices, tuple):
indices = (indices,)
return ArrayAccess(self.array, self.indices + indices)
def __eq__(self, other):
"""Check equality."""
return (
isinstance(other, type(self))
and self.array == other.array
and self.indices == other.indices
)
def __hash__(self):
"""Hash."""
return hash(self.array)
def __repr__(self):
"""Representation."""
return str(self.array) + "[" + ", ".join(str(i) for i in self.indices) + "]"
class Conditional(LExprOperator):
"""Conditional."""
precedence = PRECEDENCE.CONDITIONAL
def __init__(self, condition, true, false):
"""Initialise."""
self.condition = as_lexpr(condition)
self.true = as_lexpr(true)
self.false = as_lexpr(false)
self.dtype = merge_dtypes([self.true.dtype, self.false.dtype])
def __eq__(self, other):
"""Check equality."""
return (
isinstance(other, type(self))
and self.condition == other.condition
and self.true == other.true
and self.false == other.false
)
def as_lexpr(node):
"""Typechecks and wraps an object as a valid LExpr.
Accepts LExpr nodes, treats int and float as literals.
"""
if isinstance(node, LExpr):
return node
elif isinstance(node, numbers.Integral):
return LiteralInt(node)
elif isinstance(node, numbers.Real):
return LiteralFloat(node)
else:
raise RuntimeError(f"Unexpected LExpr type {type(node)}:\n{node}")
class Statement(LNode):
"""Make an expression into a statement."""
def __init__(self, expr):
"""Initialise."""
self.expr = as_lexpr(expr)
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.expr == other.expr
def __hash__(self) -> int:
"""Hash."""
return hash(self.expr)
def as_statement(node):
"""Perform type checking on node and wrap in a suitable statement type if necessary."""
if isinstance(node, StatementList) and len(node.statements) == 1:
# Cleans up the expression tree a bit
return node.statements[0]
elif isinstance(node, Statement):
# No-op
return node
elif isinstance(node, LExprOperator):
if node.sideeffect:
# Special case for using assignment expressions as statements
return Statement(node)
else:
raise RuntimeError(
f"Trying to create a statement of lexprOperator type {type(node)}:\n{node}"
)
elif isinstance(node, list):
# Convenience case for list of statements
if len(node) == 1:
# Cleans up the expression tree a bit
return as_statement(node[0])
else:
return StatementList(node)
elif isinstance(node, Section):
return node
else:
raise RuntimeError(f"Unexpected Statement type {type(node)}:\n{node}")
class Annotation(Enum):
"""Annotation."""
fuse = 1 # fuse loops in section
unroll = 2 # unroll loop in section
licm = 3 # loop invariant code motion
factorize = 4 # apply sum factorization
class Declaration(Statement):
"""Base class for all declarations."""
def __init__(self, symbol):
"""Initialise."""
self.symbol = symbol
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.symbol == other.symbol
def is_declaration(node) -> bool:
"""Check if a node is a declaration."""
return isinstance(node, VariableDecl) or isinstance(node, ArrayDecl)
class Section(LNode):
"""A section of code with a name and a list of statements."""
def __init__(
self,
name: str,
statements: list[LNode],
declarations: Sequence[Declaration],
input: Optional[list[Symbol]] = None,
output: Optional[list[Symbol]] = None,
annotations: Optional[list[Annotation]] = None,
):
"""Initialise."""
self.name = name
self.statements = [as_statement(st) for st in statements]
self.annotations = annotations or []
self.input = input or []
self.declarations = declarations or []
self.output = output or []
for decl in self.declarations:
assert is_declaration(decl)
if decl.symbol not in self.output:
self.output.append(decl.symbol)
def __eq__(self, other):
"""Check equality."""
attributes = ("name", "input", "output", "annotations", "statements")
return isinstance(other, type(self)) and all(
getattr(self, name) == getattr(other, name) for name in attributes
)
class StatementList(LNode):
"""A simple sequence of statements."""
def __init__(self, statements):
"""Initialise."""
self.statements = [as_statement(st) for st in statements]
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.statements == other.statements
def __hash__(self) -> int:
"""Hash."""
return hash(tuple(self.statements))
def __repr__(self):
"""Representation."""
return f"StatementList({self.statements})"
class Comment(Statement):
"""Line comment(s) used for annotating the generated code with human readable remarks."""
def __init__(self, comment):
"""Initialise."""
assert isinstance(comment, str)
self.comment = comment
def __eq__(self, other):
"""Check equality."""
return isinstance(other, type(self)) and self.comment == other.comment
def commented_code_list(code, comments):
"""Add comment to code list if the list is not empty."""
if isinstance(code, LNode):
code = [code]
assert isinstance(code, list)
if code:
if not isinstance(comments, (list, tuple)):
comments = [comments]
comments = [Comment(c) for c in comments]
code = comments + code
return code
# Type and variable declarations
class VariableDecl(Declaration):
"""Declare a variable, optionally define initial value."""
def __init__(self, symbol, value=None):
"""Initialise."""
assert isinstance(symbol, Symbol)
assert symbol.dtype is not None
self.symbol = symbol
if value is not None:
value = as_lexpr(value)
self.value = value
def __eq__(self, other):
"""Check equality."""
return (
isinstance(other, type(self))
and self.typename == other.typename
and self.symbol == other.symbol
and self.value == other.value
)
class ArrayDecl(Declaration):
"""A declaration or definition of an array.
Note that just setting values=0 is sufficient to initialize the
entire array to zero.
Otherwise use nested lists of lists to represent multidimensional
array values to initialize to.
"""
def __init__(self, symbol, sizes=None, values=None, const=False):
"""Initialise."""
assert isinstance(symbol, Symbol)
self.symbol = symbol
assert symbol.dtype
if sizes is None:
assert values is not None
sizes = values.shape
if isinstance(sizes, int):
sizes = (sizes,)
self.sizes = tuple(sizes)
if values is None:
assert sizes is not None
# NB! No type checking, assuming nested lists of literal values. Not applying as_lexpr.
if isinstance(values, (list, tuple)):
self.values = np.asarray(values)
else:
self.values = values
self.const = const
self.dtype = symbol.dtype
def __eq__(self, other):